/*
*               __    _ __              __  __           _    _______
*              / /   (_) /_  ________  / /_/ /_____     | |  / /__  /
*             / /   / / __ \/ ___/ _ \/ __/ __/ __ \    | | / / /_ <
*            / /___/ / /_/ / /  /  __/ /_/ /_/ /_/ /    | |/ /___/ /
*           /_____/_/_.___/_/   \___/\__/\__/\____/     |___//____/
*
*           2FluidCreative (AB) - 09/09/08
*/

/* Embed Flash objects using SWFObject
*  #1 LaunchPad, Front cover display & ExpressInstall
*  #2 Main Libretto */

/* #1 */ if($('launch') != null)          { swfobject.registerObject("frontCover", "9.0.0"); }
/* #2 */ if($('librettoWrapper') != null) { swfobject.registerObject("LibrettoSWF", "9.0.0", "/flash/expressInstall.swf"); }

Libretto={
	init:function() {
		if($('librettoWrapper') != null) { // Run on main Libretto page only
			// Flash's Stage.onresize is flakey - double-click on title bar (max/min) does not register as a resize event
			Event.observe(window, 'resize', function() {
				$SWF('LibrettoSWF').resizeHandler();
			});
		}
		Libretto.PDFDownload();
	},

	buySub:function(url) {
		if(confirm("Sorry, only users who have purchased this issue may view all pages. \nPress OK to close this window and buy a copy now.")) {
			opener.location=url;
			self.close();
		}
	},

	Grid:{
		fetch:function() {
			var url = "/xhr/grid.xhr.php";
			new Ajax.Request(url, { method:'get', onComplete: function(r) {
				var response = r.responseText;
				if(response != "ERROR") {
					$SWF('LibrettoSWF').Grid_load($JSON(response));
				}
			}});
		},
		buy:function(url) {
			if(confirm("Sorry, only users who have purchased this issue may view all pages. \nPress OK to close this window and buy a copy now.")) {
				opener.location=url;
				self.close();
			} else {
				$SWF('LibrettoSWF').Grid_hide();
			}
		}
	},

	BackIssuesGrid:{
		fetch:function() {
			var url = "/xhr/backIssues.xhr.php";
			new Ajax.Request(url, { method:'get', onComplete: function(r) {
				var response = r.responseText;
				if(response != "ERROR") {
					$SWF('LibrettoSWF').BackIssuesGrid_load($JSON(response));
				} else {
					if(confirm("Sorry, we could not find any back issues. Press Ok to exit or cancel to try again")) Libretto.BackIssuesGrid.fetch();
				}
			}});
		},
		buy:function(url) {
			if(confirm("Sorry, you do not seem to have a subscription to this issue. \nPress OK to close this window and buy a copy now.")) {
				opener.location=url;
				self.close();
			} else {
				$SWF('LibrettoSWF').BackIssuesGrid_hide();
			}
		}
	},

	URLs:{

		startPage:null,
		startTitle:null,

		init:function() {
			var loc = window.location.toString();
			if(loc.indexOf("#") != -1) {
				var fragment = loc.split("#")[1];
				// Goto page #page-19
				if(fragment.indexOf("page-") != -1) {
					var pn = fragment.split("-")[1];
					this.startPage = pn;
				}
			}

			// IE6 has nasty habit of setting window.title as the url fragment
			this.startTitle = document.title;
		},

		load:function() {
			if(this.startPage != null) $SWF('LibrettoSWF').goto(this.startPage-1,true); // Jump straight to page. Book counts from 0
		},

		set:function(pn) {
			pn = pn+1; // So we don't have page 0 etc
			var loc = window.location.toString();
			window.location = (loc.indexOf("#") != -1) ? loc.split("#")[0]+"#page-"+pn : loc+"#page-"+pn;

			// Reset window title if changed to fragment
			if(Libretto.URLs.startTitle != null) document.title = Libretto.URLs.startTitle;
		}
	},

	stats:{

		issue:null,

		init:function() {
			this.issue = document.title;
		},

		add:function(n) {
			GA.add('/'+Libretto.stats.issue+'/Page '+n);
		},

		addZoomLarge:function(n) {
			GA.add('/Zoom-Large/'+Libretto.stats.issue+'/Page '+n);
		},

		addZoomMed:function(n) {
			GA.add('/Zoom-Medium/'+Libretto.stats.issue+'/Page '+n);
		}
	},

	PDFDownload:function() {
		$$('a.PDF-Download').each(function(a) {
			a.observe('click', function() {
				var id    = this.href.split("=")[1];
				if(isNaN(id)) id = 0;
				GA.add('/PDF Download/'+id+'/');
			}.bindAsEventListener(a));
		});
	}
};

