﻿/// <reference path="jquery-1.3.2-vsdoc.js" />

if (typeof (console) === 'undefined') {
    console = new function() { };
    console.log = function() { };
}
var InviteMeta;
$(document).ready(function() {

    InitializeModal();
    InitWatermarks();
    InitLists();
    PopulateDateValues();
    SearchEnterKeyHandler();
    InitalizeLoader();
    InitializeTinyMCE();
    $('html a[href] > button').click(function() { window.location = $(this).parent().attr('href'); });
    $('html.IE6').find('a[href=javascript:void(0);]').attr('href', '#');
    InviteMeta = new InviteMetadata(document.location);
});

/**
*   Get query param
**/
function QParams(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];
}


/**
*   Prepopulate Invite Meta
**/
function InviteMetadata(documentLocation) {
    var __self = this;
    this.Email = null;
    this.InviteCode = null;
    if (QParams('inv') && QParams('email')) {
        $.cookie('inviteCode', QParams('inv'));
        $.cookie('inviteEmail', QParams('email'));
    }
    __self.Email = $.cookie('inviteEmail');
    __self.InviteCode = $.cookie('inviteCode');
}


/**
*   Initialize Ajax Loader
*/
function InitalizeLoader() {
    $('.loader').live("click", function(e) {
        AddLoader($(e.originalTarget), 'loadingIcon');
    });
    $('.loaderRed').live("click", function(e) {
        AddLoader($(e.originalTarget), 'loadingIconRed');
    });
    $('.loaderWhite').live("click", function(e) {
        AddLoader($(e.originalTarget), 'loadingIconWhite');
    });
}

/**
*   Remove Ajax Loader
*/
function RemoveLoader(path) {

    if (path == undefined)
        path = '.loader';

    $(path).find('*').show().end().removeClass('loadingIcon');

    if (path == '.loader')
        path = '.loaderRed';

    $(path).find('*').show().end().removeClass('loadingIconRed');

    if (path == '.loaderRed')
        path = '.loaderWhite';

    $(path).find('*').show().end().removeClass('loadingIconWhite');
}

/**
*   Add Ajax Loader
*/
function AddLoader(target, style) {

    var height = target.height();
    var width = target.width();

    height += parseInt(target.css('padding-top')) + parseInt(target.css('padding-bottom'));
    width += parseInt(target.css('padding-left')) + parseInt(target.css('padding-right'));

    try {
        target.width(width).height(height).addClass(style).find('span').hide();
    }
    catch (ex) {

    }
}

/**
*   Initialize Watermarks On Text Input
*/
function InitWatermarks() {
    $('.watermarked')
            .each(function() {
                if ($(this).val() === $(this).attr('title')) $(this).addClass('watermark');
            })
            .focus(function() {
                if ($(this).val() == $(this).attr('title')) {
                    $(this).val('').removeClass('watermark');
                }
            })
            .blur(function() {
                if ($(this).val() == '') {
                    $(this).addClass('watermark').val($(this).attr('title'));
                }
            }).each(function() {
                if ($(this).val() == '') {
                    $(this).addClass('watermark').val($(this).attr('title'));
                }
                else {
                    $(this).removeClass('watermark');
                }
            });
}

/**
*   Initialize Modal
*/
function InitializeModal() {
    $('.modal').dialog({
        autoOpen: false,
        bgiframe: true,
        width: 600,
        height: 'auto',
        modal: true,
        resizable: false,
        draggable: false,
        position: 'center',
        close: function(event, ui) {
            $(this).empty();
        }
    });
}

/**
*   Login Modal Options
*/
function CloseModal() {
    $('.modal').dialog('close');
}

/**
*   Rich Text Box Editor Help Modal Options
*/

var RTEHelpOptions =
{
    title: 'Text Editor FAQ',
    width: 450,
    height: 'auto',
    open: function(event, ui) {
        $(template).filter('.RTEHelpDialog').appendTo(this);
        $(this).dialog('option', 'position', 'top');
    },
    close: function(event, ui) {
        $(this).empty();
    }
};


/**
* Tiny MCE
**/
        
