var Cookie = {
	set: function(name,value,seconds){
		if(seconds){
			d = new Date();
			d.setTime(d.getTime() + (seconds * 1000));
			expiry = '; expires=' + d.toGMTString();
		}else
			expiry = '';
		document.cookie = name + "=" + value + expiry + "; path=/";
	},
	get: function(name){
		nameEQ = name + "=";
		ca = document.cookie.split(';');
		for(i = 0; i < ca.length; i++){
			c = ca[i];
			while(c.charAt(0) == ' ')
				c = c.substring(1,c.length);
			if(c.indexOf(nameEQ) == 0)
				return c.substring(nameEQ.length,c.length);
		}
		return false;
	},
	unset: function(name){
		Cookie.set(name,'',-1);
	}
}

function isLoggedOn() {
	return Cookie.get("pln");
}

Burley={
	seen:function() {
		return Cookie.get("burley");
	},

	saw:function() {
		Cookie.set("burley", 1, 1209600);
	}
}

Instructions={
	seen:function() {
		return Cookie.get("instructions");
	},

	saw:function() {
		Cookie.set("instructions", 1, 1209600);
	}
}

returning={
	row:function() {
		var windowHREF = window.location.toString();
		var frag = windowHREF.split("#")[1];

		if(frag.length > 0) {
			var s,r;

			if(frag.split("/")[1].toLowerCase() == "row") {
				s = frag.split("/")[2]; // stand
				r = frag.split("/")[3]; // row
				$SWF('stadiumSWF').SWFReturning(s,r);

				var path = "/row/"+s+"/"+r;
				returning.setPath(path);
				return true;
			}
		}
		return false;
	},

	setPath:function(path) {
		setTimeout("returning.path('"+path+"');", 5000);
	},

	path:function(p) {
		Cookie.set("stadiumPage", p);
	}
}


stadium={
	init:function() {
		if($('stadium') != null) {
			if($('stadiumFlash') != null) {
				var FO = { movie:"/flash/stadium.swf", width:"758", height:"390", majorversion:"8", build:"0", id:"stadiumSWF", bgcolor:"#172148" };
				UFO.create(FO, "stadiumFlash");
			}
		}
	},

	setCurrentPage:function(path) {
		if(path != "/") {
			Cookie.set("stadiumPage", path);
		} else {
			Cookie.unset("stadiumPage");
		}
	},

	stats:{
		cache:null,
		sendToFlash:false,

		preload:function() {
			var url = "/xhr/stadiumStats.xhr.php";
			var qs  = "?request=preload&noCache="+vhUtils.noCacheString();
			new Ajax.Request(url, { method:'get', parameters:qs, onComplete: function(r) {
				var response = r.responseText;
				if(response != "ERROR") {
					stadium.stats.cache = $JSON(response);
					if(stadium.stats.sendToFlash) {
						$SWF('stadiumSWF').setDataCache(stadium.stats.cache);
						stadium.stats.sendToFlash = false;
					}
				}
			}});
		},

		getCache:function() {
			return stadium.stats.cache;
		},

		flashWaiting:function() {
			if(stadium.stats.cache != null) {
				$SWF('stadiumSWF').setDataCache(stadium.stats.cache);
			} else {
				stadium.stats.sendToFlash = true;
				stadium.stats.preload();
			}
		}
	}
}

Sections={

	list:null,

	load:function(sid) { // P5
		var url = "/xhr/sectionSeats.xhr.php";
		var qs  = "?section="+sid+"&noCache="+vhUtils.noCacheString();
		new Ajax.Request(url, { method:'get', parameters:qs, onComplete: function(r) {
			var response = r.responseText;
			if(response != "ERROR") {
				var seats = $JSON(response);
				$SWF('stadiumSWF').loadSection(seats);
			}
		}});
	}
}

