﻿/**
*   Get Administrators Of Advocacy
*/
function GetAdmins(advocacyId, admins) {

    $('.modal .Users').empty();
    var searchTerm = $('.modal').find('input').val();
    $.ajax({
        url: "/Advocacies/GetAdmins",
        data: { 'searchToken': searchTerm, 'advocacyId': advocacyId, 'admin': admins },
        dataType: 'json',
        type: 'POST',
        success: function(result) {
            $('.modal .Info').show();
            $('.modal .Inst').remove();
            var length = result.length;

            if (admins) {
                for (var i = 0; i < length; i++) {
                    $('.modal .Admins').append('<li class="clearfix"><div class="Col">' + result[i].Name + '</div><div class="RCol"><a href="javascript:void(0);" onclick="UpdateAdmin(' + result[i].ID + ', ' + result[i].AdvocacyID + ', this);">' + (result[i].Admin ? 'Remove As Admin' : 'Add As Admin') + '</a></div></li>');
                }
            }
            else {
                // Append Non Admins
                for (var i = 0; i < length; i++) {
                    $('.modal .Users').append('<li class="clearfix"><div class="Col">' + result[i].Name + '</div><div class="RCol"><a href="javascript:void(0);" onclick="UpdateAdmin(' + result[i].ID + ', ' + result[i].AdvocacyID + ', this);">' + (result[i].Admin ? 'Remove As Admin' : 'Add As Admin') + '</a></div></li>');
                }
                if (length == 0) {
                    $('.modal .Users').append('<li class="clearfix"><div class="Col"><h4>No users found matching "' + searchTerm + '".</div></li>');
                }
            }
            InitLists();
        }
    });
}

/**
*   Remove Advocacy From User
*/
function RemoveAdvocacyFromUser(urlPart) {
    ;
    $.ajax({
        url: "/RemoveAdvocacyFromUser",
        data: { 'urlPart': urlPart },
        dataType: 'json',
        type: 'POST',
        success: function(result) {

            ValidateResult(result,
            function() {
                window.location = window.location;
            },
            function() {
                error('Administrator Error', result.Errors[0]);
            });

            RemoveLoader();
        }
    });
}

/**
*   Update Administrators Of Advocacy
*/
function UpdateAdmin(profileId, advocacyId, anchor) {

    var admin =
            {
                ID: profileId,
                AdvocacyID: advocacyId
            };

    $.ajax({
        url: "/Advocacies/UpdateAdmin",
        data: $.toJSON(admin),
        dataType: 'json',
        type: 'POST',
        contentType: "application/json; charset=utf-8",
        success: function(result) {

            ValidateResult(result, function() {

                anchor = $(anchor).html((result.Admin ? 'Remove As Admin' : 'Add As Admin'));

                if (result.Admin) {
                    anchor.parents('li:first').appendTo('ul.Admins:visible')
                }
                else {
                    anchor.parents('li:first').remove();
                }
            },
                    function() {
                        error('Administrator Error', result.Errors[0]);
                    });
        }
    });
}

/**
*   Authorize Advocacy Voting For User
*/
function AuthorizeAdvocacyVoting(authorize, urlPart) {
    if (!authorize) {
        $('.modalSupportConfirm .Err').show();
        setTimeout('RemoveLoader()', 500);
        return;
    }
    $('.modalSupportConfirm .Err').hide();
    $.ajax({
        url: "/Advocacies/AuthorizeAdvocacyVoting/",
        dataType: 'json',
        data: { 'authorize': authorize, 'urlPart': urlPart },
        type: 'POST',
        success: function(result) {
            ValidateResult(result, function() { $('.modal').dialog('close'); });
            RemoveLoader();
        }
    });


}

