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

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

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

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

// set section names
var sections = ["News", "About", "Directors", "Composers", "Contact", "Resistor"];

// save displayed project ids
var projectIds = [];

// scrolling tween object
var scrollTw = { s:0, smax:16, ys:0, yd:0, i:null };

// set ajax page names
var ajaxUrls = [];
	ajaxUrls[1] = "ajax.news.php";
	ajaxUrls[2] = "ajax.about.php";
	ajaxUrls[3] = "ajax.director.php";
	ajaxUrls[4] = "ajax.director.php";
	ajaxUrls[5] = "ajax.contact.php";
	ajaxUrls[6] = "ajax.resistor.php";

function init (p, s, t, q) {
	go(p, s, t, q, false);
	if (useFlash) insertMenu();
}

function go (p, s, t, q, fromMenu, event) {
	// set values for unsent parameters
	if (p == undefined) p = 0;
	if (s == undefined) s = 0;
	if (t == undefined) t = 0;
	if (q == undefined) q = 0;
	if (fromMenu == undefined) fromMenu = false;
	// prevent the event from propagating to other handlers, if applicable
	if (event != undefined) {
		event.cancelBubble = true;
		event.stopPropagation();
	}
	// cancel if there is no change
	if (p == pid && s == sid &&
		t == tid && q == qid && inited) return false;
	// record previous IDs
	pidPrev = pid;
	sidPrev = sid;
	tidPrev = tid;
	qidPrev = qid;
	// set new IDs
	pid = p;
	sid = s;
	tid = t;
	qid = q;
	// determine the section label
	var label = ((pid==3||pid==4) && sid) ? directors[sid].name : sections[pid - 1];
	// modify either the Flash or HTML menus, depending on the useFlash flag
	if (useFlash) {
		// attempt to modify the Flash menu
		try {
			var menu = getPluginRef("menu");
			menu.setLabel(label);
			if (!fromMenu) {
				menu.select(pid, sid, tid, qid, true);
			}
		}
		catch (e) {}
	} else {
		// attempt to modify the HTML menu
		try {$("menu_label").update(label); }
		catch (e) {}
	}
	// get the content
	getContent();
	// track the request
	track();
	// flip the flag
	inited = true;
	// return value to prevent link hrefs from firing
	return false;
}

function onContentLoaded (ajax) {
	var json = getJSON(ajax);
	insertHTML(json);
	insertSWFs(json);
	insertQTs(json);

	if ((pid==3||pid==4) && tid==0) {
		if (json.data) {
			setupProjectList(json.data);
		}
	}

	if (ie) correctPng();
}

function getContent (url, fn, p, el) {
	// set defaults for parameters, if not specified
	if (!url) url = ajaxUrls[pid];
	if (!fn) fn = onContentLoaded;
	if (!p) p = [];
	if (!el) el = "content";
	// stop the currently playing QT, if applicable; this addresses
	// an issue in Safari where the current QT's audio continues to
	// play when a new QT is loaded, overlapping the audio.
	if (safari) {
		try { getPluginRef("qt").Stop(); }
		catch (e) {}
	}
	var params = ["pid=" + pid,
				  "sid=" + sid,
				  "tid=" + tid,
				  "qid=" + qid,
				  "el=" + el].concat(p);
	var ajax = new Ajax.Request(url,
								{ method: "get",
								  parameters: params.join("&"),
								  onComplete: fn
								}
								);
}

function scrollToTop (fn) {
	var y = 156;
	//if (window.scrollY < y) return;
	function easeOut (t, b, c, d) { return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;}
	function tween () {
		scroll(0, easeOut(scrollTw.s++, scrollTw.ys, scrollTw.yd, scrollTw.smax));
		if (scrollTw.s > scrollTw.smax) {
			clearInterval(scrollTw.i);
			fn();
		}
	}
	clearInterval(scrollTw.i);
	scrollTw.s = 0;
	scrollTw.ys = window.scrollY;
	scrollTw.yd = -(window.scrollY - y);
	scrollTw.i = setInterval(tween, 25);
}

function getNewsByPage (page) {
	getContent("ajax.news.php", null, ["pg=" + page]);
}

function getNewsByYear (year) {
	getContent("ajax.news.php", null, ["yr=" + year]);
}

function getProjectListPage (page, col, dir) {
	getContent("ajax.director.list.php",
			   null,
			   ["pg=" + page, "col=" + col, "dir=" + dir],
			   "list"); 
}