Search={
	keyword:function(term) {

		var url = "/xhr/keyword.xhr.php?q="+escape(term);
		new Ajax.Request(url, { method:'get', onComplete: function(r) {
			var response = r.responseText;
			if(response != "ERROR") {
				$SWF('LibrettoSWF').Grid_setFound($JSON(response));
				GA.add("/Search/"+term);
			} else {
				alert("Sorry, no results found for "+term);
			}
		}});
	}
};

// Google Analytics
GA={
	add:function(loc) {
		if(pageTracker && pageTracker._trackPageview) {
			pageTracker._trackPageview(loc);
		}
	}
};

function adLinkGo(url) {
	// Add protocol
	desc = url;
	linkParts = url.split("_");
	if(linkParts[0] != "mailto" && linkParts[0] != "http" && linkParts[0] != "https" && linkParts[0] != "ftp") {
		url = "http://"+url;
	} else {
		if(linkParts[0] == "mailto") {
			url = "mailto:"+linkParts[1];
		} else {
			url = linkParts[0] + "://" + linkParts[1];
		}
	}
	adLink(url, desc);
}

function adLink(url, desc) {
	GA.add("/Ad-Link/"+desc);
	var adwin = window.open(url);
	adwin.focus();
}

function productZoomImage(url) {

	var params  = 'width=200';
	params += ', height=100';
	params += ', top=0, left=0'
	params += ', fullscreen=yes';

	var newwin=window.open("/productPreview.php?url="+escape(url),"ProductPreview",params);
	if(window.focus) {newwin.focus()}
}

function LogOut() {
	opener.location="/?logout=true";
	self.close();
}

function getPDF(id) {
	GA.add('/PDF Download/'+id+'/');
	window.location ="/downloadPDF.php?id="+id;
}

Launch={

	init:function() {
		if($('launch') != null) { // on launch pad page?
			$$('a.launchIssue').each(function(a) { // launch popup on each click
				a.observe('click', function(e) {
					Event.stop(e);
					Launch.now();
				});
			});
		}
	},

	now:function() {
		// Find a link containing the url as the rel attribute
		if($$('a.launchIssue').length > 0) {
			var l = $$('a.launchIssue')[0];
			if(!l.rel.blank()) {
				Launch.pop(l.rel);
			} else {
				Launch.retry();
			}
		} else {
			Launch.retry();
		}
	},

	pop:function(loc) {
		var playerVersion = swfobject.getFlashPlayerVersion();
		var majorVersion = playerVersion.major; // access the major


		if(majorVersion < 9) {
			if(confirm("Libretto requires the latest version of Adobe Flash Player. Do you wish to download this now?")) window.location="http://www.adobe.com/go/getflashplayer";
			return;
		}

		var dims = Utility.dimensions();

		var params  = 'width='+dims['x'];
		params += ', height='+dims['y'];
		params += ', top=0, left=0'
		params += ', fullscreen=yes';

		var newwin=window.open(loc,"LibrettoPop",params);
		if(window.focus) {newwin.focus()}

		/*
		window.openCentered(loc,
							name,
							{
								width:       dims['x'],
								height:      dims['y'],
								directories: false,
								fullscreen:  false,
								location:    false,
								menubar:     false,
								resizable:   false,
								scrollbars:  false,
								status:      false,
								toolbar:     false
							}
						);
		*/
	},

	retry:function() {
		if(confirm("There has been a problem launching this issue of Libretto.\nPress OK to try again.")) Launch.now();
	}
};


