// flag indicating if the site has been initialized
var inited = false;

// current primary, secondary and tertiary content IDs
var pid = 0;
var sid = 0;
var tid = 0;

// previous primary, secondary and tertiary content IDs
var pidPrev;
var sidPrev;
var tidPrev;

// Scrollbar instance references
var outerScrollbar;
var innerScrollbar;

// browser flags
var ie = navigator.appName.indexOf("Microsoft") != -1;
var safari = navigator.userAgent.indexOf("Safari") != -1;

// URLs for AJAX calls
var contentUrls = ["ajax.home.php",
				   "ajax.info.php",
				   "ajax.releases.php",
				   "ajax.shows.php",
				   "ajax.images.php",
				   "ajax.video.php",
				   "ajax.podcast.php",
				   "ajax.press.php",
				   "ajax.shop.php",
				   "ajax.contact.php"];

// page titles
var contentTitles = ["",
					 "Info",
					 "Releases",
					 "Shows",
					 "Images",
					 "Video",
					 "Podcast",
					 "Press",
					 "Shop",
					 "Contact"];


function init () {
	// determine if specific content is being linked to
	if (location.hash.length > 1) {
		// extract the content IDs from the hash
		var ids = location.hash.substr(1).split(".");
		switch (ids.length) {
			case 3: tid = Number(ids[2]);
			case 2: sid = Number(ids[1]);
			case 1: pid = Number(ids[0]);
		}
	}
	// setup the news
	setupNews();
	// load content
	go(pid, sid, tid);
}

/* PUBLIC FUNCTIONS */

function go (p, s, t, fromMenu) {
	if (p == undefined) p = 0;
	if (s == undefined) s = 0;
	if (t == undefined) t = 0;
	if (fromMenu == undefined) fromMenu = false;
	// cancel if already viewing specified content
	if (p == pid && s == sid && t == tid && inited) return;
	// record previous IDs
	pidPrev = pid;
	sidPrev = sid;
	tidPrev = tid;
	// store new IDs
	pid = p;
	sid = s;
	tid = t;
	// alter the menu, if applicable
	if (!fromMenu) {
		try { getSwfRef('menu').select(pid, true); }
		catch (e) {}
	}
	// load the content and update the URL/title
	getContent();
	updateURL();
	// track the request
	track(pid, sid, tid);
	// flip the flag
	inited = true;
}

function goImage (s) {
	// record previous IDs
	pidPrev = pid;
	sidPrev = sid;
	tidPrev = tid;
	// store new IDs
	pid = 4;
	sid = s;
	tid = 0;
	// change the classes for the thumbnails
	var thumbNodes = $("images_thumbs").childNodes;
	for (var i=0; i<thumbNodes.length; i++) {
		var thumbNode = thumbNodes[i];
		thumbNode.className = (i == (s - 1)) ? "kl btn tn selected" : "kl btn tn";
	}
	// load the content and update the URL/title
	getImage();
	updateURL();
	// track the request
	track(pid, sid, tid);
}

function goVideo (s) {
	// record previous IDs
	pidPrev = pid;
	sidPrev = sid;
	tidPrev = tid;
	// store new IDs
	pid = 5;
	sid = s;
	tid = 0;
	// change the classes for the thumbnails
	var thumbNodes = $("video_thumbs").childNodes;
	for (var i=0; i<thumbNodes.length; i++) {
		var thumbNode = thumbNodes[i];
		thumbNode.className = (i == (s - 1)) ? "kl btn tn selected" : "kl btn tn";
	}
	// load the content and update the URL/title
	getVideo();
	updateURL();
	// track the request
	track(pid, sid, tid);
}

/* PRIVATE FUNCTIONS AND CALLBACKS */