function InitializeTinyMCE() {
        var options = {
            script_url: '/Scripts/tiny_mce/tiny_mce.js',
            theme: "advanced",
            theme_advanced_toolbar_location: "top",
            theme_advanced_toolbar_align: "left",
            theme_advanced_buttons1: "bold,italic,underline,strikethrough,|,link,unlink,|,justifyleft,justifycenter,justifyright,justifyfull,|,bullist,numlist",
            theme_advanced_buttons2: "",
            theme_advanced_buttons3: "",
            plugins: "advlink,paste,directionality,visualchars,nonbreaking,xhtmlxtras,template"
        };
        
        //make sure tinymce works...
        if (typeof $().tinymce === "function") {
            $('.tiny_mce').tinymce(options);
        }
}

/**
*   Login Modal Options
*/
var LoginModalOptions =
{
    title: 'Login',
    width: 620,
    height: 'auto',
    open: function(event, ui) {
        $(template).filter('.modalLogin').appendTo(this);
        $(this).find('.accountActiveMsg').addClass("hidden"); //No need for actovation message
        $(this).dialog('option', 'position', 'center');
        LoginEnterKeyHandler();
    },
    close: function(event, ui) {
        $(this).empty();
    }
};

/**
*   Login Modal Options
*/
var ActivatedLoginModalOptions =
{
    title: 'Login',
    width: 620,
    height: 'auto',
    open: function(event, ui) {
        $(template).filter('.modalLogin').appendTo(this);
        $(this).find('.accountActiveMsg').removeClass("hidden").text('Congratulations, your account has been activated.');
        $(this).dialog('option', 'position', 'center');
        LoginEnterKeyHandler();
    },
    close: function(event, ui) {
        $(this).empty();
    }
};

/**
*   Flash Video Modal Options

.ui-widget-header {border-bottom:0px solid #000;}
.ui-dialog-content {background-color: #000;}
.ui-dialog-titlebar {background-color: #000;}
.ui-widget-content {border-bottom:0px solid #000;}

*/
var FlashVideoModalOptions =
{
    title: '',
    width: 660,
    open: function(event, ui) {
        
        $(template).filter('.flashVideoModal').show().appendTo(this);
        
        $(this).dialog('option', 'position', 'center');
        
        //WORKS:
        $(".ui-widget-header").css("border-bottom-width","0px");
        $(".ui-dialog-titlebar").css('background-color', "#5D5D5D");
        $(".ui-dialog-content").css('background-color', "#5D5D5D");
        $(".ui-widget-content").css("border-width","0px");
    },
    close: function(event, ui) {
        // Reset the modal to default skin
        $(".ui-widget-header").css("border-bottom-width","1px");
        $(".ui-dialog-titlebar").css('background-color', "#F3F3F3");
        $(".ui-dialog-content").css('background-color', "#FFFFFF");
        $(".ui-widget-content").css("border-width","1px");
        $(this).empty();
    }
};

function reloadCaptcha(objParent) {
    $(objParent + ' .captchaImg').attr('src', secureUrl + '/account/GetCaptcha?' + new Date().getTime());
    setTimeout('RemoveLoader();', 500);
}


/**
*   Initialize Ajax Loader
*/
function InitalizeLoader() {
    $('.loader').live("click", function(e) {
        AddLoader($(e.originalTarget), 'loadingIcon');
    });
    $('.loaderRed').live("click", function(e) {
        AddLoader($(e.originalTarget), 'loadingIconRed');
    });
    $('.loaderWhite').live("click", function(e) {
        AddLoader($(e.originalTarget), 'loadingIconWhite');
    });
}

function CancelRegistration() {
    $.ajax({
        url: "/Account/CancelRegistration",
        data: {},
        dataType: 'json',
        type: 'Get',
        success: function(result) {

        }
    });
}

function LoadCaptcha() {
    Recaptcha.create('6Lc2VwcAAAAAAAIKaK0S1QzVznkKFZv4AeVvbbo6', 'recaptcha', {
        callback: Recaptcha.focus_response_field
    });
}

/**
*   Control Number Modal Options
*/
var ControlNumberModalOptions =
{
    title: 'Do you have a control number?',
    height: 'auto',
    open: function(event, ui) {
        $($('.modalControl').parent().html()).appendTo(this);
        $(this).dialog('option', 'position', 'center');
    }
};

/**
*   New Ballot Modal Options
*/
var NewBallotModalOptions =
{
    title: 'Add New Ballot',
    open: function(event, ui) {
        $(template).filter('.newBallotModal').appendTo(this);
        $(this).dialog('option', 'position', 'center');
    }
};

