﻿/*!
* Various Functions For The Member Profile Section
*/

$(document).ready(function() {
    InitializeUpload();
    InitLocation();
});

/*
* Initial Loading of Location
*/
function InitLocation() {
    if (document.location.toString().indexOf('/profile/#/Priority-Queue') > -1) {
        OpenModal(AdvocacyEditModalOptions);
    }
}

/*
Get Profile
*/
function GetProfile() {

    $.ajax({
        url: "/GetProfile",
        dataType: 'json',
        type: 'GET',
        contentType: "application/json; charset=utf-8",
        success: function(data) {

            // Parse Result
            var profile = eval(data);

            ValidateResult(profile, function() {
                $('.EditProfile')
                    .find('.DisplayName').val(profile.DisplayName).end()
                        .find('.city').val(profile.City).end()
                        .find('.state').val(profile.State).end()
                        .find('.description').val(profile.Description).end()
                        .show();
            });
        }
    });
}

/*
Hide Instructional Text
*/
function HideInstructionalText(hide) {

    if (hide) {
        $.ajax({
            url: "/HideProfileInstructionalText",
            dataType: 'json',
            type: 'GET',
            contentType: "application/json; charset=utf-8",
            success: function(data) {
            }
        });
    }
}

/*
Get Profile
*/
function GetAccountSettings() {

    $.ajax({
        url: "/GetProfile",
        dataType: 'json',
        type: 'GET',
        contentType: "application/json; charset=utf-8",
        success: function(data) {

            // Parse Result
            var account = eval(data);

            ValidateResult(account, function() {

                OpenModal(AccountModalOptions);

                $('.NotificationUpdate .NotificationResult').each(function() {

                    var notificationId = parseInt($(this).attr('rel'));

                    var checkbox = $(this).find('input[type=checkbox]').removeAttr('checked');

                    var length = account.Notifications.length;
                    for (var i = 0; i < length; i++) {
                        if (account.Notifications[i].NotificationID == notificationId && account.Notifications[i].Active == true) {
                            $(checkbox).attr('checked', 'checked');
                            break;
                        }
                    }
                });

                $('.modalAccountEdit')
                        .find('.email').val(account.Email).end()
                        .find('.displayName').val(account.DisplayName).end()
                        .show();

            });
        }
    });
}

/*
Update Profile
*/
function UpdateProfile() {

    setTimeout("$('.EditProfile').hide();", 400);

    var profile = {
        'DisplayName': $('.EditProfile .DisplayName').val(),
        'FirstName': $('.EditProfile .DisplayName').val(),
        'City': $('.EditProfile .city').val(),
        'State': $('.EditProfile .state').val(),
        'Description': $('.EditProfile .ProfileDesc textarea').val()
    };

    $.ajax({
        url: secureUrl + "/Profile/UpdateProfile",
        data: $.toJSON(profile),
        dataType: 'json',
        type: 'POST',
        contentType: "application/json; charset=utf-8",
        success: function (profile) {

            ValidateResult(profile, function () {
                $('.ReadProfile')
                        .find('.name').html(profile.DisplayName).end()
                        .find('.location').html(profile.Location).end()
                        .show();

                if (profile.Description != null && profile.Description.length > 0) {
                    $('.ReadProfile .description').html('"' + profile.Description + '"').prev().show();
                }
                else {
                    $('.ReadProfile .description').html('').prev().hide();
                }

                $('.ReadProfile .proEditLink').html(profile.Description!=null && profile.Description.length > 0 && profile.City!=null && profile.City.length>0 ? "edit your info" : "add a little more info about yourself");
                $('.loggedIn b').text(profile.DisplayName);
            },
            function () {
                if (profile.Errors.length > 0) {
                    error('Your Info', profile.Errors[0]);
                }
            });
        }
    });
}