function onContentLoaded (ajax) {
	// convert the response to a Javascript object
	var json = getJSON(ajax);
	// insert the html into the content area
	var c = $("content");
	c.innerHTML = json.html;
	// determine if SWFs area to be inserted
	if (json.swf) {
		for (var i=0; i<json.swf.length; i++) {
			var swf = json.swf[i];
			var f = new SWFObject(swf.url, swf.swfId, swf.w, swf.h, swf.version, swf.bgColor);
			f.addParam("menu", "false");
			f.addParam("quality", "best");
			f.addParam("salign", "tl");
			f.addParam("scale", "noscale");
			f.addParam("allowscriptaccess", "always");
			f.addParam("allowfullscreen", "true");
			if (swf.vars != undefined) {
				for (var j=0; j<swf.vars.length; j++) {
					f.addVariable(swf.vars[j][0], swf.vars[j][1]);
				}
			}
			f.write(swf.targetId);
		}
	}
	// determine inner scrolling
	if (json.sbar) {
		if ($(json.sbar.targetId).scrollHeight > json.sbar.height) {
			$("sbar_inner").style.display = "block";
			innerScrollbar = new Scrollbar(json.sbar.targetId, "sbar_inner_track", "sbar_inner_thumb", "sbar_inner_thumbimg", json.sbar.height);
		}
	}
	// determine outer scrolling
	if (c.scrollHeight > 325) {
		c.style.width = 495;
		$("sbar_outer").style.display = "block";
		outerScrollbar = new Scrollbar("content", "sbar_outer_track", "sbar_outer_thumb", "sbar_outer_thumbimg", 325);
		outerScrollbar.logTarget = $("sblogInner");
	}
	// resume the audio
	try {
		if (pid == 5) getSwfRef('aplayer').pause();
		else getSwfRef('aplayer').resume();
	} catch (e) {}
	// determine if the show nav needs to be alters
	if (pid == 3) {
		setupShowNav(json);
	}
	// fix PNGs, if IE
	if (ie) correctPng();
}

function getContent () {
	// remove the scrollbar & restore the content area width
	outerScrollbar = null;
	innerScrollbar = null;
	$("sbar_outer").style.display = "none";
	$("sbar_outer_thumb").style.top = 0;
	$("content").style.width = 510;
	$("content").scrollTop = 0;
	// hide the shows nav, if applicable
	if (pid != 3) {
		$("shows_nav").style.visibility = "hidden";
		$("shows_prev").style.visibility = "hidden";
		$("shows_next").style.visibility = "hidden";
	}
	// set the loading screen
	ringSwf.write("content");
	// start the AJAX call
	var url = contentUrls[pid];
	var params = ["sid=" + sid, "tid=" + tid];
	var ajax = new Ajax.Request(
							url,
							{ method: "get",
							  parameters: params.join("&"),
							  onComplete: onContentLoaded
							}
							);
}

function onImageLoaded (ajax) {
	// convert the response to a Javascript object
	var json = getJSON(ajax);
	// insert the html into the content area
	var c = $("images_detail");
	c.innerHTML = json.html;
}

function getImage () {
	// start the AJAX call
	var url = "ajax.images.sub.php";
	var params = ["sid=" + sid, "tid=" + tid];
	var ajax = new Ajax.Request(
							url,
							{ method: "get",
							  parameters: params.join("&"),
							  onComplete: onImageLoaded
							}
							);
}

function onVideoLoaded (ajax) {
	// convert the response to a Javascript object
	var json = getJSON(ajax);
	// insert the html into the content area
	var c = $("video_detail");
	c.innerHTML = json.html;
	// determine if SWFs area to be inserted
	if (json.swf) {
		for (var i=0; i<json.swf.length; i++) {
			var swf = json.swf[i];
			var f = new SWFObject(swf.url, swf.swfId, swf.w, swf.h, swf.version, swf.bgColor);
			f.addParam("menu", "false");
			f.addParam("quality", "best");
			f.addParam("salign", "tl");
			f.addParam("scale", "noscale");
			f.addParam("allowscriptaccess", "always");
			f.addParam("allowfullscreen", "true");
			if (swf.vars != undefined) {
				for (var j=0; j<swf.vars.length; j++) {
					f.addVariable(swf.vars[j][0], swf.vars[j][1]);
				}
			}
			f.write(swf.targetId);
		}
	}
	// insert the html into the content area
	// var c = $("video_detail_text");
	// c.innerHTML = json.html;
}

function getVideo () {
	// start the AJAX call
	var url = "ajax.video.sub.php";
	var params = ["sid=" + sid, "tid=" + tid];
	var ajax = new Ajax.Request(
							url,
							{ method: "get",
							  parameters: params.join("&"),
							  onComplete: onVideoLoaded
							}
							);
}

/* NEWSFEED FUNCTIONS */

function setupNews () {
	var next = $("news_next");
	var prev = $("news_prev");
	next.onmouseover = function () { hover(this); }
	next.onmouseout = function () { hover(this); }
	prev.onmouseover = function () { hover(this); }
	prev.onmouseout = function () { hover(this); }
	getNews();
}

