﻿/// <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);
});


$(document).ready(function () {
    if ($('.search #searchToken').autocomplete) {
        var secureAjax = (window.location.protocol == "https:") ? secureUrl + '/AjaxSearch2' : '/AjaxSearch';
        $('.search #searchToken').autocomplete(secureAjax,
                {
                    delay: 0,
                    onItemSelect: FindSearchValue,
                    width: 180,
                    formatItem: function (data, i, n, value) {
                        return "<table border='0'><tr><td valign='middle' class='photo'><img style = 'width:40px;height:40px' src='" + data[2] + "'/></td><td valign='middle' class='text'>" + data[0] + "<br />" + data[3] + "</td></tr></table>";
                    },
                    formatResult: function (data, value) {
                        return data[0];
                    }
                });
    }

});

function FindSearchValue(li) {
    if (li != null) {
        window.location = li.extra[0];
    }
}

/**
*   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: 680,
    open: function(event, ui) {
        
        $(template).filter('.flashVideoModal').show().appendTo(this);
        
        $(this).dialog('option', 'position', 'center');
        
    },
    close: function(event, ui) {
        $(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');
    }
};

/**
*   Select A Ballot By Cusip Modal
*/
var SelectBallotModalOptions =
{
    title: 'Which ballot do you want?',
    open: function(event, ui) {
        $(template).filter('.selectBallotModal').appendTo(this);
        $(this).dialog('option', 'position', 'center');
    },
    close: function(event, ui) {
        var controlNumber = $(".selectBallotInner .controlNumber").val();
        var ballotId = $("#selectBallotInput").val();

        if (controlNumber.length > 0)//We have a control number lets route to vote now
            document.location = '/Ballots/VoteNow/' + ballotId + '/' + controlNumber;
        else
            UserSelectionSelectBallot();
        $(this).empty();
    }
};

function SelectBallot(ballotId, controlNumber) {
    $.ajax({
        url: "/Ballots/GetRelatedBallots",
        data: { 'ballotId': ballotId },
        dataType: 'json',
        type: 'GET',
        contentType: "application/json; charset=utf-8",
        success: function (result) {
            OpenModal(SelectBallotModalOptions);
            if (controlNumber != null) {
                $(".selectBallotInner .controlNumber").val(controlNumber);
            }
            var options = $(".selectBallotModal #selectBallotInput");
            if (result.length > 0) {
                $(".selectBallotModal .selectBallotInner .Security").text(result[0].Company.Name);
                for (var i = 0; i < result.length; i++) {
                    var title = '';
                    if (result[i].IsContest) {
                        if (result[i].IsManagement)
                            title = ' (Management)';
                        else
                            title = ' (ShareHolder)';
                    }

                    if (controlNumber == null) {
                        options.append($("<option />").val(result[i].Url).text(result[i].Cusip + title));
                    } else {
                        options.append($("<option />").val(result[i].BallotID).text(result[i].Cusip + title));
                    }
                }
            }
        }
    });
}

function UserSelectionSelectBallot() {
    var url = $("#selectBallotInput").val();
    javascript: document.location = url;
}

/**
*   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) {
        $(this).empty();
        $($('.modalSupportConfirm').parent().html()).appendTo(this);
        $(this).dialog('option', 'position', 'center');
    },
    close: function (event, ui) {
        if (window.GoodCausesRefreshPage) {
            GoodCausesRefreshPage();
        }
        else {
            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/';
            });
        }
    });
}


/**
*   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');
    $('.modalAccountEdit .NotificationUpdate li').removeClass('Alt');
    $('.modalAccountEdit .NotificationUpdate 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 ballotIdResult = result.BallotID;

            $('.modal button').click(function() {
                AddAdvocacyToBallot(ballotIdResult, $('.potentialAdvocacies:visible').val());
            });
        }
    });
}

function AddAdvocacyToBallot(ballotId, urlPart) {
    $.ajax({
        url: "/AddAdvocacyToBallot",
        data: { 'ballotId': ballotId, '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');
    }
}

/* 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 = 455;
    var _lastModalHeight = 640
    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(["DisplayName", "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); 
    });
}
/* Warning Confirmation Modal Options */
var WarningModalOption =
{
    width: 550,
    height: 'auto',

    open: function(event, ui) {
        $(template).filter('.genericWarningDialog').appendTo(this);
        $(this).dialog('option', 'position', 'center');
    },
    close: function(event, ui) {
        window.location = window.location;
        $(this).empty();
    }
};
//Start(E1): VoteNowModal
/**
*   Set ID Chosen For Brokerage Account
*/
function FindBallot(li) {
    if (li != null) {
        $('.modalVoteNow input[type=hidden]').val(li.extra[0]);
        SetSecurityInputErrorStatus(false);
    }
}