/*
Save Found Advocacies
*/
function UpdateAdvocacySupport() {

    var advocacySupporters = new Array();

    $('.advocacyListing .AdvocaciesRemove li.AdvocacyResult:visible').each(function(i) {
        var checked = $(this).find('input').attr('checked');

        var advocacySupporter = {
            'Vote': checked,
            'AdvocacyID': $(this).attr('rel'),
            'Rank': (i + 1),
            'DefaultVote': $('.DefaultVoting select:visible').val()
        };

        advocacySupporters.push(advocacySupporter);

        // Set Correct Attributes For Redisplay
        if (checked)
            $(this).find('input').attr('checked', 'checked');
        else
            $(this).find('input').removeAttr('checked');


    });

    var votePreference = $('.DefaultVoting select:visible').val();

    $('.modalAdvocacyEdit:first').parent().empty().append($('.modal .modalAdvocacyEdit').find('.password').val('').end().clone(true));
    $('.modalAdvocacyEdit option:not(:selected)').removeAttr('selected');
    $('.modalAdvocacyEdit option[value=' + votePreference + ']').attr('selected', 'selected');

    var postData = advocacySupporters;

    $.ajax({
        url: "/UpdateAdvocacySupport",
        data: $.toJSON(postData),
        dataType: 'json',
        type: 'POST',
        contentType: "application/json; charset=utf-8",
        success: function(result) {
            DisplayAdvocacies(result);
            RemoveLoader();
            $('.modal').dialog('close');
        }
    });
}

/*
Update Priority Queue
*/
function UpdatePriorityQueue(reload) {

    var priorityQueueItems = new Array();

    $('.advocacyListing .AdvocaciesRemove li.AdvocacyResult:visible').each(function (i) {
        var checked = $(this).find('input').attr('checked');

        var priorityQueueItem = {
            'EntityID': $(this).attr('rel'),
            //'EntityTypeID': $(this).find("input[type='hidden']").val(),
            'EntityTypeID': $(this).find("#entityID").val(),
            'PriorityQueueName': $(this).find("#entityName").val(),
            'PriorityQueueRank': (i + 1),
            'DefaultVoteChar': $('.DefaultVoting select:visible').val()
        };

        priorityQueueItems.push(priorityQueueItem);

        // Set Correct Attributes For Redisplay
        if (checked)
            $(this).find('input').attr('checked', 'checked');
        else
            $(this).find('input').removeAttr('checked');


    });

    //IF THERE ARE NO ITEMS IN PRIORITY QUEUE, DEFAULT VOTING POLICY MIGHT HAVE CHANGED
    //SO WE NEED TO POPULATE THE ARRAY WITH AT LEAST ONE ITEM CONTAINING THE DEFAULT VOTING POSITION
    if (priorityQueueItems.length == 0) {
        var priorityQueueItem = {
            'DefaultVoteChar': $('.DefaultVoting select:visible').val()
        }
        priorityQueueItems.push(priorityQueueItem);
    }

    var votePreference = $('.DefaultVoting select:visible').val();

    $('.modalAdvocacyEdit:first').parent().empty().append($('.modal .modalAdvocacyEdit').find('.password').val('').end().clone(true));
    $('.modalAdvocacyEdit option:not(:selected)').removeAttr('selected');
    $('.modalAdvocacyEdit option[value=' + votePreference + ']').attr('selected', 'selected');

    var postData = priorityQueueItems;
    $.ajax({
        url: "/UpdatePriorityQueue",
        data: $.toJSON(postData),
        dataType: 'json',
        type: 'POST',
        contentType: "application/json; charset=utf-8",
        success: function (result) {
            if (reload) {
                window.location.reload();
            }
            else {
                DisplayAdvocacies(result);
                RemoveLoader();
                $('.modal').dialog('close');
            }
        }
        //error: function (result) { alert(result); }
    });
}

/**
*   Default Help Modal Options
*/

var DefaultVoteHelpOptions =
{
    title: 'Voting Policy Details',
    width: 450,
    height: 'auto',
    open: function (event, ui) {
        $(template).filter('.defaultHelpDialog').appendTo(this);
        $(this).dialog('option', 'position', 'center');
    },
    close: function (event, ui) {
        $(this).empty();
        window.location = window.location;
        //window.location = window.location + "/#/Priority-Queue";
    }
};
function JumpToQuestion(jump_to_location) {
    $('#' + jump_to_location).css('background-color', '#eeeeee');
    var new_position = $('#' + jump_to_location).offset();
    window.scrollTo(new_position.left, new_position.top); 
    return false; 
}

function LoadAdvocacyEditModal() {
    if (document.location.toString().indexOf('/profile/#/Priority-Queue') > -1) {
        window.location = window.location;
    }
    else {
        window.location = window.location + "/#/Priority-Queue";
    }
}