/*
Get Advocacy Profile
*/
function GetAdvocacyProfile(urlPart) {

    $.ajax({
        url: "/Advocacies/GetAdvocacyProfile",
        data: { 'urlPart': urlPart },
        dataType: 'json',
        type: 'GET',
        contentType: "application/json; charset=utf-8",
        success: function(data) {

            // Parse Result
            var profile = eval(data);

            ValidateResult(profile, function() {
                $('.EditProfile')
                        .resizable({ maxWidth: $('.mainCol').width(), minWidth: 160, minHeight: 173, alsoResize: $('.EditProfile').find('.ProfileDesc textarea') })
                        .find('.name').val(profile.Name).end()
                        .find('.urlPart').val(profile.UrlPart).end()
                        .find('.ProfileDesc textarea').val(profile.Description).end()
                        .find('.ProfileDesc .urlPart').val(profile.UrlPart).end()
                        .show();
            });
        }
    });
}


/*
Cancel Advacacy Profile Edit
*/
function AdvProfileCancel() {
    $('.ReadProfile .description').show();
    $('.ReadProfile .EditInfo').show();
    $('.AdvocacyNamePreview').text($('.AdvocacyNamePreview').attr('title'));
    $('.EditProfile').hide();
}

/*
Update Profile
*/
function UpdateAdvocacyProfile(urlPart) {

    var advocacy = {
        'Name': $('.EditProfile .name').val(),
        'UrlPart': $('.EditProfile .urlPart').val(),
        'Description': $('.EditProfile .ProfileDesc textarea').val()
    };

    $.ajax({
        url: "/Advocacies/UpdateAdvocacyProfile/" + urlPart,
        data: $.toJSON(advocacy),
        dataType: 'json',
        type: 'POST',
        contentType: "application/json; charset=utf-8",
        success: function(profile) {

            ValidateResult(profile, function() {
                if (urlPart == profile.UrlPart) {
                    $('.ReadProfile .description').html(profile.Description).show();
                    $('.AdvocacyName').html(profile.Name);

                    $('.EditProfile').hide();
                    $('.ReadProfile').find('.description').show().end().find('.EditInfo').show();
                }
                else {
                    window.location = '/advocates/' + profile.UrlPart;
                }

                $('.ReadProfile .EditInfo').html(profile.Description.length > 0 ? "edit your info" : "add a little more info about your advocate ");
            });
        }
    });
}


/*
Link Template
*/
var linkTemplate = '<input type="text" value="Link Name" class="watermarked watermark" /><input type="text" value="Web Address" class="watermarked watermark" /> <a href="javascript:void(0);" onclick="$(this).parent().hide()">X</a>';

/*
Edit Links
*/
function EditLinks(urlPart) {

    $('.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');
}