/**
*   Create Advocacy Modal Options
*/
var AdvocacyModalOptions =
{
    title: 'Create Advocate',
    width: 562,
    height: 'auto',
    open: function(event, ui) {
        $(template).filter('.modalCreateAdvocacy').appendTo(this);
        $(this).dialog('option', 'position', 'center');
        $(this).find('.validationCode').val(inviteCode);
    }
};

/**
*   Validate Invite Modal Options
*/
var InviteAdvocacyModalOptions =
{
    title: "We're invite-only, for now.",
    width: 470,
    height: 150,
    open: function(event, ui) {
        $(template).filter('.modalInviteAdvocacy').appendTo(this);
        $(this).dialog('option', 'position', 'center');
    }
};

/* General Error Modal Options
*/
var GeneralErrorModalOptions =
{
    width: 550,
    height: 'auto'
};

/* General Success Modal Options
*/
var GeneralSuccessModalOptions =
{
    width: 550,
    height: 'auto'
};

/* Add Brokerage Confirmation Modal Options */
var AddBrokerageModalConfirmOptions =
{
    title: 'Broker Confirmation',
    width: 450,
    height: 300,
    open: function(event, ui) {
        $(template).filter('.modalAddBrokerageSuccess').appendTo(this);
        $(this).dialog('option', 'position', 'center');
    },
    close: function(event, ui) {
        window.location = window.location;
        $(this).empty();
    }
};

/**
*   Advocacy Supporter Modal Options
*/
var AdvocacySupporterModalOptions =
{
    title: 'You are now a supporter!',
    width: 600,
    height: 'auto',
    open: function(event, ui) {
        $($('.modalSupportConfirm').parent().html()).appendTo(this);
        $(this).dialog('option', 'position', 'center');
    },
    close: function(event, ui) {
        window.location = window.location;
    }
};

/**
*   Add User As Supporter
*/
function AddAdvocacyToUser(urlPart) {

    $.ajax({
        url: "/Advocacies/AddAdvocacyToUser/",
        data: { 'urlPart': urlPart },
        dataType: 'json',
        type: 'POST',
        success: function(result) {
            OpenModal(AdvocacySupporterModalOptions);
            RemoveLoader();
        }
    });
}


/**
*   Open Modal
*/
function OpenModal(options) {

    if ($('.modal').dialog('isOpen')) {
        $('.modal').dialog('close');
    }

    $('.modal').dialog('option', options).dialog('open');
}

function error(title, text) {
    /// <summary>Displays an error dialog</summary>
    /// <param name="title">The error dialog's title text or HTML</param>
    /// <param name="text">The error dialog's content message text or HTML</param>

    var options = GeneralErrorModalOptions;
    options.title = title;
    options.open = function(event, ui) {
        $($(template).filter('.genericErrorDialog').html()).appendTo(this);
        $(this).find('.content').html(text);
        $(this).dialog('option', 'position', 'center');
    };
    OpenModal(options);
}
/// <summary>Displays an error dialog</summary>
/// <param name="title">The error dialog's title text or HTML</param>
/// <param name="text">The error dialog's content message text or HTML</param>
/// <param name="width">The Dialog's width</param>
/// <param name="height">The Dialog's height</param>
function ErrorWithSize(title, text, w, h) {
    var options =
        {
            width: w,
            height: h
        };
    options.title = title;
    options.open = function(event, ui) {
        $($(template).filter('.genericErrorDialog').html()).appendTo(this);
        $(this).find('.content').html(text);
        $(this).dialog('option', 'position', 'center');
    };
    OpenModal(options);
}

function success(title, text) {
    /// <summary>Displays an error dialog</summary>
    /// <param name="title">The error dialog's title text or HTML</param>
    /// <param name="text">The error dialog's content message text or HTML</param>

    var options = GeneralSuccessModalOptions;
    options.title = title;
    options.open = function(event, ui) {
        $($(template).filter('.genericSuccessDialog').html()).appendTo(this);
        $(this).find('.content').html(text);
        $(this).dialog('option', 'position', 'center');
    };
    OpenModal(options);
}


function ShowLogin() {
    $.cookie('moxyCallBackQueue', callback, { expires: 1, path: '/' });
    window.location = secureUrl + "/account/login?ReturnUrl=" + window.location;
}