/**
*   Advocacy Edit Modal Options
*/
var AdvocacyEditModalOptions =
{
    title: 'Your Voting Policy',
    width: 630,
    height: 'auto',
    maxHeight: 600,
    open: function(event, ui) {
        var defaultVote = $('.modalAdvocacyEdit select').val();
        $($('.modalAdvocacyEdit').clone(true)).appendTo(this).find('select').val(defaultVote);
        $(this).dialog('option', 'position', 'center');
        InitWatermarks();
        InitializeSortables();
    },
    close: function(event, ui) {
        $(this).empty();
    }
};


/**
*   Dewire Brokerage Account Modal
*/

var DewireBrokerageOptions =
{
    title: 'Paper ballots for which accounts?',
    width: 550,
    height: 'auto',
    open: function(event, ui) {
        $('.modalRemoveBrokerage .dewireMessage').hide();
        $('.modalRemoveBrokerage .confirmTitle').hide();
        $($('.modalRemoveBrokerage').parent().html()).appendTo(this);
        $(this).find('.submitDewire').unbind("click").click(function() {
            ConfirmAccountToDewire();
        });
        $(this).find('.cancelDewire').unbind("click").click(function() {
            $('.modal').dialog('close');
            window.location = '/profile';
        });
        $(this).dialog('option', 'position', 'center');
    },
    close: function(event, ui) {
        $(this).empty();
    }
};

var DewireNoChangeOptions =
{
    title: 'You\'re still with us.',
    width: 550,
    height: 250,
    open: function(event, ui) {
        $($(template).filter('.genericSuccessDialog').html()).appendTo(this);
        $(this).find('.content').html('Your ballots will continue to be delivered through Moxy Vote, and you can vote from our site.');
        $(this).dialog('option', 'position', 'center');
    },
    close: function(event, ui) {
        $(this).empty();
        window.location = '/profile/';
    }
};

var DewireConfirmOptions =
{
    title: 'Brokerage account dewired.',
    width: 550,
    height: 250,
    open: function(event, ui) {
        $($(template).filter('.genericSuccessDialog').html()).appendTo(this);
        $(this).find('.content').html('We will notify your broker of your desire to receive paper ballots in the mail. This change should happen soon.');
        $(this).dialog('option', 'position', 'center');
    },
    close: function(event, ui) {
        $(this).empty();
        window.location = '/profile/';
    }
};

function DewireAcounts(accounts) {
    $('.modal').dialog('close');
    
    if (accounts != null && accounts.length > 0) {
        $.ajax({
            url: "/profile/DewireBrokerageAccounts",
            data: $.toJSON(accounts),
            dataType: 'json',
            type: 'POST',
            contentType: "application/json; charset=utf-8",
            success: function(result) {

                ValidateResult(result,
            function() {
                OpenModal(DewireConfirmOptions);
            },
            function() {
                error('Brokerage account dewire Error', result.Errors[0]);
                setTimeout("window.location = '/profile/';", 500);
            });

                RemoveLoader();
            }
        });
    }
}

function ConfirmAccountToDewire() {
    var accountList = new Array();
    var accounts = $('.modalRemoveBrokerage .brokerageAccts .brokerageRow').find('input[type=checkbox]:checked');
    if (accounts.length > 0) {
        $('.modalRemoveBrokerage .brokerageAccts .brokerageRow').each(function() {
            var chkBox = $(this).find('input[type=checkbox]');
            if (chkBox.attr('checked')) {
                accountList.push(chkBox.val());
                chkBox.hide();
            }
            else {
                $(this).hide();
            }
        });
        $('.modalRemoveBrokerage .submitDewire').text('Yes, Paper Please');
        $('.modalRemoveBrokerage .submitDewire').unbind("click").click(function() {
            DewireAcounts(accountList);
        });
        $('.modalRemoveBrokerage .cancelDewire').unbind("click").click(function() {
            $('.modal').dialog('close');
            OpenModal(DewireNoChangeOptions);
        });
        $('.modalRemoveBrokerage .selectTitle').hide();
        $('.modalRemoveBrokerage .dewireMessage').show();
        $('.modalRemoveBrokerage .confirmTitle').show();
    }
}

