/*
	jCore v0.2
	Matthew Ausonio
	Last Updated:October 2,2009
	Created:October 10, 2008
	
	This file contains the required scripts for a base Digicore site.
	Includes functionality for common modules such as Poll and Rating. For a full list please refer to Core SVN.
*/
var jCore = {
	// **************************************************************
	// Item Stats Retrieval methods. Do not remove
	// **************************************************************
	jCoreInit: function(shareURL,shareTitle,itemId,pollIdsArray) {
		// first thing we do is test to see if cookies is enabled, if it isnt, we alert user to enable cookies.
		this.cookieTest();
		//end cookie test, lets continue
		//self = this
		/* now we check to see if our userID cookie has been set, if not we request a new userID and make the cookie */
		userId = (jCore.readCookie("userID"))?jCore.readCookie("userID"):"";
		
		// the blankItemStats is used when we have an error or timeout getting the actual item stats.
		blankItemStats = {
			"clicks": 1446,
			"comments": 0, 			// int : number of comments of the current item
			"votes" : 0, 			// int : number of votes of the current item (sometimes refered to as ratings)
			"rating" : 3.00, 		// int : the current calculated rating of the current item
			"userVoted" : false, 	// boolean : if user has rated current item. based on current itemId and current userID.
			"usersRating" : null,	// int or null : rating of current item. based on current itemId and current userId.
			"userId" : ""			// string : current userId generated by sitecore.
		};
		// make call to item stats.  On callback init the jCore object.
		$.ajax({type: "GET", url: "/Handlers/ItemStats.ajax", data:"id="+itemId+"&userid="+userId,dataType:"json",cache:false,async:false,
		   success: function(updatedItemStatistics){
				jCore.writeCookie("userID",updatedItemStatistics.userId, 365);
				jCore.assignItemStats(shareURL,shareTitle,itemId,updatedItemStatistics,pollIdsArray);
			},
			error: function(error){
				jCore.assignItemStats(shareURL,shareTitle,itemId,blankItemStats,pollIdsArray);
			},
			timeout: function(error){
				jCore.assignItemStats(shareURL,shareTitle,itemId,blankItemStats,pollIdsArray);
			}
		});
	},
	assignItemStats: function(shareURL,shareTitle,itemId,itemStats,pollIdsArray) {
		this.shareURL = shareURL; // url of the item/page
		this.shareTitle=shareTitle; // title of the item/page
		this.itemId=itemId; // sitecore id of the item/page
		this.itemStats=itemStats; // stats on the item
		this.pollIdsArray=new Array(); // array of poll ids for polls on current page
		
		$(".jcorePoll").each(function(i) {
			jCore.pollIdsArray.push(this.id);
			jCore.initPoll(i);
		});
		
		updateRatingStats(itemStats);
		
		//this goes through the itemPolls array and initializes all polls on the page
		/*for(i=0;i<this.pollIdsArray.length;i++) {
			this.initPoll(i);
		}*/
	},
	cookieTest: function() {
		var cookieEnabled=(navigator.cookieEnabled)? true : false
		//if not IE4+ nor NS6+
		if (typeof navigator.cookieEnabled=="undefined" && !cookieEnabled){ 
			document.cookie="testcookie"
			cookieEnabled=(document.cookie.indexOf("testcookie")!=-1)? true : false
		}
		if(!cookieEnabled) {
			alert("Cookies are required for this site to run properly.  Please enable cookies in your browser settings and reload page.");
			return false;
		}
	},
	// **************************************************************
	// Core Module methods
	// 
	// **************************************************************
	pollItems: new Array(),
	initPoll: function(i) {
		// set up this poll item. this is done for each poll item on the page.
		this.pollItems[i] = {
			pollId: jCore.pollIdsArray[i],
			pollForm: document.getElementById(jCore.pollIdsArray[i]),
			pollContainer: document.getElementById(jCore.pollIdsArray[i]+"Container"),
			pollUrl: $("#"+jCore.pollIdsArray[i]).attr("action")
		}
		// lets go ahead and store the source code for later use in results.
		jCore.tempPollSource(i, this.pollItems[i].pollContainer);
		
		// lets request current poll results handler. this will tell us if the user has already submitted to this poll.
		$.ajax({
			type: "GET",
			url: "/Handlers/Poll.ajax",
			dataType: "json",
			cache:false,
			data:"id="+jCore.pollIdsArray[i]+"&userID="+jCore.itemStats.userId,
			success: function(pollJSON){
				if(pollJSON.userClicked) {
					// user already voted. show results.
					jCore.showPollResults(i,pollJSON);
				} else {
					// user has not voted. attach submit event to form.
					$("#"+jCore.pollItems[i].pollId).submit(function() {
						return jCore.submitPoll(i,jCore.pollItems[i].pollId,jCore.pollItems[i].pollForm,jCore.pollItems[i].pollContainer,jCore.pollItems[i].pollurl);
					});
				}
			}
		});
	},
	submitPoll: function(i,pollId,pollForm,pollContainer,pollurl) {
		// get currently selection to submit
		var pollValue = $("input:radio:checked", pollForm).val();

		// if there is no selection we stop and alert user.
		if(!pollValue)
			alert("Please select a poll answer");
		else {
			// if we made it this far, we go ahead and submit the poll. on success we re-request the poll results handler
			$.ajax({
				type: "GET",
				url: "/Handlers/PollClick.ajax",
				data: "id="+pollId+"&choiceId="+pollValue+"&userid="+jCore.itemStats.userId,
				cache:false,
				success: function(pollResults){
					if(pollResults.processed = true)
						jCore.getPollResults(i);
				}
			});	
		}
		return false;
	},
	getPollResults: function(i) {
		// request results. this is called on a successful poll submission. on success we show results.
		$.ajax({
			type: "GET",
			url: "/Handlers/Poll.ajax",
			dataType:"json",
			cache:false,
			data:"id="+jCore.pollItems[i].pollId+"&userid="+jCore.itemStats.userId,
			success: function(pollresults){
				jCore.showPollResults(i, pollresults);
			}
		});
	},
	showPollResults: function(i, pollresults) {
		// modify stored source object with percentages from poll results json
		for(p=0;p<pollresults.poll.length;p++) {
			var oldVal = jCore.pollItems[i].pollSource[pollresults.poll[p].itemId];
			var percentage=pollresults.poll[p].percentage;
			var re=/PERCENT/g
			var newVal = oldVal.replace(re,percentage);
			jCore.pollItems[i].pollSource[pollresults.poll[p].itemId]=newVal;
		}
		// create an array to hold final source code for results
		tempSource=new Array;
		for (var qId in jCore.pollItems[i].pollSource) {
			tempSource.push(jCore.pollItems[i].pollSource[qId]);
		}
		tempSource.push('<span class="pollTotalVoteText">Total Votes: '+pollresults.totalClicks+'</span>')
		// output final source code for results
		pCont = $(this.pollItems[i].pollContainer);
		pCont.html(tempSource.join(""));
	},
	tempPollSource: function(p, pollContainer) {
		// new object inside this poll item to store source code for later use in results
		jCore.pollItems[p].pollSource=new Object();
		// if the input is also inside the label, we want to remove it. here we create the reg exp to do that
		inputReg = new RegExp(/<input[^>]*>/); 
		// for each label we store a string for later use in results source code.
		$("label", pollContainer).each(function(i) {
			inputFor = document.getElementById($(this).attr("for")).value;
			cleanSource = this.innerHTML.replace(inputReg, "");
			jCore.pollItems[p].pollSource[inputFor]= "<div class='pollResultRow'><div>"+cleanSource+"</div><div class='pollResultBar' style='width:PERCENT%;'>&nbsp;</div><span>PERCENT%</span></div>";
		});

	},
	// Utility methods
	// **************************************************************
	
	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 false;
	},
	writeCookie: function(name,value,days) {
		if(name == "userName" && value == "")
			return;
		if(days)
		{
			var date = new Date();
			date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
			var expires = "; expires=" + date.toGMTString();
			document.cookie = name + "=" + value + expires;	
		}
		else
		{
			var expires = "";
			document.cookie = name+"="+value+expires;
		}
	},
	deleteCookie: function(name) {
		var expire = new Date();
		expire.setDate(expire.getDate() - 1);
		document.cookie = ''+name+'=""; expires=' + expire.toGMTString() + '; path=/';
	},
	openWin: function(url,wName,para) {
		if(typeof(arguments[2]) == "object")
		var values = jCore.parameters(arguments[2]);
		window.open(url,wName,values);
	},
	parameters: function (attributes)
	{
		var values = [];
		for(attribute in attributes)
		{
			values.push(attribute + "=" + attributes[attribute].toString());
		}
		return values.join(",");
	}
};
function updateRatingStats(itemStats) {
	if(itemStats.userVoted == true)
		disableRatings();
	$(".shareBarRatings p span.ratingTotalVotes").html("("+itemStats.votes+" Votes)");
	$(".currentRating").width(itemStats.rating * 19);
	var comments=itemStats.comments;
	if (comments==0) {
		comments="+";
	}
	$(".shareBarComments a").html(""+comments);
}
function disableRatings() {
	$(".shareBarRatings li a").remove();
	$(".shareBarRatings ul").removeClass("ratingHover").unbind("mouseover");
}
// pointer for function call in each page. Now sent to already existing jCore object.
jCoreInit = function(shareURL,shareTitle,itemId,pollIdsArray) {jCore.jCoreInit(shareURL,shareTitle,itemId,pollIdsArray);}