function ajaxRequest(url,func,obj) {
	if (window.XMLHttpRequest) {var req = new XMLHttpRequest();}
	else if (window.ActiveXObject) {try {req = new ActiveXObject("Msxml2.XMLHTTP");}catch(e) {req = new ActiveXObject("Microsoft.XMLHTTP");}}
	if (func) {req.onreadystatechange = function() {func(req,obj);};}
	req.open('GET',url,true);
	req.setRequestHeader('X-Requested-With','XMLHttpRequest');
	req.setRequestHeader('If-Modified-Since','Wed, 15 Nov 1995 00:00:00 GMT');
	if (req.overrideMimeType) {req.overrideMimeType("text/xml");}
	req.send(null);
	return false;
}

function MyRiding (){
	$ = function(e){e = document.getElementById(e); return e;};
	this.formdiv = $('myr-form');
	this.display = $('myr-display');
	this.form = $('pcode');
	this.potalcode = $('code');
	this.subbtn = $('subbtn');
	this.statusdisplay = $('myr-status');
	this.statusmsg = $('myr-msg');
	this.backbtn = $('myr-backbtn');
	this.change = $('myr-change');
	this.changebtn = $('myr-change-btn');	
	//console.log("New MyRiding Created");
	this.init();
}

MyRiding.prototype = {
	init: function(){
		//console.log("Init");
		var o = this;
		//clearInterval(o.mrInterval);
		this.subbtn.onclick = function(){o.formSubmit();return false;};
		this.form.onsubmit = function(){o.formSubmit();return false;};
		this.backbtn.onclick = function(){o.init();return false;};
		this.changebtn.onclick = function(){o.changeRiding();return false;};
		
		o.display.style.display = "none";
		o.formdiv.style.display = "block";
		o.statusdisplay.style.display = "none";
		o.backbtn.style.display = "none";
		o.change.style.display ="none";
		
		var mycookie = o.readCookie("myridingid");
		if(mycookie > 0){
			//console.log("Cookie = " + mycookie);
			o.formdiv.style.display = "none";
			o.fetchRiding(mycookie);
		}
		
	},
	formSubmit: function(){
		var pc = this.potalcode.value;
		this.formdiv.style.display = "none";
		//console.log("Postal Code Entered: " + pc);
		pc = pc.replace(/\s|-/gi, "");
		pc = pc.toLowerCase();
		//console.log("Postal Code To Search For: " + pc);
		if(pc.search(/^\s*[a-ceghj-npr-tvxy]\d[a-z](\s)?\d[a-z]\d\s*$/i) == 0 ){
			//console.log("Good Postal Code");
			this.fetchPostalCode(pc);
		} else {
			//console.log("Bad Postal Code");
			this.showMessage("badpc","error",1);
		}
	},
	fetchPostalCode: function(pc){
		//console.log("Fetching Postal Code: " + pc);
		url = "/news/canadavotes/myriding/postalcodes/";
		url += pc.substr(0,1) + "/" + pc.substr(0,3) + "/" + pc.substr(3,3) + ".html";
		//console.log("URL to Fetch: " + url);
		this.showMessage("deriding","status");
		ajaxRequest(url,this.fetchPostalCodeResponse,this);
	},
	fetchPostalCodeResponse: function(req,obj){
		if (req.readyState == 4){if (req.status == 200){
			//console.log("Riding Data = " + req.responseText);
			var ridings = eval('(' + req.responseText + ')');
			if (ridings.length > 1){
				//console.log("More then one riding returned " + ridings.length);
				obj.chooseRiding(ridings);
			} else {
				//console.log("Only one riding we'll use that one");
				obj.fetchRiding(ridings[0].rid);
			}
		} else {
			obj.showMessage("nopc","error",1);
			//console.log("There was a problem retrieving data: " + req.status);
		}}
	},
	fetchRiding: function(rid) {
		this.setCookie("myridingid", rid, 90);
		this.myridingid = rid;
		paddingrid = "00" + rid;
		url = "/news/canadavotes/myriding/ridings/" + paddingrid.substr((paddingrid.length - 3),3) + ".html";
		//console.log("URL to Fetch: " + url);
		this.display.style.display = "none";
		this.showMessage("getriding","status");
		ajaxRequest(url,this.displayRiding,this);
	},
	chooseRiding: function(ridings) {
		var choice = "<p>There are multiple ridings for your selected postal code, please select one from the following list:</p>";
		choice += "<ol>";
		for (i in ridings) {
			choice += '<li><a href="#" onclick="MyRiding.fetchRiding(' + ridings[i].rid + '); return false;">' + ridings[i].name + '</a></li>';
		}
		choice += "</ol>";
		this.formdiv.style.display = "none";
		this.display.innerHTML = choice;
		this.statusdisplay.style.display = "none";
		this.display.style.display = "block";
	},
	displayRiding: function(req, obj) {
		if (req.readyState == 4){if (req.status == 200){
			obj.statusdisplay.style.display = "none";
			obj.display.innerHTML = req.responseText; 
			obj.display.className = "";
			obj.display.style.display = "block";
			obj.change.style.display = "block";
			//clearInterval(obj.mrInterval);
			//obj.mrInterval = setInterval("MyRiding.autoRefresh()",30000);
			//console.log("Got Riding Info " + req.responseText);
		} else {
			obj.showMessage("noriding","error",1);
			//console.log("There was a problem retrieving data: " + req.status);
		}}
	},
	autoRefresh: function(){
		//console.log("Auto Refreshing");
		this.display.className = "auto";
		paddingrid = "00" + MyRiding.myridingid;
		url = "/news/canadavotes/myriding/ridings/" + paddingrid.substr((paddingrid.length - 3),3) + ".html";
		ajaxRequest(url,this.displayRiding,this);
	},
	changeRiding: function(){
		//console.log("Changing Riding");
		this.setCookie("myridingid", 0, 90);
		this.init();
	},
	showMessage: function(a, b, c){
		var msgs = {
			"badpc":"Please enter a valid postal code - example M9A2X1.",
			"nopc":"Can't determine riding from supplied postal code.",
			"noriding":"Riding information currently unavailable",
			"deriding":"Determining Riding",
			"getriding":"Getting Riding Info"
		};
		//console.log(msgs[a]);
		this.statusmsg.innerHTML = msgs[a];
		this.statusmsg.className = b;
		if (c) this.backbtn.style.display = "block";
		this.statusdisplay.style.display = "block";
	},
	setCookie: function(name,value,days) {
		//console.log("Setting Cookie for riding: " + value);					
		if (days) {
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
			var expires = "; expires="+date.toGMTString();
		}
		else var expires = "";
		document.cookie = name+"="+value+expires+"; path=/";
	},
	readCookie: function(name) {
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for(i in ca) {
			var 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 null;
	}
};
MyRiding = new MyRiding();
