/****************************************
*	This is a jQuery Plugin Script      *
*	Without Jquery Included in the      *
*	Document BEFORE this plugin,        *
*	These scripts will NOT work.        *
****************************************/

/* REMEMBER TO SET THE FOLLOWING LINES OF CODE FOR EACH COPY OF THIS DOCUMENT  */
var	defaultSiteName = "HGTV|Handyman Superstar|Favourite";
var api = "http://" + window.location.host + "/global/services/Api/Poll.svc/json/";
var submitApi = api + "SubmitVote"; 
/* showInactive is a global override to allow inactive polls to still receive votes */
var showInactive = false;

/*
NOTES:
	pollOptions must have a value.  
	only run insertPoll from the auto scan function that looks for elements with a class of "insertPoll"
TODO:
	- Make "To Do" list
	- Add functionality for tooltips (2008.11.25 - Complete)
	- Add relative bargraphs
	
	Developed by Arron Gibson for CanWest 2008.11
	Completely ravaged and re-written for Handyman by Steve Munday.  2009.06
	Special Thanks to Steve Munday for his great API
*/

function insertFavouriteCurrentPoll()
{
	u = api + "GetCurrentPollQuestion?siteName=HGTV|Handyman Superstar|Favourite";			
	$.getJSON(u, function(json){
		//alert("Cookies: " + document.cookie + " value: " + readCookie("pollID_"+json.d.PollID));
		$("<input type='hidden' id='WhoFavPollId' />").attr({"value":json.d.PollID}).appendTo("#WhoFav");			
		
		if (readCookie("pollID_"+json.d.PollID) !="true" && (json.d.IsActive || showInactive)){ 
			/*
			showInactive is a global override.  if either is true the poll is inserted if the poll is active it will ALWAYS be shown though.  
			the override is only to allow inactive polls to still receive votes 
			*/
			$.each(json.d.Choices, function(i, item){								
				// Do not change this line.  if you set the "name" value after creating the DOM node IE will not work.  the radio button will show but will be unusable.
				$("<input type=\"radio\" name=\"WhoFavChoice\"/>").attr({ 
					"id": "choiceID_"+item.ChoiceID,
					"value": item.ChoiceID,
					"class": "RadioBT"
				}).appendTo("#WhoFav .vote" + item.Title); 		
				// Change the image from the greyed out one to the full-colour one.  This "activates" a person as an option
				$("#WhoFav .vote" + item.Title + " img").attr({"src":"/Media/microsites/Handyman/images/vote/" + item.Title + ".jpg"});
			});				
			$("<a><img src='images/Button_vote.gif' alt='Vote!' class='voteSubmit' /></a>").attr({
				"href":"javascript:sendPost(" + json.d.PollID + "," + json.d.QuestionID + ",'WhoFavChoice',insertFavouriteResults);"
				}).appendTo("#WhoFav");
		} else {
			insertFavouriteResults();
		}
		
		// I assume this is designed to remove any loading icons once the loading is done.
		//$(target).addClass("hasPoll").removeClass("insertPoll")
	});		
}

function insertWhoNextCurrentPoll()
{
	u = api + "GetCurrentPollQuestion?siteName=HGTV|Handyman Superstar|Should Go Next";			
	$.getJSON(u, function(json){		
		
		$("<input type='hidden' id='WhoNextPollId' />").attr({"value":json.d.PollID}).appendTo("#WhoNext");					
		if (readCookie("pollID_"+json.d.PollID) !="true" && (json.d.IsActive || showInactive)){ 
			/* 
			showInactive is a global override.  if either is true the poll is inserted if the poll is active it will ALWAYS be shown though.  
			the override is only to allow inactive polls to still receive votes 
			*/							
			$.each(json.d.Choices, function(i, item){								
				// Do not change this line.  if you set the "name" value after creating the DOM node IE will not work.  the radio button will show but will be unusable.
				$("<input type=\"radio\" name=\"WhoNextChoice\"/>").attr({ 
					"id": "choiceID_"+item.ChoiceID,
					"value": item.ChoiceID,
					"class": "RadioBT"
				}).appendTo("#WhoNext .vote" + item.Title); 								
				$("#WhoNext .vote" + item.Title + " img").attr({"src":"/Media/microsites/Handyman/images/vote/" + item.Title + ".jpg"})
			});			
			
			$("<a><img src='images/Button_vote.gif' alt='Vote!' class='voteSubmit' /></a>").attr({
				"href":"javascript:sendPost(" + json.d.PollID + "," + json.d.QuestionID + ",'WhoNextChoice',insertWhoNextResults);"
				}).appendTo("#WhoNext");
		} else {
			insertWhoNextResults();
		}
	});		
}

function insertFavouriteResults()
{
	$("input[name='WhoFavChoice']").remove();
	$("#WhoFav a").remove();
	
	var pollId = $("#WhoFavPollId").val();	
	u = api + "GetPollResult?siteName=HGTV|Handyman Superstar|Favourite&pollid=" + pollId;			
	$.getJSON(u, function(json){
		$.each(json.d.Choices, function(i, item){											
			$("<span>" + (item.VotePercentage * 100).toFixed(1) + "%</span>").appendTo("#WhoFav .vote" + item.Title);
			$("#WhoFav .vote" + item.Title + " img").attr({"src":"/Media/microsites/Handyman/images/vote/" + item.Title + ".jpg"});
		});			
	});
}

function insertWhoNextResults()
{
	$("input[name='WhoNextChoice']").remove();
	$("#WhoNext a").remove();
	
	var pollId = $("#WhoNextPollId").val();	
	u = api + "GetPollResult?siteName=HGTV|Handyman Superstar|Should Go Next&pollid=" + pollId;			
	$.getJSON(u, function(json){
		$.each(json.d.Choices, function(i, item){											
			$("<span>" + (item.VotePercentage * 100).toFixed(1) + "%</span>").appendTo("#WhoNext .vote" + item.Title);
			$("#WhoNext .vote" + item.Title + " img").attr({"src":"/Media/microsites/Handyman/images/vote/" + item.Title + ".jpg"})
		});			
	});
}

function insertCurrentPollResult(target){
	u = api + "GetCurrentPollQuestion?siteName=" + defaultSiteName;
	$.getJSON(u, function(json){
		currentPollID = json.d.PollID;
		var pollOptions = "pollId="+currentPollID;
		$(target).attr("id", "pollID_"+currentPollID);
		insertPollResult("#pollID_"+currentPollID, pollOptions);
	});
}

function sendPost(pollId, questionId, choiceName, callback){

	var d={};
	$("input[name='" + choiceName + "']").each(function(){
		if (this.checked == true)
			d.choiceId = this.value;
	});
	
	if (d.choiceId == undefined)	
		return;
	
	d.pollId = pollId * 1;
	d.questionId = questionId * 1;	
	
	$.ajax({
		type: "POST",
		url: submitApi,
		data: $.toJSON(d),
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		success: callback
	});
	
	createCookie("pollID_"+d.pollId, true, 7);
}

function createCookie(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=/";
}

function readCookie(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;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}
