/*
	jCore v0.2
	Matthew Ausonio
	Last Updated:October 2,2009
	Created:October 10, 2008
	
	Dependent libraries:
		jQuery v1.3.2
	
	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) {
        jCore.log(jCore);
        // 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

        /* 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") : "";

        /* debugPath will help us modify ajax calls for development purposes. to trigger put debug=true in url */
        debugPath = (jCore.getUrlParam("debug") == "true") ? "/Html" : "";

        // 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: debugPath + "/Handlers/ItemStats.ajax", data: "id=" + itemId + "&userid=" + userId, dataType: "json", cache: false,
            success: function (updatedItemStatistics) {
                jCore.writeCookie("userID", updatedItemStatistics.userId, 365);
                jCore.assignItemStats(shareURL, shareTitle, itemId, updatedItemStatistics, pollIdsArray, debugPath);
            },
            error: function (error) {
                jCore.assignItemStats(shareURL, shareTitle, itemId, blankItemStats, pollIdsArray, debugPath);
            },
            timeout: function (error) {
                jCore.assignItemStats(shareURL, shareTitle, itemId, blankItemStats, pollIdsArray, debugPath);
            }
        });
    },
    assignItemStats: function (shareURL, shareTitle, itemId, itemStats, pollIdsArray, debugPath) {
        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
        this.debugPath = debugPath;
        if (itemStats.userWhitelisted == true) {
            this.writeCookie("whitelisted", "YES", 365);
        }
        //this goes through polls on the page and initializes
        $(".jcorePoll").each(function (i) {
            jCore.pollIdsArray.push(this.id); // store this poll id in an array for later
            jCore.initPoll(i); // initialize this poll
        });

        // initialize all ratings
        updateRatingStats(itemStats);
        // Initialize comments
        /*initComments();*/
    },
    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;
        }
    },
    // **************************************************************
    // Poll 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: jCore.debugPath + "/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: jCore.debugPath + "/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: jCore.debugPath + "/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) {
        var values = [];

        // Go through all of the results, storing their percentages in to the values array
        for (p = 0; p < pollresults.poll.length; p++) {
            values.push(pollresults.poll[p].percentage);
        }

        // Sort the array of values so we go from highest in pos 0 to lowest percentages
        values.sort(function (a, b) {
            return b - a;
        });

        // modify stored source object with percentages from poll results json
        for (p = 0; p < pollresults.poll.length; p++) {
            var perc = pollresults.poll[p].percentage;
            var percadjust = pollresults.poll[p].percentage * .87; // make sure 100% will appear along side colored bar

            // Find the position in values with the same percentage - so we know what position the item should be in
            var pos = -1;
            for (var j = 0; j < values.length; j++) {
                if (pos == -1) {
                    if (values[j] == perc) {
                        pos = j;
                    }
                }
            }

            var iid = pollresults.poll[p].itemId;
            var newVal = jCore.pollItems[i].pollSource[iid];
            // Replace #P# with the percentage
            newVal = newVal.replace(/#P#/g, perc);
            // Replace #PA# with the percentage adjustment
            newVal = newVal.replace(/#PA#/g, percadjust);
            // Replace #POS# with the position
            newVal = newVal.replace(/#POS#/g, pos);
            jCore.pollItems[i].pollSource[iid] = 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]);
        }

        // Tack on the total number of votes
        tempSource.push('<div class="pollTotal"><span class="pollTotalValue">' + pollresults.totalClicks + '</span> <span class="pollTotalLabel">Total Votes. Poll results are not scientific.</span></div>');

        // 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 pollResultsPos#POS#'><div class='pollResultBar' style='width:#PA#%;'><div></div></div><span>#P#%</span><div>" + cleanSource + "</div></div>";
        });

    },
    // **************************************************************
    // Rating Module methods
    // 
    // **************************************************************
    initRating: function () {

    },
    // **************************************************************
    // Utility methods
    // **************************************************************
    log: function (v) {
        if (window.console)
            console.log(v);
    },
    findPos: function (obj) {
        var curleft = curtop = 0;
        if (obj.offsetParent) {
            do {
                curleft += obj.offsetLeft;
                curtop += obj.offsetTop;
            } while (obj = obj.offsetParent);
            return [curleft, curtop];
        }
    },
    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 (days) {
            var date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            var expires = "; expires=" + date.toGMTString();
            document.cookie = name + "=" + value + expires + "; path=/";
        }
        else {
            var expires = "";
            document.cookie = name + "=" + value + expires + "; path=/; domain=" + globalDomain;
        }
    },
    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(",");
    },
    getUrlParam: function (name) {
        name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
        var regexS = "[\\?&]" + name + "=([^&#]*)";
        var regex = new RegExp(regexS);
        var results = regex.exec(window.location.href);
        if (results == null)
            return "";
        else
            return results[1];
    }
};
// 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);}

function prepRatingSystem(e) {
	var rateInfo = $(".shareBarRatings:eq("+e+") li a:first");
		
	$(".shareBarRatings:eq("+e+") ul").mouseover(function() {
		$(".shareBarRatings:eq("+e+") ul").addClass("ratingHover");				   
	});
	
	$(".shareBarRatings:eq("+e+") ul").mouseout(function() {
		$(".shareBarRatings:eq("+e+") ul").removeClass("ratingHover");		
	});
	
	$(".shareBarRatings:eq("+e+")>ul>li a").click(function() {
		rateContent(this);
		return false;
	});
}

// function to submit rating
function rateContent(el) {
	var rateResultPage = $(el).attr("href");	
	$.ajax({
		type: "GET",url: rateResultPage+"&id="+jCore.itemId+"&userid="+jCore.itemStats.userId,dataType: "json",cache:false,
		success: function(rateJSON){
			if(rateJSON.processed == true) {
				updateRating();
			} else if(rateJSON.processed == false) {
				alert("We are sorry, we were unable to save your rating at this time. Please try again later.");
			}
		}
	});
}
function updateRating() {
	var url=jCore.debugPath+"/Handlers/ItemStats.ajax";
	var data="id="+jCore.itemId+"&userid="+jCore.itemStats.userId;
	$.ajax({type: "GET", 
		   url: url, 
		   data: data,
		   dataType:"json",
		   cache:false,
	   success: function(updatedItemStatistics){
			updateRatingStats(updatedItemStatistics);
			disableRatings();
		}
	});

}

function updateRatingStats(itemStats) {
    if (itemStats.userVoted == true)
        disableRatings();
    $(".shareBarRatings p span.ratingTotalVotes").html("(" + itemStats.votes + " Votes)");
    $(".currentRating").width(itemStats.rating * 13);
    var comments = itemStats.comments;
    if (comments == 0) {
        comments = "+";
    }
    $(".shareBarComments a").html("" + comments);
}
function disableRatings() {
    $(".shareBarRatings li a").remove();
    $(".shareBarRatings ul").removeClass("ratingHover").unbind("mouseover");
}