function onNewsLoaded (ajax) {
	// convert the response to a Javascript object
	var json = getJSON(ajax);
	// insert the html into the content area
	var c = $("news_detail");
	c.innerHTML = json.html;
	// update the arrows
	var next = $("news_next");
	var prev = $("news_prev");
	if (json.next != 0) {
		next.onclick = function () { getNews(json.next); }
		next.style.visibility = 'visible';
	} else {
		next.style.visibility = 'hidden';
	}
	if (json.prev != 0) {
		prev.onclick = function () { getNews(json.prev); }
		prev.style.visibility = 'visible';
	} else {
		prev.style.visibility = 'hidden';
	}
	// fix PNGs, if IE
	if (ie) correctPng();
}

function getNews (nid) {
	if (nid == undefined) nid = 1;
	// start the AJAX call
	var url = "ajax.news.php";
	var params = ["nid=" + nid];
	var ajax = new Ajax.Request(
							url,
							{ method: "get",
							  parameters: params.join("&"),
							  onComplete: onNewsLoaded
							}
							);

}

function setupShowNav (json) {
	$("shows_nav").style.visibility = "visible";
	var next = $("shows_next");
	var prev = $("shows_prev");
	next.onmouseover = function () { hover(this); }
	next.onmouseout = function () { hover(this); }
	prev.onmouseover = function () { hover(this); }
	prev.onmouseout = function () { hover(this); }
	if (json.next != -1) {
		next.onclick = function () { go(3, json.next); }
		next.style.visibility = 'visible';
	} else {
		next.style.visibility = 'hidden';
	}
	if (json.prev != -1) {
		prev.onclick = function () { go(3, json.prev); }
		prev.style.visibility = 'visible';
	} else {
		prev.style.visibility = 'hidden';
	}
}

function playTrack (n) {
	try { getSwfRef('aplayer').playTrackById(n); }
	catch (e) {}
}

/* MAILING LIST FUNCTIONS */

function mailList () {
	var ml = $("maillist");
	var html = '';
	html += '<input type="text" id="maillist_email" value="e-mail" onfocus="if(this.value==\'e-mail\')this.value=\'\';" onblur="if(!this.value.length)this.value=\'e-mail\';" align="baseline">&nbsp;\n';
	html += '<img src="img/maillist_cancel0.gif" align="baseline" width="42" height="9" border="0" onmouseover="hover(this);" onmouseout="hover(this);" onclick="mailListCancel();" title="cancel">&nbsp;&nbsp;\n';
	html += '<img src="img/maillist_send0.gif" align="baseline" width="34" height="9" border="0" onmouseover="hover(this);" onmouseout="hover(this);" onclick="mailListSend();" title="send">';
	ml.innerHTML = html;		
}

function mailListSend () {
	var ml = $("maillist");
	var email = $("maillist_email").value;
	if (!validateEmail(email)) {
		alert('Hmm.. please check that your email address is valid!');
		return;
	}
	// start the AJAX call
	var url = "ajax.maillist.php";
	var params = ["email=" + email];
	var ajax = new Ajax.Request(
							url,
							{ method: "get",
							  parameters: params.join("&")
							}
							);
	ml.innerHTML = '<img src="img/maillist_thankyou.gif" width="51" height="9" border="0">';
	setTimeout(mailListCancel, 2500);
}

function mailListCancel () {
	var ml = $("maillist");
	var html = '';
	html += '<img src="img/maillist_signup0.gif" ';
	html += 'width="138" height="9" border="0" ';
	html += 'onmouseover="hover(this);" ';
	html += 'onmouseout="hover(this);" ';
	html += 'onclick="mailList();" ';
	html += 'title="sign up for our mailing list">';
	ml.innerHTML = html;
}

/* IMAGE ZOOMING & GMAP FUNCTIONS */

// window reference vars
var oirPopupWindow;

function oirPopupClose () { oirPopupWindow = null; }