pledgeForm={
	init:function() {
		if($('createPledgeForm') != null) {
			this.registerMaxCharsEvent();

			if($('editing') == null) {
				$('password').observe('keyup', pledgeForm.checkPasswords);
				$('passwordConfirm').observe('keyup', pledgeForm.checkPasswords);
			}

			$('fileAvatar').observe('change', pledgeForm.prettyInput);
			$('fileAvatar').observe('mouseout', pledgeForm.prettyInput);

			$('createPledgeForm').observe('submit', function(e) {
				pledgeForm.clearErrors();
				pledgeForm.validate(e);
			});
		}
	},

	registerMaxCharsEvent:function() {
		$$('textarea[maxlength]').each(function(textarea) {
			textarea.observe('keyup',  pledgeForm.updateMaxChars.bindAsEventListener(textarea));
			textarea.observe('change', pledgeForm.updateMaxChars.bindAsEventListener(textarea));
		});
	},

	updateMaxChars:function() {
		var txtId = this.id;
		if($(txtId+'-length') != null) {
			var max = this.getAttribute('maxlength');
			var rem = max - $F(this).length;
			if(rem < 0) {
				this.value = $F(this).substring(0, max);
				rem = 0;
			}
			var charStr = (rem == 1) ? "character" : "characters";
			$(txtId+'-length').innerHTML = "You have "+ rem + " " + charStr +" remaining";
		}
	},

	validate:function(e) {
		var reqInputs;
		if($('editing') != null) {
			reqInputs = $A(["firstName", "surname", "email", "pledgeText", "fanType", "hometown"]);
		} else {
			reqInputs = $A(["firstName", "surname", "email", "pledgeText", "fanType", "hometown"]);
		}
		reqInputs.each(function(name) {
			if($F(name).blank()) pledgeForm.showError(name);
			if(name == "fanType") {
				if($F(name) == "na") pledgeForm.showError(name);
			}
		});

		if(!confirm("I confirm that I and those in my pictures are over the age of 18")) {
			pledgeForm.showError("fileAvatar");
		}

		/* Special case for terms */
		if(!$('terms').checked) pledgeForm.showError("terms");

		/* Special case for passwords */
		if($('editing') == null) {
			if($F('password').blank() || ($F('password') != $F('passwordConfirm')))        pledgeForm.showError("password");
			if($F('passwordConfirm').blank() || ($F('password') != $F('passwordConfirm'))) pledgeForm.showError("passwordConfirm");
		}

		if($$('form#createPledgeForm strong.error').length > 0) {
			Event.stop(e);
			var p = document.createElement("p");
			p.className = "error";
			p.id = "pledgeFormErrorMessage";
			var txt = document.createTextNode("There is an error with your submission. Fix the fields marked with * & try again.");
			p.appendChild(txt);
			$('createPledgeForm').insertBefore(p, $$('form#createPledgeForm h4')[0]);
			window.scrollTo(0,0);
		}

	},

	showError:function(name) {
		var strong = document.createElement("strong");
		strong.className = "error";
		var txt = document.createTextNode("*");
		strong.appendChild(txt);

		$(name).parentNode.appendChild(strong);
	},

	clearErrors:function() {
		if($$('form#createPledgeForm strong.error').length > 0) {
			$$('form#createPledgeForm strong.error').each(function(s) {
				$(s).remove();
			});
			$('pledgeFormErrorMessage').remove();
		}
	},

	checkPasswords:function() {
		var pass1 = $F('password');
		var pass2 = $F('passwordConfirm');

		var ddDone = ($('passwordMismatchMsg') != null) ? $('passwordMismatchMsg').remove() : false;

		if(pass1 != pass2) {
			var dd;

			if(!ddDone) {
				dd = document.createElement("dd");
				dd.id = "passwordMismatchMsg";
				var p = document.createElement("p");
				var small = document.createElement("small");
				small.className = "error";
				var txt = document.createTextNode("passwords do not match");

				small.appendChild(txt);
				p.appendChild(small);
				dd.appendChild(p);
			} else {
				dd = ddDone;
			}

			$('passwordConfirm').parentNode.parentNode.appendChild(dd);
		} else {
			if($('passwordMismatchMsg') != null) $('passwordMismatchMsg').remove();
		}
	},

	prettyInput:function() {
		$$('#fileAvatarPrettyControls input[type=text]')[0].value = $F('fileAvatar');
	}
}