function LoadCallBacks() {
    $(document).ready(function() {
        var cb = $.cookie('moxyCallBackQueue');
        var callBackQueue = new Array();
        if (cb != null) {
            //write split function if we want to extract an array
            callBackQueue.push(cb);

            if (callBackQueue != null) {
                if (callBackQueue.length > 0) {
                    for (var i = 0; i < callBackQueue.length; i++) {
                        eval('setTimeout("$(document).ready(' + callBackQueue[i] + ');",500)');
                    }
                    callBackQueue = new Array();
                    $.cookie('moxyCallBackQueue', null, { path: '/' });
                }
            }
        }
    });
}

/**
*   Show Login Modal
*/
var callback = new Array();
function Login() {
    $('.modalLogin .accountActiveMsg').hide();

    var login = {
        'Username': $('.modalLogin .username').val(),
        'Password': $('.modalLogin .password').val(),
        'RememberMe': $('.modalLogin .rememberMe').attr('checked')
    };

    $.ajax({
        url: secureUrl + '/account/authenticate/',
        data: login,
        dataType: 'json',
        type: 'post',
        success: function(result) {
            ValidateResult(result, function() {
                if (result.ReturnUrl != null && result.ReturnUrl.length > 0)
                    window.location = result.ReturnUrl;
                else
                    window.location = '/home/';
            });
        }
    });
}

/**
*   Validate Control Number
*/
function ValidateControlNumber(ballotId, advocacyId) {

    var controlNumber = {
        'Number': $('.modal .controlNumber').val(),
        'BallotID': ballotId
    };

    $.ajax({
        url: "/Account/ControlNumber",
        data: $.toJSON(controlNumber),
        dataType: 'json',
        type: 'POST',
        contentType: "application/json; charset=utf-8",
        success: function(result) {
            ValidateResult(result, function() {
                //$('.allSet .Submit').removeAttr('onclick').click(function() { OpenModal(ConfirmBallotModalOptions); });
                if (advocacyId > 0) {
                    $('.ownShares .Submit').removeAttr('onclick').click(function() { GiveSupportToAdvocateForBallots(advocacyId, [boardBallot, propBallot]); });
                }
                OpenModal(ConfirmBallotModalOptions);
                $('.confirmModal .controlNumber').val(controlNumber.Number);
            });

            RemoveLoader();
        }
    });
}

/**
*   Global Validation Summary Display
*/
function ValidateResult(result, success, fail) {

    // Check If Need To Authenticate
    if (result.Authenticate && !result.IsAuthenticated) {
        OpenModal(LoginModalOptions);
    }
    else {

        // Get Validation Container
        var validationSummary = $('.' + result.ValidationGroup + ':last').hide();

        // Clear Validation Container
        validationSummary.empty();

        if (result.Errors.length == 0) {
            if (typeof (success) === 'function') {
                success();
            }
        }
        else {
            validationSummary.show();
            var length = result.Errors.length;
            for (var i = 0; i < length; i++) {
                validationSummary.append('<li>' + result.Errors[i] + '</li>');
            }

            if (typeof (fail) === 'function') {
                fail();
            }
        }
    }

    RemoveLoader();
}

/**
*   Reset User Password
*/
function ResetPassword() {

    var resetPassword = {
        'Email': $('.resetPassword .password').val()
    };

    $.ajax({
        url: "/Account/ResetPassword",
        data: $.toJSON(resetPassword),
        dataType: 'json',
        type: 'POST',
        contentType: "application/json; charset=utf-8",
        success: function(result) {

            $('.resetPassword .password').val('');

            ValidateResult(result, function() { $('.modalLogin .resetPasswordCont').html(result.Result); });

            RemoveLoader();
        }
    });
}

/**
*   Populate Month And Year Values
*/
function PopulateDateValues() {
    var days = $('select.day');

    for (var i = 1; i < 31; i++) {
        var option = document.createElement('option');
        $(option).val(i).html(i);
        days.append(option);
    }

    var years = $('select.year');

    var currentYear = new Date().getFullYear();

    for (var i = currentYear; i > (currentYear - 100); i--) {
        var option = document.createElement('option');
        $(option).val(i).html(i);
        years.append(option);
    }
}
/**
*   Get Date
*/
function GetDate(parent) {

    var day = $(parent).find('.day').val();
    var month = parseInt($(parent).find('.month').val()) - 1;
    var year = $(parent).find('.year').val();
    var date = new Date(year, month, day);

    if (IsValidDate(day, month, year)) {
        return date.toDateString();
    }
    else {
        return null;
    }
}