function onZoomImageLoaded (ajax) {
	var json = getJSON(ajax);
	// pad the width and height
	var w = json.w + 20;
	var h = json.h + 35;
	// determine centering
	var x = 0;
	var y = 0;
	if (screen) {
		var aw = screen.availWidth;
		var ah = screen.availHeight;
		x = Math.round((aw - w) / 2);
		y = Math.round((ah - h) / 2);
	}
	// close existing popup
	if (oirPopupWindow) {
		oirPopupWindow.close();
		oirPopupWindow = null;
	}
	// build the url
	var url = "zoomimage.php?file=" + json.img + "&title=" + escape(json.title) + "&w=" + json.w  + "&h=" + json.h;
	var params = "";
	params += "resizable=no,width="+w+",height="+h+",innerwidth="+w+",innerheight="+h+",";
	params += "top="+y+",left="+x+","
	params += "scrollbars=no,toolbar=no,location=no,status=no";
	oirPopupWindow = window.open(url, "oir_popup", params);
	oirPopupWindow.focus();
}

function zoomImage (p, s) {
	// start the AJAX call
	var url = "ajax.images.zoom.php";
	var params = ["pid=" + p, "sid=" + s];
	var ajax = new Ajax.Request(
							url,
							{ method: "get",
							  parameters: params.join("&"),
							  onComplete: onZoomImageLoaded
							}
							);
}

function onVenueMapLoaded (ajax) {
	var json = getJSON(ajax);
	// pad the width and height
	var w = 470;
	var h = 485;
	// determine centering
	var x = 0;
	var y = 0;
	if (screen) {
		var aw = screen.availWidth;
		var ah = screen.availHeight;
		x = Math.round((aw - w) / 2);
		y = Math.round((ah - h) / 2);
	}
	// close existing popup
	if (oirPopupWindow) {
		oirPopupWindow.close();
		oirPopupWindow = null;
	}
	// build the url
	var url = "venuemap.php?vn=" + escape(json.venueName) + "&va=" + escape(json.venueAddr);
	var params = "";
	params += "resizable=no,width="+w+",height="+h+",innerwidth="+w+",innerheight="+h+",";
	params += "top="+y+",left="+x+","
	params += "scrollbars=no,toolbar=no,location=no,status=no";
	oirPopupWindow = window.open(url, "oir_popup", params);
	oirPopupWindow.focus();
}

function venueMap (s) {
	// start the AJAX call
	var url = "ajax.shows.map.php";
	var params = ["sid=" + s];
	var ajax = new Ajax.Request(
							url,
							{ method: "get",
							  parameters: params.join("&"),
							  onComplete: onVenueMapLoaded
							}
							);
}

/* UTILITY FUNCTIONS */

function updateURL () {
	// add the hash to the location bar
	var hash = [];
	if (pid) hash.push(pid);
	if (pid && sid) hash.push(sid);
	if (pid && sid && tid) hash.push(tid);
	if (!ie && !safari && hash.length) {
		// IE & Safari fuck up when the href is set with a hash multiple times.
		// Fuck IE. Fuck Safari.
		location.href = "#" + hash.join(".");		
	}
	// alter the page title
	document.title = "Off the International Radar";
	if (pid > 0) {
		document.title += " | " + contentTitles[pid];
	}
}

function getJSON (ajax) {
	// converts the JSON content of the AJAX object's 'responseText'
	// property to a Javascript object.
	var json = eval('(' + ajax.responseText + ')');
	return json;
}

function getSwfRef (id) {
	return ie ? window[id] : document[id];
}

function validateEmail (e) {
	var ePatt = /^[\w-\.]+@([\w-\.]+\.)+[a-z]{2,3}$/i
	return ePatt.test(e);
}

function hover (img) {
	var src = img.src;
	var dot = ".";
	var pos = src.lastIndexOf(dot);
	var state = Number(src.substr(pos - 1, 1));
	state = (state == 0) ? 1 : 0;
	src = src.substr(0, pos - 1) + state.toString() + src.substr(pos);
	img.src = src;
}

function download (file) {
	if (!file || !file.length) return;
	location.href = "download.inc.php?file=" + file;
	// track the request
	track(100, null, null, file);
}

function onTrackerLoaded (ajax) {
	var json = getJSON(ajax);
	urchinTracker(json.url);
}

function track (p, s, t, f) {
	if (p == undefined) p = 0;
	if (s == undefined) s = 0;
	if (t == undefined) t = 0;
	if (f == undefined) f = '';
	// start the AJAX call
	var url = "ajax.tracker.php";
	var params = ["pid=" + p, "sid=" + s, "tid=" + t, "file=" + f];
	var ajax = new Ajax.Request(
							url,
							{ method: "get",
							  parameters: params.join("&"),
							  onComplete: onTrackerLoaded
							}
							);
}

