﻿$(window).load(function() {
    getVotes();
    $("#vote1").click(function(e) { onClick('1', 'Friends_Family'); return false; });
    $("#vote2").click(function(e) { onClick('2', 'Friends_Family'); return false; });
    $("#vote3").click(function(e) { onClick('3', 'Friends_Family'); return false; });
});

function onClick(charity, campaign) {
    //ajax call to insert vote and retrive votes

    jQuery.ajax({
        type: 'GET',
        url: '/WebServices/RenderControls.aspx?control=CharityVotes&action=insert&charity=' + charity + '&campaign=Friends_Family',
        dataType: 'html',
        success: function(html) {
            var result = RemoveScriptFromAjaxResponse(CleanAjaxResponse(html));
            var Groups = result.split(',');
            for (i = 0; i < Groups.length; i++) {
                var values = Groups[i].split('|');
                var barheight = 50 - eval(values[2]) / 100 * 50;
                $("#nat-friends-option" + values[0]).css("height", barheight.toString() + "px");
                $("#nat-friends-percent" + values[0]).html(values[2].toString() + '%');
                $("#nat-friends-votes" + values[0]).html(values[1].toString() + ' votes');
                $("#vote" + values[0]).hide();
            }
            var cookieManager = new CookieManager();
            cookieManager.setCookie(campaign, charity, 1, siteDomain);
            alert("Thank you for your vote!");
        },
        error: function() {
            alert('There was an error while try to save your vote. Please try later.');
        }
    });
}

function getVotes() {
    var cookieManager = new CookieManager();
    var votecookie = cookieManager.getValueIgnoreCase('Friends_Family');
    
    jQuery.ajax({
        type: 'GET',
        url: '/WebServices/RenderControls.aspx?control=CharityVotes&campaign=Friends_Family',
        dataType: 'html',
        success: function(html) {
            var result = RemoveScriptFromAjaxResponse(CleanAjaxResponse(html));
            var Groups = result.split(',');
            for (i = 0; i < Groups.length; i++) {
                var values = Groups[i].split('|');
                var barheight = 50 - eval(values[2]) / 100 * 50;
                $("#nat-friends-option" + values[0]).css("height", barheight.toString() + "px");
                $("#nat-friends-percent" + values[0]).html(values[2].toString() + '%');
                $("#nat-friends-votes" + values[0]).html(values[1].toString() + ' votes');
                if (votecookie) $("#vote" + values[0]).hide();
            }
        },
        error: function() {
            alert('something is wrong.....');
        }
    });
}