/**
*   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
        });

        $("#security").focus();

        $(modal).find('.modalVoteNow .securityInput').keyup(function () {

            if ($('.modalVoteNow input[type=hidden]').val() > 0) {
                $('.modalVoteNow input[type=hidden]').val(0);
                SetSecurityInputErrorStatus(true);
            }
        });
    }
};

function VoteNow() {
    if (ValidateVoteNowModal()) {
        $(".controlNumVoteSubmit button").removeClass("loader");
    }
    else {
        $(".controlNumVoteSubmit button").addClass("loader");
        var ballotId = $('.modal input[type=hidden]').val();
        if (ballotId.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.');
            $(".controlNumVoteSubmit button").removeClass("loader");
            SetSecurityInputErrorStatus(true);
            return;
        }

        var controlNum = $('.modal .controlNumber').val().length;
        switch (controlNum) {
            case 0:
                $(".controlNumVoteSubmit button").removeClass("loader");
                SetControlIDErrorStatus(true, "#controlNumberError", "#controlNumberLabel", "#controlNumber");
                //error('Enter Control Number', 'You must enter the control number from the physical ballot in order to vote.');
                return;
            case 12:
                $.ajax({
                    url: "/Ballots/VaidateBallots",
                    data: $.toJSON($("#security").val()),
                    dataType: 'json',
                    type: 'POST',
                    contentType: "application/json; charset=utf-8",
                    error: function(result) {
                        $(".controlNumVoteSubmit button").removeClass("loader");
                        SetControlIDErrorStatus(true, "#controlNumberError", "#controlNumberLabel", "#controlNumber");
                    },
                    success: function(result) {
                        if (result.HasMultipleBallots) {
                            SelectBallot(result.BallotID, $('.modal .controlNumber').val());
                        }
                        else {
                            $('.modal .controlNumVoteSubmit').submit();
                        }
                    }
                });

                break;
            case 15:
            case 22:
                Warning('Ballot can\'t be voted here.', 'Unfortunately this ballot can not be voted on our site. You should be able to vote your ballot at <a href="http://www.computershare.com" target="_blank" onClick="$(\'.modal\').dialog(\'close\');">ComputerShare.com</a>', 'http://www.computershare.com');
                return;
        }
    }
}
function Warning(title, text, url) {

    var options = GeneralErrorModalOptions;
    options.title = title;
    options.open = function(event, ui) {
        $($(template).filter('.genericWarningDialog').html()).appendTo(this);
        $(this).find('.content').html(text);
        $(this).dialog('option', 'position', 'center');
    };
    OpenModal(options);
}

function OpenVoteNowModal() {
    OpenModal(VoteNowModalOptions);
    AttachVoteNowValidationEvent(".modal .Submit", 0);
    AttachVoteNowValidationEvent(".modal .Submit", 1);
}
function ClearButtonUpdate(selectorClass) {
    $(document).ready(function() {
        //Remove ButtonUpdate
        $(selectorClass + " button").removeClass("loadingIcon");
        $(selectorClass + " button span").show();
    });
}
function ValidateVoteNowModal() {
    var hasErrors = false;
    var ErrorCompanyIn = ValidateVoteNowBallotID();
    var hasErrorCnum = ValidateControlNumber();
    
    if (ErrorCompanyIn) {
        hasErrors = true;
    } else if(hasErrorCnum){
        hasErrors = true;
    }
    return hasErrors;
}
function ValidateVoteNowBallotID() {
    var hasErrors = false;
    var ballotId = $("#ballotId").val();
    var inputLength = $("#security").val().length;

    if (inputLength == 0) {
            SetSecurityInputErrorStatus(true);
            hasErrors = true;
    }
    else if (inputLength > 0 && ballotId == 0) {
    SetSecurityInputErrorStatus(true);
    hasErrors = true;
    }
    else {
        SetSecurityInputErrorStatus(false);
    }
    return hasErrors;
}
function ValidateCompanyInput() {
    var hasErrors = false;
    var inputID = "#security";

    if ($(inputID).val().length == 0) {
        SetSecurityInputErrorStatus(true);
        hasErrors = true;
    }
    else {
        $.ajax({
            url: "/Ballots/VaidateBallots",
            data: $.toJSON($(inputID).val()),
            dataType: 'json',
            type: 'POST',
            contentType: "application/json; charset=utf-8",
            error: function(result) {
            SetSecurityInputErrorStatus(true);
            },
            success: function(result) {
            SetSecurityInputErrorStatus(false);
            }
        });
        if ($(inputID).is('.invalid')) { hasErrors = true; }
    }
    return hasErrors;
}
function IsBroadRidgeControlNumber(parent) {
    path = ".controlNumber";
    if (parent != null)
        path = parent + " " + path;
    var isBroadRidge = false;
    var pattern_broadRidge = '[0-9]{12}';
    var regBroadRidge = new RegExp(pattern_broadRidge, "i");
    var text_value = $(path).val();
    
    if (regBroadRidge.test(text_value)) {
        isBroadRidge = true;
    }
    return isBroadRidge;
}
/**
*   Validate Control Number
*/
function ValidateControlNumber1(ballotId, advocacyId) {

    var controlNumber = {
        'Number': $('.modal .controlNumber').val(),
        'BallotID': ballotId
    };
    if (!ValidateControlNumber('.modal')) {

        var controlNum = controlNumber.Number.length;
        switch (controlNum) {
            case 0:
                $(".controlNumVoteSubmit button").removeClass("loader");
                SetControlIDErrorStatus(true, ".modal #controlNumberError", ".modal #controlNumberLabel", ".modal #controlNumber");
                return;
            case 12:
                $.ajax({
                    url: "/Account/ControlNumber",
                    data: $.toJSON(controlNumber),
                    dataType: 'json',
                    type: 'POST',
                    contentType: "application/json; charset=utf-8",
                    success: function (result) {
                        ValidateResult(result, function () {
                            if (advocacyId > 0) {
                                $('.ownShares .Submit').removeAttr('onclick').click(function () { GiveSupportToAdvocateForBallots(advocacyId, [propBallot]); });
                            }

                            $('.controlNumber').val(controlNumber.Number);
                            OpenModal(ConfirmBallotModalOptions);

                        },
                        function () {
                            SetControlIDErrorStatus(true, ".modal #controlNumberError", ".modal #controlNumberLabel", ".modal #controlNumber", result.Error[0]);
                        }
                        );

                        RemoveLoader();
                    }
                });
                break;
            case 15:
            case 22:
                Warning('Ballot can\'t be voted here.', 'Unfortunately this ballot can not be voted on our site. You should be able to vote your ballot at <a href="http://www.computershare.com" target="_blank" onClick="$(\'.modal\').dialog(\'close\');">ComputerShare.com</a>', 'http://www.computershare.com');
                return;
        } 
    }
}
function ValidateControlNumber(path) {
    var hasErrors = false;
    var inputID = ".controlNumber";
    var errorNumber = "#controlNumberError";
    var errorLabel = "#controlNumberLabel";
    var securityID = "#security";
    var pattern_controlId = '[A-Za-z0-9]{12,22}';
    var reg = new RegExp(pattern_controlId, "i");

    if (path != null) {
        inputID = path + " " + inputID;
        errorNumber = path + " " + errorNumber;
        errorLabel = path + " " + errorLabel;
    }

    var ctrlTxtBox = $(inputID);
    //Remove Dashes if entered
    $(inputID).val(removeDashes($(inputID).val()));
    
    var text_value = $(inputID).val();
    var c_length = text_value.length;
    
    if (reg.test(text_value)) {
        switch (c_length) {
            case 15:
            case 22:
                SetControlIDErrorStatus(false, errorNumber, errorLabel, inputID);
                if (path == null) {
                    if ($(securityID).val().length > 0 && $(securityID).is('.invalid')) 
                        { SetSecurityInputErrorStatus(false); } 
                }
                break;
            case 12:
                if (IsBroadRidgeControlNumber(path)) {
                    SetControlIDErrorStatus(false, errorNumber, errorLabel, inputID);
                }
                else {
                    SetControlIDErrorStatus(true, errorNumber, errorLabel, inputID);
                    hasErrors = true;
                }
                break;
            default:
                SetControlIDErrorStatus(true, errorNumber, errorLabel, inputID);
                hasErrors = true;
                break;
        }
    }
    else {
        SetControlIDErrorStatus(true, errorNumber, errorLabel, inputID);
        hasErrors = true;
    }
    return hasErrors;
}
function AttachVoteNowValidationEvent(selector, index) {
    $(document).ready(function() {
        $(selector).blur(function() {
            switch (index) {
                case 0:
                    ValidateVoteNowBallotID();
                    break;
                case 1:
                    ValidateControlNumber();
                    break;
            }
        });
    });      
}