/*
*   When Sorting
*/
function OnAdvocacySort(event, ui) {
    InitLists();
    $(ui.item).parents('ul').find('.Order').each(function(i) {
        $(this).html(i + 1);
    });
}

/*
*   Initialize Advocacy Edit Sortables
*/
function InitializeSortables() {
    $(".AdvocaciesRemove").sortable({ stop: OnAdvocacySort, revert: 500, placeholder: 'SortPlaceHolder' });
    $("ul, li").disableSelection();
}

/*
*   Cancel Profile Edit
*/
function ProfileCancel() {
    $('.ReadProfile').show();
    $('.EditProfile').hide();
}

/*
Update Deleted Advocacies
*/
function RemoveAdvocacySupport(advocacyId) {

    var advocacySupporter = {
        'AdvocacyID': advocacyId,
        'Rank': 0
    };

    $.ajax({
        url: "/RemoveAdvocacySupport",
        data: $.toJSON(advocacySupporter),
        dataType: 'json',
        type: 'POST',
        contentType: "application/json; charset=utf-8",
        success: function(result) {

            ValidateResult(result,
            function() {
                DisplayAdvocacies(result.Result);
                $('.AdvocacyResult[rel=' + advocacyId + ']').remove();

            },
            function() {
                error('Edit Supported Advocate Error', result.Errors[0]);
            });

            RemoveLoader();
        }
    });
}

/*
Render Advocacy Display
*/
function DisplayAdvocacies(advocacies) {

    // Clear Advocacy Containers
    $('li.userAdvocacy').remove();

    var length = advocacies.length;
    for (var i = 0; i < length; i++) {
        // Update Profile
        $('ul.userAdvocacies').prepend('<li class="userAdvocacy"><a href="" id="' + advocacies[i].AdvocacyID + '">' + advocacies[i].Name + '</a></li>');
    }

}

/*
Link Template
*/
var linkTemplate = '<input type="text" value="Link Name" title="Link Name" class="input watermarked watermark" /><input type="text" value="Web Address" title="Web Address" class="0 input watermarked watermark" /> <a href="javascript:void(0);" onclick="$(this).parent().hide()">X</a>';

/*
Edit Links
*/
function EditLinks() {

    RemoveLoader();
    
    $('.advocacyLinks .edit').hide();
    OldLinks = $('.advocacyLinks').html();
    $('.advocacyLinks').addClass('Editing');
    $('.advocacyLinks .Hidden').show();
    $('.advocacyLinks li.Link').each(function() {
        var link = $(this);
        if (link.hasClass("NoLink")) return false;
        var linkId = link.attr('class');
        var url = link.find('a').attr('href');
        var title = link.find('a').text();

        var html = $(linkTemplate);

        html.filter('input:first').val($.trim(title));
        html.filter('input:last').attr('class', linkId).val(url);

        link.html(html);
    });
}

/*
Add New Input Link
*/
function AddNewLink() {
    $('<li class="0 Link">' + linkTemplate + '</li>').insertBefore('.advocacyLinks .Opts');
    InitWatermarks();
}

/*
Save Links
*/
function SaveLinks() {

    var links = new Array();

    $('.advocacyLinks li.Link:visible').each(function() {

        var title = ($(this).find('input:first').val() == 'Link Name') ? $(this).find('input:last').val() : $(this).find('input:first').val();
        var url = $(this).find('input:last');
        var linkId = parseInt(url.attr('class'));
        var urlValue = url.val();
        var link =
            {
                Title: title,
                LinkID: linkId,
                Url: urlValue
            }

        links.push(link);
    });

    $.ajax({
        url: "/Profile/UpdateLinks/",
        data: $.toJSON(links),
        dataType: 'json',
        type: 'POST',
        contentType: "application/json; charset=utf-8",
        success: function(data) {

            var advocacyLinks = "";

            for (var i = 0; i < data.Result.length; i++) {
                advocacyLinks += '<li class="' + data.Result[i].LinkID + ' Link"><a target="_blank" href="' + data.Result[i].Url + '">' + data.Result[i].Title + '</a></li>';
            }
            $('.advocacyLinks li').each(function() {
                if ($(this).hasClass('NoLink')) return false; ;
                $(this).remove();
            });
            $('.advocacyLinks').prepend(advocacyLinks);
            $('.advocacyLinks').removeClass('Editing');
            $('.advocacyLinks .edit').show();

            $('.NoLink .edit').html(data.Result.length > 0 ? "edit these links" : "add a link to your profile");

            if (data.Errors.length > 0) {
                error('Link Error', data.Errors[0]);
            }
        }
    });
}