/*
Save Links
*/
function SaveLinks(urlPart) {

    var links = new Array();

    $('.advocacyLinks li.Link:visible').each(function () {
        var title = $(this).find('input:first').val();
        var url = $(this).find('input:last');
        var linkId = parseInt(url.attr('class'));
        if (isNaN(linkId)) { linkId = 0; }
        var urlValue = url.val();
        var link =
            {
                Title: title,
                LinkID: linkId,
                Url: urlValue
            }
        links.push(link);
    });

    $.ajax({
        url: "/Advocacies/UpdateLinks/" + urlPart,
        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 .edit').show();

            RemoveLoader();

            $('.advocacyLinks').removeClass('Editing');

            $('.NoLink .edit').html(data.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();
}

/*
Hide Instructional Text
*/
function HideInstructionalText(hide, urlPart) {

    if (hide) {
        $.ajax({
            url: "/HideInstructionalText/" + urlPart,
            dataType: 'json',
            type: 'GET',
            contentType: "application/json; charset=utf-8",
            success: function(data) {
            }
        });
    }
}

/*
Initialize Advocacy Image Upload
*/
function InitializeUpload(urlPart) {
    var upload = new AjaxUpload($('#uploadButton'), {
        action: '/Advocacies/ImageUpload/' + urlPart,
        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 upload = new AjaxUpload($('.Photo .Upload'), {
            action: '/Advocacies/ImageUpload/' + urlPart,
            name: 'myfile',
            responseType: 'json',
            onSubmit: function(file, ext) {
            },
            onComplete: function(file, result) {

                ValidateResult(result, function() { $('#uploadButton').css('background-image', 'url(' + result.Result + ')'); });

            }
        });
    }
}


/*
Initialize Advocacy Ballot Image Upload
*/
function InitializeAdvocacyBallotImageUpload(advocacyId, ballotId) {
    var upload = new AjaxUpload($('#uploadAdvocacyBallotButton'), {
        action: '/Advocacies/ImageUpload/' + advocacyId + '/' + ballotId,
        name: 'myfile',
        responseType: 'json',
        onSubmit: function(file, ext) {
        },
        onComplete: function(file, result) {

            ValidateResult(result, function() { $('#uploadAdvocacyBallotButton').css('background-image', 'url(' + result.Result + ')'); });

        },
        onError: function(e) {
        }
    });
}

/*
Delete Update
*/
function RemoveUpdate(url) {

    $.ajax({
        url: url,
        dataType: 'json',
        type: 'GET',
        contentType: "application/json; charset=utf-8",
        success: function(result) {
        }
    });
}

/*
Edit Update
*/

function EditUpdate(updateId) {
    $('#Update' + updateId + ' .EditCont .BotRight a:first').removeAttr('onclick').unbind('click').text('(Save)').click(function() {
        SaveUpdate(updateId);
    });

    $('#UploadButton' + updateId).addClass('EditingImg');
    var titleContainer = $('#Update' + updateId).find('.TopCont .TopTitle')
    var title = $.trim(titleContainer.text());
    titleContainer.html('<span style="font-weight: normal; font-size: 12px;">Title</span><br /><input style="width: 528px" type="text" value="' + title + '"/>');

    var textContentContainer = $('#Update' + updateId).find('.UpdateItemDesc .TextContent')

    if (textContentContainer.hasClass('ReadMore')) {
        textContentContainer.removeClass('ReadMore');
    }

    textContentContainer.html('<textarea class="tiny_mce">' + textContentContainer.html() + '</textarea>');
    InitializeTinyMCE();
    var textContent = $.trim(textContentContainer.html());
    //textContentContainer.html('<input name="updateText' + updateId + '" type="text" value="" style="display: none;" /><iframe id="ifrmBody' + updateId + '" class="richtextframe" scrolling="no" style="width:528px;height:170px;visibility:hidden" frameborder="0" src="/RichTextBox/richtext.aspx?refid=' + updateId + '&width=528px&height=100px&dm=' + escape(textContent) + '"></iframe>');

    //setTimeout('ShowRichTextBox(' + updateId + ')', 200);

    HideShowEditLinks();
    if ($(textContentContainer).hasClass('ReadMore')) {
        ToggleText(this);
    }
}

function SaveRichTextContent(updateId) {
//    var iframeWindow = getRichTextBoxById(updateId);
//    if (typeof (iframeWindow.readyState) == 'undefined') {
//        iframeWindow.contentWindow.__doPostBack('__Page', '');
//        if ($('#Update321').find('.UpdateItemDesc .rightArrRed').attr('href') != null) {
//            $('#Update' + updateId).find('.UpdateItemDesc .TextContent').addClass('ReadMore');
//        }
//    }
//    else {
//        if (iframeWindow.readyState == 'complete') {
//            iframeWindow.contentWindow.__doPostBack('__Page', '');
//            iframeWindow.style.visibility = 'hidden';

//            if ($('#Update321').find('.UpdateItemDesc .rightArrRed').attr('href') != null) {
//                $('#Update' + updateId).find('.UpdateItemDesc .TextContent').addClass('ReadMore');
//            }
//        }
    //    }
    return false;
}

function ShowRichTextBox(updateId) { 
    var iframeWindow = getRichTextBoxById(updateId);
    if (iframeWindow.style.visibility == 'hidden')
        iframeWindow.style.visibility = 'visible';
}

function getRichTextBoxById(updateId) {
    var iframeWindow = '#ifrmBody' + updateId;
    return $(iframeWindow)[0];
}

function PostUpdateWithId(updateId, content) {
    var textContentContainer = $('#Update' + updateId).find('.UpdateItemDesc .TextContent');
    textContentContainer.find('input').val($.trim(content));
    HideShowEditLinks();
    SaveUpdate(updateId);
}

function HideShowEditLinks() {
    $("a[innerText=(Edit)]").each(function() {
        var link = $(this);
        if (link.css('visibility') == 'inherit' || link.css('visibility') == 'visible')
            link.css('visibility', 'hidden');
        else {
            link.css('visibility', 'visible');
        }
    });
}

/*
Save Update
*/
function SaveUpdate(updateId) {
    $('#UploadButton' + updateId).removeClass('EditingImg');
    var titleContainer = $('#Update' + updateId).find('.TopCont .TopTitle');
    var textContentContainer = $('#Update' + updateId).find('.UpdateItemDesc .TextContent');

    var title = $.trim(titleContainer.find('input').val());
    var body = $.trim(textContentContainer.find('textarea').html());

    if (title.length > 0 && body.length > 0) {

        var update =
        {
            'UpdateID': updateId,
            'Title': title,
            'TextContent': body
        };

        $.ajax({
            url: '/SaveUpdate',
            data: $.toJSON(update),
            dataType: 'json',
            type: 'POST',
            contentType: "application/json; charset=utf-8",
            success: function(result) {

                ValidateResult(result,
                    function() {
                        titleContainer.html(result.Title);
                        textContentContainer.html(result.TextContent);

                        $('#Update' + updateId + ' .EditCont .BotRight a:first').unbind('click').text('(Edit)').click(function() {
                            EditUpdate(updateId);
                        });
                    },
                    function() {
                        error('Comment post failed', result.Errors[0]);
                    }
                );
            }
        });
    }
}

/*
Initialize Advocacy Update Image Upload
*/
function InitializeUpdateUpload(updateId) {

    if ($('#UploadButton' + updateId).length > 0) {
        var upload = new AjaxUpload($('#UploadButton' + updateId), {
            action: '/AdvocacyUpdateImageUpload/' + updateId,
            name: 'myfile' + updateId,
            responseType: 'json',
            onSubmit: function(file, ext) {
            },
            onComplete: function(file, result) {

                ValidateResult(result, function() { $('#UploadButton' + updateId).css('background-image', 'url(' + result.Result + ')'); });

            }
        });
    }
}

function WaitTimer(pauseTime) {
    var __self = this;
    this.Counting = false;
    this.OnTimesUp = function() {
    }
    this.Start = function() {
        __self.Counting = true;
        setTimeout(function() {
            __self.OnTimesUp(__self);
            __self.Counting = false;
        }, pauseTime);
    }
}
var UpdateUrlWaitTimer = new WaitTimer(1000);
UpdateUrlWaitTimer.OnTimesUp = function() {
    var urlCont = $('.EditProfile .ProfileUrl');
    var url = urlCont.find('.inputField').val().ToFriendlyURL();
    $.ajax({
        url: "/IsAdvocacyUrl?url=" + url,
        dataType: 'json',
        type: 'GET',
        contentType: "application/json; charset=utf-8",
        success: function(data) {
            if (data) {
                urlCont.find('.Red').show().end()
                .find('.Green').hide()
            }
            else {
                urlCont.find('.Green').show().end()
                .find('.Red').hide()
            }
        }
    });

}
function UpdateUrlAvail() {
    if (!UpdateUrlWaitTimer.Counting) {
        UpdateUrlWaitTimer.Start();
    }
}