function getProject (p, s, q) {
	// record the new qid
	qid = q;
	// toggle row behaviours
	for (var i=0; i<projectIds.length; i++) {
		var e = $("project[" + projectIds[i] + "]");
		if (qid == projectIds[i]) {
			e.addClassName("selected");
			e.onmouseover = null;
			e.onmouseout = null;
			e.onclick = null;
		} else {
			e.dirId = null;
			e.projId = projectIds[i];
			e.removeClassName("selected");
			e.onmouseover = function () { this.addClassName("hover"); }
			e.onmouseout = function () { this.removeClassName("hover"); }
			e.onclick = function () {
				this.onmouseover = null;
				this.onmouseout = null;
				getProject(pid, this.dirId, this.projId);
			}
		}
	}
	// modify the menu
	try { getPluginRef("menu").select(pid, sid, tid, qid, true); }
	catch (e) {}
	// scroll to the top
	if (window.scrollY > 156) {
		var callback = function () { getContent("ajax.director.project.php", null, [], "info_text"); }
		scrollToTop(callback);
		return;
	}
	// get the video
	getContent("ajax.director.project.php",
			   null,
			   [],
			   "info_text"); 
}

function setupProjectList (data) {
	
	// record the selected project as qid
	if (data.qid != undefined) {
		qid = Number(data.qid);
	}

	// setup the project rows
	projectIds = [];
	for (var i=0; i<data.projects.length; i++) {
		var dirId	= Number(data.projects[i].split(".")[1]);
		var projId	= Number(data.projects[i].split(".")[3]);
		var e = $("project[" + projId + "]");
		if (qid == projId) {
			e.addClassName("selected");
		} else {
			e.removeClassName("selected");
			e.dirId = dirId;
			e.projId = projId;
			e.onmouseover = function () { this.addClassName("hover"); }
			e.onmouseout = function () { this.removeClassName("hover"); }
			e.onclick = function () {
				this.onmouseover = null;
				this.onmouseout = null;
				getProject(pid, this.dirId, this.projId);
			}
		}
		// record the project id
		projectIds.push(projId);
	}

	// get the page indices
	var pageCurr = Number(data.page_curr);
	var pagePrev = Number(data.page_prev);
	var pageNext = Number(data.page_next);

	// setup the column headers
	var col = data.page_col;
	var dir = data.page_dir;
	var tt = $("list_tab_title");
		tt.addClassName("clickable");
		tt.onclick = function () { getProjectListPage(0, "title", (col=="title" ? (dir=="d" ? "a" : "d"): "a")); }
		tt.src = "/img/list_tab_title_"
				 + (col=="title" ? (dir=="a" ? "a" : "d") : "n")
				 + ".gif";
	var tc = $("list_tab_date");
		tc.addClassName("clickable");
		tc.onclick = function () { getProjectListPage(0, "ctime", (col=="ctime" ? (dir=="d" ? "a" : "d"): "a")); }
		tc.src = "/img/list_tab_date_"
				 + (col=="ctime" ? (dir=="a" ? "a" : "d") : "n")
				 + ".gif";
	if (!sid) {
		var td = $("list_tab_director");
			td.addClassName("clickable");
			td.onclick = function () { getProjectListPage(0, "director", (col=="director" ? (dir=="d" ? "a" : "d"): "a")); }
			td.src = "/img/list_tab_"
					 + (pid==3 ? "director" : "composer")
					 + "_" + (col=="director" ? (dir=="a" ? "a" : "d") : "n")
					 + ".gif";
	}

	// setup the paging controls
	var pp = $("page_prev");
	var pn = $("page_next");
	if (pagePrev == -1) {
		pp.src = "/img/list_page_prev_dead.gif";
		pp.onmouseover = null;
		pp.onmouseout = null;
		pp.onclick = null;
		pp.removeClassName("clickable");
	} else {
		pp.src = "/img/list_page_prev_off.gif";
		pp.onmouseover = function () { this.src = "/img/list_page_prev_on.gif"; }
		pp.onmouseout = function () { this.src = "/img/list_page_prev_off.gif"; }
		pp.onclick = function () { getProjectListPage(pagePrev, col, dir); }
		pp.addClassName("clickable");
	}
	if (pageNext == -1) {
		pn.src = "/img/list_page_next_dead.gif";
		pn.onmouseover = null;
		pn.onmouseout = null;
		pn.onclick = null;
		pn.removeClassName("clickable");
	} else {
		pn.src = "/img/list_page_next_off.gif";
		pn.onmouseover = function () { this.src = "/img/list_page_next_on.gif"; }
		pn.onmouseout = function () { this.src = "/img/list_page_next_off.gif"; }
		pn.onclick = function () { getProjectListPage(pageNext, col, dir); }
		pn.addClassName("clickable");
	}
}

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