/*
Cancel Link Edit
*/
var OldLinks;
function CancelLinkEdit() {
    $('.advocacyLinks').removeClass('Editing');
    $('.advocacyLinks').html(OldLinks);
    $('.advocacyLinks .edit').show();
}

/**
*   Account Modal Options
*/
var AccountModalOptions =
{
    title: 'Edit Account Settings',
    width: 562,
    height: 'auto',
    open: function(event, ui) {
        $($('.modalAccountEdit').parent().html()).appendTo(this);
        $(this).dialog('option', 'position', 'center');
        InitWatermarks();
        RemoveLoader();
    }
};

/**
*   Brokerage Modal Options
*/
var AddBrokerageModalOptions =
{
    //title: "Let's wire up your brokerage account",
    title: "Get your proxies delivered here!",
    width: 660,  // 562
    height: 620,
    open: function (event, ui) {
        var modal = this;

        $(template).filter('.modalAddBrokerageAcct').appendTo(modal);
        $(modal).dialog('option', 'position', 'center');
        InitWatermarks();

        // Init Autocomplete
        //        $(modal).find('input.brokerageInput').autocomplete('/GetBrokerages',
        //                {
        //                    delay: 0,
        //                    width: 182,
        //                    onItemSelect: FindValue
        //                });

        $(modal).find('div.validationSummary').hide();

        var dropDownContainer = $('#dropdown_container'),
            autoCompleteContainer = $('#autocomplete_container');

        dropDownContainer.find('a').click(function () {
            dropDownContainer.hide();
            autoCompleteContainer.show();

            return false;
        });

        autoCompleteContainer.find('a').click(function () {
            autoCompleteContainer.hide();
            dropDownContainer.show();

            return false;
        });

        $.ajax({
            url: '/GetBrokerages',
            dataType: 'json',
            type: 'GET',
            contentType: "application/json; charset=utf-8",
            success: function (result) {
                var options = '';

                for (var i = 0, objLength = result.length; i < objLength; i++) {
                    options += '<option value="' + result[i].BrokerageID + '">' + result[i].Name + '</option>';
                }

                $('#brokerage_select')
                    .html(options)
                    .removeAttr('disabled');
            }
        });

        RemoveLoader();
    },

    close: function (event, ui) {
        RemoveLoader();
        $(this).empty();
        $('.ac_results').hide();
    }
};



var AddBrokerageModalDetailOptions =
{
title: "Account Wiring",
width: 600,  // 562
height: 180,
open: function (event, ui) {
var modal = this;
$(template).filter('.modalAddBrokerageDetails').appendTo(modal);
$(modal).dialog('option', 'position', 'center');
$('.ui-dialog-titlebar-close').unbind('click');
$('.ui-dialog-titlebar-close').hide();
},
close: function (event, ui) {
$('.ui-dialog-titlebar-close').click(function () { CloseModal(); });
$('.ui-dialog-titlebar-close').show();
$(this).empty();
}
};

/**
*   Set ID Chosen For Brokerage Account
*/
function FindValue(li) {
    if (li != null) {
        $('.modal .Form .FormItem input[type=hidden]').val(li.extra[0]);
    }
}