pubForm={
	init:function() {
		if($('createPubForm') != null) {
			pledgeForm.registerMaxCharsEvent();
			$('fileAvatar').observe('change', pledgeForm.prettyInput);
			$('fileAvatar').observe('mouseout', pledgeForm.prettyInput);

			$('createPubForm').observe('submit', function(e) {
				pubForm.clearErrors();
				pubForm.validate(e);
			});
		}
	},

	validate:function(e) {
		var reqInputs = $A(["pubName", "pubAddress1", "pubTown", "pubPostcode", "pubPledgeText"]);
		reqInputs.each(function(name) {
			if($F(name).blank()) pledgeForm.showError(name);
		});

		if(!confirm("I confirm that I and those in my pictures are over the age of 18")) {
			pledgeForm.showError("fileAvatar");
		}

		/* Special case for terms */
		if(!$('terms').checked) pledgeForm.showError("terms");

		if($$('form#createPubForm strong.error').length > 0) {
			Event.stop(e);
			var p = document.createElement("p");
			p.className = "error";
			p.id = "pubFormErrorMessage";
			var txt = document.createTextNode("There is an error with your submission. Fix the fields marked with * & try again.");
			p.appendChild(txt);
			$('createPubForm').insertBefore(p, $$('form#createPubForm h4')[0]);
			window.scrollTo(0,0);
		}

	},

	clearErrors:function() {
		if($$('form#createPubForm strong.error').length > 0) {
			$$('form#createPubForm strong.error').each(function(s) {
				$(s).remove();
			});
			$('pubFormErrorMessage').remove();
		}
	}
}

headlines={
	draw:function() {
		if(typeof sIFR == "function"){
			sIFR.replaceElement(named({
									sSelector:"h3.pageTitle",
									sFlashSrc:"/flash/sifr-AvantGardeBold-tracking.swf",
									sColor:"#FFFFFF",
									sLinkColor:"#FFFFFF",
									sBgColor:"#FDCD00",
									sHoverColor:"#FFFFFF",
									sWmode:"transparent"
									}));
			sIFR.replaceElement(named({
									sSelector:"form h4",
									sFlashSrc:"/flash/sifr-AvantGardeBold.swf",
									sColor:"#1B2751",
									sLinkColor:"#1B2751",
									sBgColor:"#FFFFFF",
									sHoverColor:"#1B2751",
									sWmode:"transparent"
									}));
			sIFR.replaceElement(named({
									sSelector:"#vh-list h4",
									sFlashSrc:"/flash/sifr-AvantGardeBold.swf",
									sColor:"#1B2751",
									sLinkColor:"#1B2751",
									sBgColor:"#FFFFFF",
									sHoverColor:"#1B2751",
									sWmode:"transparent"
									}));
			sIFR.replaceElement(named({
									sSelector:"#view-pledge h4",
									sFlashSrc:"/flash/sifr-AvantGardeBold.swf",
									sColor:"#1B2751",
									sLinkColor:"#1B2751",
									sBgColor:"#FFFFFF",
									sHoverColor:"#1B2751",
									sWmode:"transparent"
									}));
		}
	}
}

listingAvatars={
	init:function() {
		var code, FO, rs;
		if($$('div.searchPledgesList a.vh-pic').length > 0) {
			$$('div.searchPledgesList a.vh-pic').each(function(a) {
				code = a.rel.split("-");

				rs = vhUtils.noCacheString();
				a.parentNode.id = rs;
				a.parentNode.className = "vh-pic";

				FO = { movie:"/flash/listing-avatar.swf", width:"62", height:"62", majorversion:"8", build:"0", flashvars:"seatN="+code[0]+"&seatId="+code[1]+"&imgId="+code[2] };
				UFO.create(FO, rs);
			});
		}
	}
}