function removeDashes(text) {
    var pattern = "(-+)|(\\s+)";
    var reg = new RegExp(pattern, "g");
    return text.replace(reg, '');
} //END(E1)
//Start(E2): Following Handle Display of Error on VoteNowModal
function SetControlIDErrorStatus(status, controlNumberErrorID, labelErrorID, inputControlNumberID, errorMSG) {
    if (errorMSG == null)
        errorMSG = "Please enter a valid control number from your paper ballot.";
    var inputID = inputControlNumberID;
    var labelID = labelErrorID;
    var errorID = controlNumberErrorID;
    SetErrorStatus(status, errorMSG, inputID, labelID, errorID);
}
function SetSecurityInputErrorStatus(status) {
    var errorMSG = "Please select a company from the auto-suggested list as you type.";
    var inputID = "#security";
    var labelID = "#securityLabel";
    var errorID = "#securityError";
    SetErrorStatus(status, errorMSG, inputID, labelID, errorID);
}
function SetErrorStatus(hasError, errorMSG, inputID, labelID, errorID) {
    var errorSpan = errorID + " span";
    if (hasError) {
        displayControlValidation(true, inputID, labelID, errorID);
        $(errorSpan).html(errorMSG);
    }
    else {
        displayControlValidation(false, inputID, labelID, errorID);
    }
}
function displayControlValidation(hasError, idInput, idLabel, idError) {
    var selector = idInput + ", " + idLabel;
    var valid = "valid";
    var invalid = "invalid";
    var validInvalid = valid + " " + invalid;

    $(selector).parent().removeClass(validInvalid);
    $(selector).removeClass(validInvalid);

    if (hasError) {
        $(selector).addClass(invalid);
        $(selector).parent().addClass(invalid);
        $(idError).show();
    }
    else {
        $(selector).addClass(valid);
        $(selector).parent().addClass(valid);
        $(idError).hide();
    }
} //End(E2)