/**
*   Add Brokerage To User
*/
var brokerageModalHeightWithErrors = 650;
function AddBrokerageToUser() {
    var formItemData = $('.modal #FormItemData'),
        validationContainer = $('div.validationSummary');

    var id = 0,
        brokerageName = '';

    if (!validationContainer.is(":hidden")) {
        validationContainer.hide();
    }

    if (formItemData.hasClass('FormItems')) {
        formItemData.removeClass('FormItems');
    }

    var visibleNameId = $('div.inner_form_wrap:visible').attr('id');

    if (visibleNameId == 'dropdown_container') {
        id = parseInt($('#brokerage_select').val());
    }
    else {
        brokerageName = $('input.brokerageInput').val();
    }

    var brokerageAccount =
    {
        AccountNumber: $('input.brokerageAccountNumber').val(),
        AccountName: $('input.brokerageAccountName').val(),
        FirstName: $('input.SignatoryFirstName').val(),
        Middle: $('input.SignatoryMiddle').val(),
        LastName: $('input.SignatoryLastName').val(),
        Brokerage:
        {
            BrokerageID: id,
            Name: brokerageName
        }
    };

    console.log(brokerageAccount);
    $.ajax({
        url: "/AddBrokerageToUser",
        dataType: 'json',
        data: $.toJSON(brokerageAccount),
        type: 'POST',
        contentType: "application/json; charset=utf-8",
        success: function (result) {
            ValidateResult(result, function () {
                OpenModal(AddBrokerageModalConfirmOptions);
            }, function () {

                if (!$('.modal #FormItemData').hasClass('FormItems')) {
                    $('.modal #FormItemData').addClass('FormItems');
                }
                $('.modal').height(brokerageModalHeightWithErrors);
                validationContainer.slideDown();
            });
        }
    });

    return false;
}

/**
*   Save Account Settings
*/
function SaveAccountSettings() {

    var notifications = new Array();

    $('.notificationListing .NotificationUpdate li.NotificationResult:visible').each(function() {
        var checked = $(this).find('input').attr('checked');

        var notification = {
            'Active': checked,
            'NotificationID': $(this).attr('rel')
        };

        notifications.push(notification);


        // Set Correct Attributes For Redisplay
        if (checked)
            $(this).find('input').attr('checked', 'checked');
        else
            $(this).find('input').removeAttr('checked');
    });

    var account = {
        'Email': $('.modalAccountEdit:visible .email').val(),
        'Password': $('.modalAccountEdit:visible .password').val(),
        'ConfirmPassword': $('.modalAccountEdit:visible .confirmPassword').val(),
        'Notifications': notifications
    };

    $.ajax({
        url: "/Account/SaveAccountSettings",
        data: $.toJSON(account),
        dataType: 'json',
        type: 'POST',
        contentType: "application/json; charset=utf-8",
        success: function (result) {
            ValidateResult(result, function () {
                var options = GeneralSuccessModalOptions;
                options.title = 'Account Settings Saved';
                options.open = function (event, ui) {
                    $($(template).filter('.genericSuccessDialog').html()).appendTo(this);
                    $(this).find('.content').html('Account settings were saved successfully');
                    $(this).dialog('option', 'position', 'center');
                };
                OpenModal(options);
            });
        }
    });
}

/**
*   Initialize Profile Image Upload
*/
function InitializeUpload() {
    var checkUploader = document.getElementById('uploadButton');
    if (checkUploader == null)
        return;
    var upload = new AjaxUpload($('#uploadButton'), {
        action: '/Profile/ImageUpload',
        name: 'myfile',
        responseType: 'json',
        onSubmit: function(file, ext) {
        },
        onComplete: function(file, result) {

            ValidateResult(result, function() { $('#uploadButton').css('background-image', 'url(' + result.Result + ')'); });

        }
    });

    if ($('.Photo .Upload').length > 0) {
        var upload1 = new AjaxUpload($('.Photo .Upload'), {
            action: '/Profile/ImageUpload',
            name: 'myfile',
            responseType: 'json',
            onSubmit: function(file, ext) {
            },
            onComplete: function(file, result) {

                ValidateResult(result, function() { $('#uploadButton').css('background-image', 'url(' + result.Result + ')'); });

            }
        });
    }
}

var BrokerAuthSuccessOptions =
{
    title: 'Broker Authorization Letter',
    open: function (event, ui) {
        $(template).filter('.BrokerAuthSuccessDialog').appendTo(this);
        $(this).dialog('option', 'position', 'center');
    },
    close: function (event, ui) {
        $(this).empty();
        window.location = "/profile/";
    }
};


function AuthorizeLetter(id) {
    $.ajax({
        url: "/BrokerLetter/Authorize",
        data: { 'refID': id },
        dataType: 'json',
        type: 'GET',
        contentType: "application/json; charset=utf-8",
        success: function (result) {

            ValidateResult(result, function () {
                $('.BrokerLetter .AuthFooter').hide();
                OpenModal(BrokerAuthSuccessOptions);
            });

        }
    });
}

        