function SetDate(parent, date) {

    var date = new Date(date);

    $('select.year:visible option[value=' + date.getFullYear() + ']').attr('selected', true);
    $('select.month:visible option[value=' + (date.getMonth() + 1) + ']').attr('selected', true);
    $('select.day:visible option[value=' + date.getDate() + ']').attr('selected', true);
}

/**
*   Is Valid Date
*/
function IsValidDate(day, month, year) {
    var date = new Date(year, month, day);
    return ((day == date.getDate()) && (month == date.getMonth()) && (year == date.getFullYear()));
}

/**
*   Alternating Lists
*/
function InitLists() {
    $('.simpleListing ul li').removeClass('Alt');
    $('.simpleListing ul li:even').addClass('Alt');
}


function SearchBallots() {

    $.ajax({
        url: "/Ballots/SearchBallots",
        data: { searchToken: $('.newBallotModal input').val() },
        dataType: 'json',
        type: 'GET',
        contentType: "application/json; charset=utf-8",
        success: function(data) {

            // Parse Results
            var ballots = eval(data);

            // Get Length
            var length = ballots.length;

            if (length > 0) {

                $('.newBallotModal').find('.results').empty().end().find('.resultsContainer').show();

                // Iterate Ballots
                for (var i = 0; i < length; i++) {
                    $('.newBallotModal .results').append('<div class="ballot"><span class="name">' + ballots[i].Name + '</span> <a href="/ballots/' + ballots[i].Ticker + '/Ballot/' + ballots[i].BallotID + '>View Ballot</a></div>');
                }
            }
            else {
                $('.resultsContainer').hide();
            }


        }
    });

}

/**
*   Gimme a friendly URL
*/
String.prototype.ToFriendlyURL = function() {
    //var re = new RegExp(/[^\w]*(\w+)[^\w]*/g);
    //_matches = re.exec(this);
    return this
		.toLowerCase() // change everything to lowercase
		.replace(/^\s+|\s+$/g, "") // trim leading and trailing spaces		
		.replace(/[_|\s]+/g, "-") // change all spaces and underscores to a hyphen
		.replace(/[^a-z0-9-]+/g, "") // remove all non-alphanumeric characters except the hyphen
		.replace(/[-]+/g, "-") // replace multiple instances of the hyphen with a single instance
		.replace(/^-+|-+$/g, "") // trim leading and trailing hyphens				
}

/**
*   Save Advocacy
*/
function SaveAdvocacy() {

    var advocacy = {
        Name: $('.modalCreateAdvocacy .name').val(),
        UrlPart: $('.modalCreateAdvocacy .urlPart').val(),
        Description: $('.modalCreateAdvocacy .description').val(),
        ValidationCode: $('.modalCreateAdvocacy .validationCode').val()
    };

    $.ajax({
        url: "/Advocacies/SaveAdvocacy",
        data: $.toJSON(advocacy),
        dataType: 'json',
        type: 'POST',
        contentType: "application/json; charset=utf-8",
        success: function(result) {
            ValidateResult(result, function() { document.location = result.Result });
        }
    });
}

/**
*   Validate Advocacy Code
*/
var inviteCode = null;
function ValidateAdvocacy() {

    var advocacyInvite = {
        ValidationCode: $('.modalInviteAdvocacy .code').val()
    };

    $.ajax({
        url: "InviteAdvocacy",
        data: $.toJSON(advocacyInvite),
        dataType: 'json',
        type: 'POST',
        contentType: "application/json; charset=utf-8",
        success: function(result) {
            ValidateResult(result, function() {

                inviteCode = result.ValidationCode;

                OpenModal(AdvocacyModalOptions);

            });
        }
    });
}

/**
*   Back to Top
*/
function BackToTop() {
    var rate = 0.75;
    var curr = $('html').scrollTop();
    $('html, body').animate({ scrollTop: 0 }, curr * rate);
}

/**
*   Search enter key handler
*/
function SearchEnterKeyHandler() {
    $('.search .Input').unbind('keyup').bind('keyup', function(e) {
        if (e.keyCode === 13) {
            $(this).parents('.search').find('a.Btn').click();
        }
    });
}

