var jsTVNZpoll = window.jsTVNZpoll || {};

// the Initialize function, which runs on load, all sub-functions are called in here.
jsTVNZpoll.initialize = function(id) {

	//set toogle function on view results text
	$('.view-results').toggle(function(){
		$('.poll').hide();
		$('.poll-results').show();
		$('.view-results').html("hide results");
		return false;
	}, function(){
		$('.poll').show();
		$('.poll-results').hide();
		$('.view-results').html("view results");
		return false;
	});
	
	
	//only enable the submit button once a radio button has been clicked
	$('.vote-radio').click(function() {
		$('#poll-submit').removeAttr('disabled');
		$('#poll-submit').removeClass('disabled');
	});
	
	// changes the submit on the form to do an ajax submit instead. e.g when you call $(<insert form id>).submit(); it will use ajax.
	$("#pollForm" + id).ajaxSubmit(id);
	
	jsTVNZpoll.Common().showPoll(id);
}


// TVNZ Common functions, that can be re-called at any point.
jsTVNZpoll.Common = function() {

	var showPoll = function(id) {
		var pollCookie = jsTVNZpoll.Common().readCookie("pollForm" + id);
		if (pollCookie == "voted") {
			// Already voted - disable the link back to 'poll'
			$('.poll').hide();
			$('.poll-results').show();
			$('.view-results').hide();
		}
		else {
			// hasn't already voted so can see poll
			$('.poll').show();
			$('.poll-results').hide();
			$('.view-results').html("view results");
		}
	}

	var createCookie = function(name,value,days) {
		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=/";
	}

	var readCookie = function(name) {
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++) {
			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;
	}

	var eraseCookie = function(name) {
		jsTVNZpoll.Common().createCookie(name,"",-1);
	}
;
	return {
		createCookie : createCookie,
		readCookie : readCookie,
		eraseCookie : eraseCookie,
		showPoll : showPoll
	}
}

$.fn.ajaxSubmit = function(id) {
	/* Change a form's submission type to ajax */
	var formId = "#pollForm" + id; 
	$(formId + " input[type=radio]").click(function() {
		$(formId + " input[name=submit]").removeClass("disabled");
	});
	$(formId).submit(function() {
		$("body").addClass("curWait");
		// adds cookie before it submits
		jsTVNZpoll.Common().createCookie("pollForm" + id,"voted",365);
		$.post(this.getAttribute("action") + "?call=ajax", $(formId).serialize(), function(xml){
			jsTVNZpoll.Common().showPoll(id);
		});
		return false;
	});
	return this;
}