SendToAFriend={
	send:function(emailData) {
		/* Record Stats in Analytics - /Send-to-a-Friend/[SENDERS EMAIL] */
		GA.add('/Send-to-a-Friend/'+emailData.yourEmail);

		var url = "/xhr/sendToAFriend.php";
		var qs  = "?yourEmail="+emailData.yourEmail+"&yourName="+emailData.yourName+"&friendsEmail="+emailData.friendsEmail+"&friendsName="+emailData.friendsName+"&subscribe="+emailData.subscribe;
		qs += "&url="+escape(window.location.toString());
		new Ajax.Request(url, { method:'post', parameters:qs, onComplete: function(r) {
			var response = r.responseText;
			$SWF('LibrettoSWF').TabSendToAFriend_reply(response);
		}});
	}
};

LoginBar={
	check:function() {
		var url = "/xhr/loginCheck.xhr.php";
		new Ajax.Request(url, { method:'post', onComplete: function(r) {
			var response = r.responseText;
			if(response != 3) {
				var status = response.split("|")[0];
				var link   = response.split("|")[1];
				$SWF('LibrettoSWF').Login_set(status,link);
			} else {
				$SWF('LibrettoSWF').Login_set(3,null);
			}
		}});
	},
	closeAndGo:function(link) {
		if(confirm("This window will close and you will be taken to the Subscription purchase page. Press OK to continue")) {
			opener.location=link;
			self.close();
		}
	},
	forgotPassword:function() {
		if(confirm("This window will close and you will be taken to the password reset page. Press OK to continue")) {
			opener.location="/reset-password/";
			self.close();
		}
	},
	changePassword:function() {
		opener.location="/change-password/";
		self.close();
	},
	login:function(username, password) {
		var qs = "remember_me=1&dont_log=true&login=true&username="+username+"&password="+password;
		var url = "/xhr/login.xhr.php";
		new Ajax.Request(url, { method:'post', parameters:qs, onComplete: function(r) {
			var response = r.responseText;
			if(response == "SUCCESS") {
				location.reload(true);
			} else {
				var err = "Invalid username or password. Press OK to try again or cancel to go the Forgotten Password page.";
				if(!confirm(err)) {
					opener.location='/reset-password/';
					self.close();
				} else {
					$SWF('LibrettoSWF').Loading_hide();
				}
			}
		}});
	}
};

ContentLinks={
	allLinks:null,
	autoLoad:false,

	fetch:function() {
		var url = "/xhr/contents.xhr.php";
		new Ajax.Request(url, { method:'get', onComplete: function(r) {
			var response = r.responseText;
			ContentLinks.allLinks = (response != "ERROR") ? $JSON(response) : false;
			if(ContentLinks.autoLoad) ContentLinks.load();
		}});
	},

	load:function() {
		if(ContentLinks.allLinks != null) {
			$SWF('LibrettoSWF').contentsLoad(ContentLinks.allLinks);
		} else {
			ContentLinks.autoLoad = true;
			ContentLinks.fetch();
		}
	}
}

Utility={
	dimensions:function() {
		return {"x":screen.width, "y":screen.height};
	}
};


// Runs the following as soon as the DOM is ready (before window.onload)
Event.onDOMReady(function() {
	Libretto.URLs.init();
	Libretto.stats.init();
	Libretto.init();
	Launch.init();

	//if($('librettoWrapper') != null) ContentLinks.fetch();

	// IE6 likes to leave noscript styles lying about so hide them all
	$$('noscript').each(function(ns) {
		ns.hide();
	});
});

function $SWF(swfId) {
	/*
	if (typeof(window.document[swfId]) != 'undefined') {
		return window.document[swfId];
	} else if (typeof(document.getElementById(swfId)) != 'undefined') {
		return document.getElementById(swfId);
	} else if (typeof(window[swfId]) != 'undefined') {
		return window[swfId];
	}
	*/
	/* SWFObject has its own function for getting a refrence to the
	*  Flash file, this took alot of head-->table to figure out! */
	return swfobject.getObjectById(swfId);
}

function $JSON(str) {
	return str.evalJSON(true);
}

/* Error loading Libretto XML Config file */
function XMLCheck_Error(msg) {
	var err = "Sorry, there has been an error!\n\n"+msg+"\nPress OK to try again or cancel to exit.";
	if(confirm(err)) {
		location.reload(true);
	} else {
		self.close();
	}
}