function LoginEnterKeyHandler() {
    $('.modalLogin').unbind('keyup').bind('keyup', function(e) {
        if (e.keyCode === 13) {
            Login();
        }
    });
}

function AddAdvocacyToBallotModal(ballotName, ballotId) {

    $.ajax({
        url: "/PotentialAdvocacies/" + ballotId,
        dataType: 'json',
        type: 'GET',
        contentType: "application/json; charset=utf-8",
        success: function(result) {

            RemoveLoader();

            OpenModal(BallotAdvocacyModalOptions);

            $('.modal').dialog('option', 'title', 'Choose Your Advocate For ' + result.Company.Name)

            // Get Select And Remove Inner Values
            var select = $('select.potentialAdvocacies').empty();

            for (var i = 0; i < result.TopAdvocates.length; i++) {

                var option = document.createElement('option');
                $(option).val(result.TopAdvocates[i].UrlPart).html(result.TopAdvocates[i].Name);
                select.append(option);
            }

            var ticker = result.Company.Ticker;

            $('.modal button').click(function() {
                AddAdvocacyToBallot(ticker, $('.potentialAdvocacies:visible').val());
            });
        }
    });
}

function AddAdvocacyToBallot(ticker, urlPart) {
    $.ajax({
        url: "/AddAdvocacyToBallot",
        data: { 'ballotTickerSymbol': ticker, 'urlPart': urlPart },
        dataType: 'json',
        type: 'POST',

        success: function(result) {

            window.location = result.Result + '/edit';
        }
    });
}

function ToggleText(link) {

    var body = $(link).parent().find('.TextContent');

    if (body.height() == 67) {
        body.height('auto').find(' ~ a').removeClass('rightArrRed').addClass('downArrRed');
    }
    else {
        body.height('67px').find(' ~ a').removeClass('downArrRed').addClass('rightArrRed');
    }
}

/**
*   Set ID Chosen For Brokerage Account
*/
function FindBallot(li) {
    if (li != null) {
        $('.modalVoteNow input[type=hidden]').val(li.extra[0]);
    }
}

/**
*   Brokerage Modal Options
*/
var VoteNowModalOptions =
{
    title: "Ballot in Hand: Vote Now",
    width: 562,
    open: function(event, ui) {
        var modal = this;

        $(template).filter('.modalVoteNow').appendTo(modal);
        $(modal).dialog('option', 'position', 'center');
        InitWatermarks();

        // Init Autocomplete
        $(modal).find('.modalVoteNow .securityInput').autocomplete('/Ballots/GetActiveBallotsList',
        {
            onItemSelect: FindBallot
        });
    }
};

function VoteNow() {
    var ticker = $('.modal input[type=hidden]').val();
    if (ticker.length == 0) {
        error('Choose Ballot First', 'You must choose a ballot for which to vote.  If you were unable to find your ballot, online voting may have already ended or may not have yet begun.');
        return;
    }

    var controlNum = $('.modal .controlNumber').val();
    if (controlNum.length == 0) {
        error('Enter Control Number', 'You must enter the control number from the physical ballot in order to vote.');
        return;
    }

    $('.modal .controlNumVoteSubmit').submit();
}




/* jquery cookie plugin - here to save requests... */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};



function Send() {

}

String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, "");
}

// Resizes the rank font-size for TopBallotsView.ascx and TopAdvocatesView.ascx
// Resizes when rank number is >= 99 and when rank number is >= 999
function ReSizeRankFont() {
    var rankFont = $('.Rank .rankNumeral');


}