searchPledges={
	init:function() {
		if($('search-pledges-form') != null) {
			$('stand').observe('change', function() {
				searchPledges.updateStand($F('stand'));
			});
			$('section').observe('change', function() {
				searchPledges.updateSection($F('section'));
			});
			if($F('section')=="na") $('section').disabled=true;
			if($F('row')=="na") $('row').disabled=true;
		}
	},

	updateStand:function(sid) {
		var url = "/xhr/searchSelects.xhr.php";
		var qs  = "?request=sections&sid="+sid+"&noCache="+vhUtils.noCacheString();
		new Ajax.Request(url, { method:'get', parameters:qs, onComplete: function(r) {
			var response = r.responseText;
			if(response != "ERROR") {
				var sections = $JSON(response);
				searchPledges.clearSelects($('section'));

                $('section').disabled=false;

				var option, txt;

				option = document.createElement("option");
				txt = document.createTextNode("Please choose");
				option.appendChild(txt);
				option.value = "na";
				$('section').appendChild(option);

				$A(sections).each(function(section) {
					option = document.createElement("option");
					txt = document.createTextNode(section.name);
					option.appendChild(txt);
					option.value = section.id;
					$('section').appendChild(option);
				});
				searchPledges.updateSection(sections[0].id);
			}
		}});
	},



	updateSection:function(sid) {
		var url = "/xhr/searchSelects.xhr.php";
		var qs  = "?request=rows&sid="+sid+"&noCache="+vhUtils.noCacheString();
		new Ajax.Request(url, { method:'get', parameters:qs, onComplete: function(r) {
			var response = r.responseText;
			if(response != "ERROR") {
				var rowCount = parseInt(response);
				searchPledges.clearSelects($('row'));

                $('row').disabled=false;

				var option, txt;

				option = document.createElement("option");
				txt = document.createTextNode("Please choose");
				option.appendChild(txt);
				option.value = "na";
				$('row').appendChild(option);

				for(var i=1; i <= rowCount; i++) {
					option = document.createElement("option");
					txt = document.createTextNode(i);
					option.appendChild(txt);
					option.value = i;
					$('row').appendChild(option);
				}
			}
		}});
	},

	clearSelects:function(el) {
		$(el).getElementsBySelector("option").each(function(opt) {
			opt.remove();
		});
	},

	flash:{
		requestStands:function() {
			var url = "/xhr/searchSelects.xhr.php";
			var qs  = "?request=stands&noCache="+vhUtils.noCacheString();
			new Ajax.Request(url, { method:'get', parameters:qs, onComplete: function(r) {
				var response = r.responseText;
				if(response != "ERROR") {
					$SWF('stadiumSWF').loadStands($JSON(response));
				}
			}});
		},

		requestSections:function(sid) {
			sid = sid || 1;
			var url = "/xhr/searchSelects.xhr.php";
			var qs  = "?request=sections&sid="+sid+"&noCache="+vhUtils.noCacheString();
			new Ajax.Request(url, { method:'get', parameters:qs, onComplete: function(r) {
				var response = r.responseText;
				if(response != "ERROR") {
					$SWF('stadiumSWF').loadSections($JSON(response));
				}
			}});
		},

		requestRows:function(sid) {
			sid = sid || 1;
			var url = "/xhr/searchSelects.xhr.php";
			var qs  = "?request=rows&sid="+sid+"&noCache="+vhUtils.noCacheString();
			new Ajax.Request(url, { method:'get', parameters:qs, onComplete: function(r) {
				var response = r.responseText;
				if(response != "ERROR") {
					$SWF('stadiumSWF').loadRows($JSON(response));
				}
			}});
		}
	}
}

help={
	init:function() {
		/* Hide help info */
		if($('instructions') != null) {
			$('instructions').hide();
			$('instructions').removeClassName('hide');
			/* Create and hide overlay */
			var div = document.createElement("div");
			div.id = "help-overlay";
			document.body.appendChild(div);
			$('help-overlay').hide();

			$('helpClose').observe('click', function(e) {
				Event.stop(e);
				help.hide();
			});
		}
	},

	show:function() {
		var arrayPageSize = vhUtils.getPageSize();
		help.overlayShow();
		var w = (arrayPageSize[0]/2)-335;
		$('instructions').setStyle({left: w+"px"});
		$('instructions').show();
	},

	overlayShow:function() {
		var arrayPageSize = vhUtils.getPageSize();
		$('stadiumFlash').innerHTML = "<img src='/flash/tmp-stadium.jpg' alt='Tmp Stadium Image' />";
		$('help-overlay').setStyle({ width: arrayPageSize[0] + 'px', height: arrayPageSize[1] + 'px' });
		$('help-overlay').setOpacity(0.8);
		$('help-overlay').show();
		$('help-overlay').observe('click', help.hide);
	},

	hide:function() {
		help.overlayHide();
		$('instructions').hide();
	},

	overlayHide:function() {
		if($('help-overlay') != null) {
			$('help-overlay').hide();
			stadium.init();
		}
	}
}