function onMailingListResponse (ajax) {
	var json = getJSON(ajax);
	if (json.response.Code == "0") {
		$("maillist").update("Thank you for subscribing. Remember, you&#0146;ll be able to unsubscribe any time, using the link in the newsletters.");
	} else {
		$("maillist").update("Hmm, there was a problem subscribing your address. Please try again later.");
	}

}

function mailingList (e, method) {
	if (method == undefined) {
		method = "+";
	}
	var valid = validateEmail(e);
	if (!valid) {
		alert("Please enter a valid email address.");
	} else {
		$("maillist").update("Please wait while your request is sent..");
		getContent("ajax.contact.maillist.php",
				   onMailingListResponse,
				   ["email=" + e, "method=" + method]); 
	}	
}


function onMailContactResponse (ajax) {
	var json = getJSON(ajax);
	if (json.response) {
		$("mailcontact").update("Your message has been sent, thank you!");
	} else {
		$("mailcontact").update("Hmm, there was a problem sending your message. Please try again later.");
	}
}

function mailContact (cid) {
	var name = $F("mailcontact_name"); 
	var email = $F("mailcontact_email");
	var subj = $F("mailcontact_subj");
	var msg = $F("mailcontact_msg");
	if (!name.length || name == "name") {
		alert("Please enter your name.");
		return;
	}
	if (!validateEmail(email)) {
		alert("Please enter a valid email address.");
		return;
	}
	if (!subj.length || subj == "subject") {
		alert("Please enter a subject.");
		return;
	}
	if (!msg.length || msg == "message") {
		alert("Please enter a message.");
		return;
	}
	$("mailcontact").update("Please wait while your message is sent..");
	var url = "ajax.contact.general.php";
	var params = ["cid=" + cid,
				  "name=" + encodeURIComponent(name),
				  "email=" + encodeURIComponent(email),
				  "subj=" + encodeURIComponent(subj),
				  "msg=" + encodeURIComponent(msg)];
	var ajax = new Ajax.Request(url,
								{ method: "get",
								  parameters: params.join("&"),
								  onComplete: onMailContactResponse
								}
								);
}

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

function track () {
	// start the AJAX call
	var url = "ajax.tracker.php";
	getContent(url, onTrackerLoaded);
}

function insertMenu () {
	// determine the label
	var label = sections[pid - 1];
	if ((pid==3||pid==4) && sid>0) {
		label = directors[sid].name;
	}
	// create a flattened list of all the directors
	var directorsFlat = [];
	for (var i in directors) {
		var d = directors[i];
		directorsFlat.push(d.name + ":" + d.type + ":" + d.id);
	}

	// insert the menu
	var menuSwf;
	menuSwf = new SWFObject("menu.swf", "menu", "650", "143", "8", "#000000");
	menuSwf.addParam("quality", "best");
	menuSwf.addParam("salign", "tl");
	menuSwf.addParam("scale", "noscale");
	menuSwf.addParam("wmode", "opaque");
	menuSwf.addVariable("_server", server);
	menuSwf.addVariable("_pid", pid);
	menuSwf.addVariable("_sid", sid);
	menuSwf.addVariable("_tid", tid);
	menuSwf.addVariable("_qid", qid);
	menuSwf.addVariable("_label", label);
	menuSwf.addVariable("_directors", directorsFlat.join("|"));
	menuSwf.write("menu_swf");
	delete menuSwf;
	delete directorsFlat;
}

function insertSWFs (json) {
	if (!json.swf) return;
	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("wmode", "transparent");
		if (swf.vars) {
			for (var j=0; j<swf.vars.length; j++) {
				f.addVariable(swf.vars[j][0], swf.vars[j][1]);
			}
		}
		f.write(swf.targetId);
	}
}

function insertHTML (json) {
	if (!json.html) return;
	var e = json.el ? $(json.el) : $("content");
	e.update(json.html);
}

function insertQTs (json) {
	if (!json.qt) return;
	for (var i=0; i<json.qt.length; i++) {
		var qt = json.qt[i];
		var q = new QTObject(qt.src, qt.qtId, Number(qt.w), Number(qt.h) + 16);
		if (qt.href) {
			q.addParam("href", qt.href);
		}
		if (qt.vars) {
			for (var j=0; j<qt.vars.length; j++) {
				q.addParam(qt.vars[j][0], qt.vars[j][1]);
			}
		}
		$(qt.targetId).update(q.getHTML());
	}
}

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 getPluginRef (id) {
	return ie ? window[id] : document[id];
}