//configuration / welcom proccess classes
var _upload;
function ProfileConfigurator(modal) {
    //__init__
    if (modal === null) {
        throw "a reference to the profile config modal is required to construct this class";

    } else var _jQueryModal = $(modal);
    var _self = this;
    //__end_init__
    var _initModalHeight = $('html').hasClass('IE7') ? 455 : 370;
    var _lastModalHeight = $('html').hasClass('IE7') ? 640 : 560;
    var ProfileConfiguratorModalOptions =
    {
        title: 'Welcome! Please configure your profile.',
        width: 600,
        //height: 370,
        height: _initModalHeight,
        open: OnModalOpen,
        close: OnModalClose
    };
    function OnModalOpen() {
        $(modal).appendTo(this);
    }
    function OnModalClose() {
        $(this).empty();
    }
    _self.Continue = function() {
        $('.StepOne', modal).hide();
        CloseModal();
        ProfileConfiguratorModalOptions.height = _lastModalHeight;
        OpenModal(ProfileConfiguratorModalOptions);
        $('.StepTwo', modal).show();
        AvatarPicker('.Avatars');
    }
    _self.OpenModal = function() {
        OpenModal(ProfileConfiguratorModalOptions);
    }
    var _profile = {};
    _self.PostProfile = function() {
        $.each(["FirstName", "LastName", "City", "State", "AboutMe"], function() {
            _profile[this] = _jQueryModal.find('.' + this).val(); //creates the property on _profile and sets its value = the elements value (using its class to find the element)
        });
        _profile.ValidationGroup = "ProfileValidation";
        $.post('/Profile/UpdateProfile', _profile, function(data) {
            ValidateResult(data,
            function() {
                //success
                _self.Continue();
            },
            function() {
                //fail
            });
        }, "json");
    }
    _self.Finish = function()
    {
        if (REGISTERED_WITH_ADV)
        {
            CloseModal();
            var advName = $('span.AdvocacyName').eq(0).text().trim();
            success("Success", "Welcome. You are now supporting " + advName + ". They hope you will vote your proxy ballots per their recommendations.");
        }
        else window.location = window.location;
    }
}
var FinishedRegWithAdvOptions;
$(document).ready(function()
{
FinishedRegWithAdvOptions =
{
    title: "You are aligned with " + $('span.AdvocacyName').eq(0).text().trim() || "an advocate.",
    width: 562,
    open: function(event, ui)
    {
        var modal = this;
        $(modal).empty();
        var advName = $('span.AdvocacyName').eq(0).text().trim();
        var cont = $(template).filter('.finishedRegWithAdv');
        cont.html(cont.html().replace('_ADV_', advName));
        cont.appendTo(modal);
        $('.modal').eq(0).height(100);
        $(modal).dialog('option', 'position', 'center');
    }
};
});

function AvatarPicker(avatarEl) {
    avatarEl = $(avatarEl);
    var list = $(avatarEl).find('.AvatarList');
    var perPage = 10;
    var groupings = [];
    var itemTemplate = list.find('.AvatarItem');

    function PageInto(data, outArray) {
        var group = [];
        $.each(data, function() {
            //fill up each group, if group is full make a new one
            group.push(this);
            if (group.length == perPage) {
                outArray.push(group);
                group = [];
            }
        });
        if (group.length > 0) outArray.push(group);//push any remainders
    }
    function CreateAvatarItemFromTemplate(data, template) {
        //and bind the selection click
        var el = template.clone();
        el.find('img').attr('src', data.ThumbUrl);
        el.click(function() {
            $('.modal').find('iframe').contents().find('img').attr('src', data.ThumbUrl);
            el.parent().find('*').removeClass('Selected');
            $.each(groupings, function() {
                $.each(this, function() {
                    this.removeClass('Selected');
                });
            });
            el.addClass('Selected');
            $.get('/Profile/ChooseAvatar', { AssetID: data.AssetID }, function() {

            });
        });
        return el;
    }

    $.getJSON('/Profile/GetAvatars', function(data) {
        var btns = [];
        $.each(data, function() {
            btns.push(CreateAvatarItemFromTemplate(this, itemTemplate));
        });
        PageInto(btns, groupings);
        list.empty();
        $.each(groupings, function() {
            $.each(this, function() {
                list.append(this);
            });
        });
        GotoPage(0);
    });

    function ShowGroup(i) {
        //hide all
        $.each(groupings, function() {
            $.each(this, function() {
                this.hide();
            });
        });
        //show the current page...

        $.each(groupings[i], function() {
                this.show();
        });
    }
    
    var pagerEl = avatarEl.find('.AvatarPager');
    var pagingBtnTemplate = pagerEl.find('a');
    
    //build paging controls
    function BuildPagingControls()
    {
        pagerEl.empty();
        $.each(groupings, function(i)
        {
            pagerEl.append(pagingBtnTemplate.clone().html(i + 1).click(function(){
                ShowGroup(i);
            }));
        });
    }
    
    function GotoPage(i) {
        ShowGroup(i);
        BuildPagingControls();
    }
}
    function renderNagBanner() {
    
        $.get('/NagBanner', function(theData) 
        { 
            $('.nagBannerAJAX').html(theData); 
        });
    }