vhUtils={
	noCacheString:function() {
		var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
		var rn;
		var str = "";
		var ln = Math.floor(Math.random()*4)+6;

		for(var i=0; i <= ln; i++) {
			rn = Math.floor(Math.random()*chars.length);
			str += chars.substring(rn,rn+1);
		}

		return str;
	},
	getPageSize: function() {

	     var xScroll, yScroll;

		if (window.innerHeight && window.scrollMaxY) {
			xScroll = window.innerWidth + window.scrollMaxX;
			yScroll = window.innerHeight + window.scrollMaxY;
		} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
			xScroll = document.body.scrollWidth;
			yScroll = document.body.scrollHeight;
		} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
			xScroll = document.body.offsetWidth;
			yScroll = document.body.offsetHeight;
		}

		var windowWidth, windowHeight;

		if (self.innerHeight) {	// all except Explorer
			if(document.documentElement.clientWidth){
				windowWidth = document.documentElement.clientWidth;
			} else {
				windowWidth = self.innerWidth;
			}
			windowHeight = self.innerHeight;
		} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
			windowWidth = document.documentElement.clientWidth;
			windowHeight = document.documentElement.clientHeight;
		} else if (document.body) { // other Explorers
			windowWidth = document.body.clientWidth;
			windowHeight = document.body.clientHeight;
		}

		// for small pages with total height less then height of the viewport
		if(yScroll < windowHeight){
			pageHeight = windowHeight;
		} else {
			pageHeight = yScroll;
		}

		// for small pages with total width less then width of the viewport
		if(xScroll < windowWidth){
			pageWidth = xScroll;
		} else {
			pageWidth = windowWidth;
		}

		return [pageWidth,pageHeight];
	}
}

RandomPledges={

	pledges:null,
	flashWaiting:false,
	current:0,

	init:function() {
		var url = "/xhr/randomPledge.xhr.php";
		var qs  = "?noCache="+vhUtils.noCacheString();
		new Ajax.Request(url, { method:'get', parameters:qs, onComplete: function(r) {
			var response = r.responseText;
			if(response != "ERROR") {
				RandomPledges.pledges = $JSON(response);
			}
		}});
		if(RandomPledges.flashWaiting) {
			$SWF('stadiumSWF').loadRandomPledge(RandomPledges.pledges[0]);
			RandomPledges.current++;
		}
	},

	nextPledge:function() {
		if(RandomPledges.pledges != null) {
			if(RandomPledges.current >= RandomPledges.pledges.length) RandomPledges.current = 0;
			$SWF('stadiumSWF').loadRandomPledge(RandomPledges.pledges[RandomPledges.current]);
			RandomPledges.current++;
		} else {
			RandomPledges.flashWaiting = true;
		}
	}
}

RandomPledges.init();

Bubbles={
	fetch:function() {
		return;
		var url = "/xhr/bubbles.xhr.php";
		var qs  = "?noCache="+vhUtils.noCacheString();
		new Ajax.Request(url, { method:'get', parameters:qs, onComplete: function(r) {
			var response = r.responseText;
			if(response != "ERROR") {
				bubbleData = $JSON(response);
				$SWF('stadiumSWF').putBubbleData(bubbleData);
			}
		}});
	}
}

function $JSON(str) {
	return str.evalJSON(true);
}

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];
	}
}

function externalLinks() {
	$$('a[rel=external]').each(function(a) {
		a.target="_blank";
	});
}

function doPopups() {
    if (!document.getElementsByTagName) return;
    var anchors = document.getElementsByTagName("a");
    for (var i=0; i<anchors.length; i++) {
        var anchor = anchors[i];
        if ( anchor.getAttribute("href") && anchor.getAttribute("rel") == "popup" ) {
            anchor.target = "_blank";
        }
    }
}

function gaAdd(p) {
	if(urchinTracker) {
		urchinTracker(p);
	}
}

Event.onDOMReady(function() {
	help.init();
	stadium.init();
	externalLinks();
    doPopups();
	headlines.draw();
	pledgeForm.init();
	pubForm.init();
	listingAvatars.init();
	searchPledges.init();
});