function RadioFilterSearch() {
    $('#searchFilter').val($("#filterArray input[@name='filter']:checked").val());
}
function FilterSearchResults(sortTypeSTR, directionSTR, optionalFilter)
{
    $('form #page').val(1);
    if (optionalFilter)
    {
        $('#searchFilter').val(optionalFilter);
    }
    SortBallotResults(sortTypeSTR, directionSTR);
    return false;
}

function SortBallotResults(sortTypeSTR, directionSTR, optionalSortSelectedText)
{
    if (!sortTypeSTR)
    {
        sortTypeSTR = $('#sort').val() ? $('#sort').val() : "SubTitle" ;
    }
    if (!directionSTR)
    {
        directionSTR = $('#sortDirection').val() ? $('#sortDirection').val() : "ASC";
    }
    
    $('#sort').val(sortTypeSTR);
    $('#sortDirection').val(directionSTR);
    if (optionalSortSelectedText)
    {
        $('#sortSelectedText').val(optionalSortSelectedText);
    }
    $('.TopLeft a.Btn').click();
    return false;
}

function CheckBrokerage(idLONG, controlNumSTR, modObj)
{   
    function CheckBrokerVar(){
        this.ballotID = idLONG;
        this.controlNum = controlNumSTR;
    }
    
    var checkVar = new CheckBrokerVar();

    $.ajax({ url: "/CheckForBrokerage",
        data: $.toJSON(checkVar),
        dataType: 'json',
        type: 'POST',
        contentType: "application/json; charset=utf-8",
        success: function (result) {
           
            OpenModal(modObj);

            if (!result) {
                $('.modalConfirm .RContainer').css('width', 500);
                $('.ui-widget-content').css('left', 240);
                $('.ui-widget-content').css('height', 455);
                $('.ui-widget-content').css('width', 770);
                $('.modalVoteThanks .nagBannerAJAX').show();
            }

            $('.modal').dialog('option', 'position', 'center');
        } 
    });
}

function FilterOffHandler()
{
    var t = $(this);
    var os = t.offset();
    t.css('visibility', 'hidden');
    //t.hide();
    var f = $('.Filter').css(os).show();
    
    $(document.body).mouseup(function(e)
    {
        if (e.originalTarget != f[0] && $(e.originalTarget).parents('.Filter').length == 0)
        {
            f.hide();
            t.css('visibility', 'visible');
        }
    });
}
function DeleteNewsArticle(url, articleID) {
    $.ajax({
        url: "/Admin/DeleteNewsFeed/",
        data: $.toJSON(articleID),
        dataType: 'json',
        type: 'POST',
        contentType: "application/json; charset=utf-8",
        success: function(result) {
            alert("Success");
        }
    });
}

