﻿// Numeric only control handler
jQuery.fn.ForceNumericOnly =
function() {
    return this.each(function() {
        $(this).keydown(function(e) {
            var key = e.charCode || e.keyCode || 0;
            // allow backspace, tab, delete, arrows, numbers and keypad numbers ONLY
            return (
                key == 8 ||
                key == 9 ||
                key == 46 ||
                (key >= 37 && key <= 40) ||
                (key >= 48 && key <= 57) ||
                (key >= 96 && key <= 105));
        })
    })
};

$(document).ready(function() {
    $("textarea").each(function() {
        if ($(this).attr("infotext") != undefined && $(this).attr("infotext") != "") {
            $(this).focus(function() {
                if ($(this).attr("infotext") == $(this).val()) {
                    $(this).val("");
                    $(this).removeClass("infotext");
                }
            });

            $(this).blur(function() {
                if ($(this).attr("infotext") != $(this).val() && $(this).val() == "") {
                    $(this).val($(this).attr("infotext"));
                    $(this).addClass("infotext");
                }
            });
        }
    });
});

var ConfigureAccount = {
    adAccountId: 0,

    init: function(adaccountid, accepttextadchallenges, acceptimageadchallenges, maxrunningadcount, maxtextadsubmissioncount, maximageadsubmissioncount, login) {
        this.adAccountId = adaccountid;
        $("#lblLogin").text(login);
        $("#chkAcceptTextAds").attr('checked', (accepttextadchallenges === "true"));
        $("#chkAcceptImageAds").attr('checked', (acceptimageadchallenges === "true"));
        $("#txtRunningAdCapacity").val(maxrunningadcount);
        $("#txtTextAdSubmissionCapacity").val(maxtextadsubmissioncount);
        $("#txtImageAdSubmissionCapacity").val(maximageadsubmissioncount);
    },

    valid: function() {
        var result = true;
        if (this.adAccountId == 0) {
            result = false;
            alert('Please select an account before continuing');
        }
        if ($("#txtRunningAdCapacity").val().length == 0) {
            result = false;
            alert('Please enter a valid running ad capacity entry before continuing');
        }
        if ($("#txtTextAdSubmissionCapacity").val().length == 0) {
            result = false;
            alert('Please enter a valid text ad submission capacity entry before continuing');
        }
        if ($("#txtImageAdSubmissionCapacity").val().length == 0) {
            result = false;
            alert('Please enter a valid image ad submission capacity entry before continuing');
        }
        return result;
    },

    saveAccount: function() {
        if (this.valid() == false) { return; }
        this.ShowAdAccountProcessing();
        $.post("/Admin/UpdateAdAccount",
            {
                AdAccountID: this.adAccountId,
                AcceptTextAdChallenges: $("#chkAcceptTextAds").is(':checked'),
                AcceptImageAdChallenges: $("#chkAcceptImageAds").is(':checked'),
                MaxRunningAdCount: $("#txtRunningAdCapacity").val(),
                MaxTextAdSubmissionCount: $("#txtTextAdSubmissionCapacity").val(),
                MaxImageAdSubmissionCount: $("#txtImageAdSubmissionCapacity").val()
            },
            function(data) { ConfigureAccount.saveAccount_callback(data); }, "json");
    },

    saveAccount_callback: function(resp) {
        if (resp == "success") {
            alert('Account settings successfully saved.');
        }
        else {
            alert("Error updating account. Please try again.");
        }
        this.HideAdAccountProcessing();
        tb_remove();
    },

    ShowAdAccountProcessing: function() {
        $('#dvConfigureAccountAjax').removeClass("nodisplay");
        $('#dvConfigureAccount').addClass("ajaxContainer");
    },

    HideAdAccountProcessing: function() {
        $('#dvConfigureAccountAjax').addClass("nodisplay");
        $('#dvConfigureAccount').removeClass("ajaxContainer");
    }
}

var ConfigureFacebookAccounts = {
    adAccountId: 0,

    init: function() { },

    selectedAdAccount: function(obj) {
        var valueId = obj.options[obj.selectedIndex].value;
        if (valueId.length == 0 || valueId == this.adAccountId) {
            this.adAccountId = 0;
            return;
        }
        this.adAccountId = valueId;
        this.getAccount();
    },

    getAccount: function() {
        this.ShowAdAccountProcessing();
        $.post("/Advertiser/GetAdAccount",
            {
                AdAccountID: this.adAccountId
            },
            function(data) { ConfigureFacebookAccounts.getAccount_callback(data); }, "json");
    },

    getAccount_callback: function(resp) {
        if (resp != null) {
            $("#chkAcceptTextAds").attr('checked', resp.AcceptTextAdChallenges);
            $("#chkAcceptImageAds").attr('checked', resp.AcceptImageAdChallenges);
            $("#txtRunningAdCapacity").val(resp.MaxRunningAdCount);
            $("#txtTextAdSubmissionCapacity").val(resp.MaxTextAdSubmissionCount);
            $("#txtImageAdSubmissionCapacity").val(resp.MaxImageAdSubmissionCount);
        }
        else {
            alert("Error retrieving account information. Please try again.");
        }
        this.HideAdAccountProcessing();
    },

    valid: function() {
        var result = true;
        if (this.adAccountId == 0) {
            result = false;
            alert('Please select an account before continuing');
        }
        if ($("#txtRunningAdCapacity").val().length == 0) {
            result = false;
            alert('Please enter a valid running ad capacity entry before continuing');
        }
        if ($("#txtTextAdSubmissionCapacity").val().length == 0) {
            result = false;
            alert('Please enter a valid text ad submission capacity entry before continuing');
        }
        if ($("#txtImageAdSubmissionCapacity").val().length == 0) {
            result = false;
            alert('Please enter a valid image ad submission capacity entry before continuing');
        }
        return result;
    },

    saveAccount: function() {
        if (this.valid() == false) { return; }
        this.ShowAdAccountProcessing();
        $.post("/Advertiser/UpdateAdAccount",
            {
                AdAccountID: this.adAccountId,
                AcceptTextAdChallenges: $("#chkAcceptTextAds").is(':checked'),
                AcceptImageAdChallenges: $("#chkAcceptImageAds").is(':checked'),
                MaxRunningAdCount: $("#txtRunningAdCapacity").val(),
                MaxTextAdSubmissionCount: $("#txtTextAdSubmissionCapacity").val(),
                MaxImageAdSubmissionCount: $("#txtImageAdSubmissionCapacity").val()
            },
            function(data) { ConfigureFacebookAccounts.saveAccount_callback(data); }, "json");
    },

    saveAccount_callback: function(resp) {
        if (resp == "success") {
            alert('Account settings successfully saved.');
        }
        else {
            alert("Error updating account. Please try again.");
        }
        this.HideAdAccountProcessing();
    },

    ShowAdAccountProcessing: function() {
        ProcessOverlay.show("configureFacebookAccounts-modal");
    },

    HideAdAccountProcessing: function() {
        ProcessOverlay.hide("configureFacebookAccounts-modal");
    }
}

var EditPageStep = {
    AdAccountID: '',

    init: function() { },

    assignValue: function(adAccountID, login, password, admarketId, status) {
        this.AdAccountID = adAccountID;
        $("#ddlAdMarketList option[value='" + admarketId + "']").attr("selected", "selected");
        $("#txtAdAccountLogin").val(login);
        $("#txtAdMarketPassword").val(password);
        $("#ddlAdAccountStatus").val(status);
    },

    submitValue: function() {
        this.ShowAdAccountProcessing();
        if (this.IsValid()) {
            $.post("/Admin/AddUpdateAdAccount",
            {
                ClientMerchantID: $("#hdnClientMerchantID").val(),
                AdAccountID: this.AdAccountID,
                AdMarketID: $("#ddlAdMarketList").val(),
                Login: $("#txtAdAccountLogin").val(),
                Password: $("#txtAdMarketPassword").val(),
                Status: $("#ddlAdAccountStatus").val()
            },
            function(data) { EditPageStep.submitValue_callback(data); }, "json");
        }
    },

    submitValue_callback: function(resp) {
        if (resp == "Success") {
            //alert('Successful');
            alert("Download request has been made.");
        }
        else {
            alert("Error during edit Status, Please try again.");
        }
        this.HideAdAccountProcessing();
        tb_remove();
    },

    IsValid: function() {
        if ($.trim($("#txtAdAccountLogin").val()) == "") {
            alert("Login is required.");
            $("#txtAdAccountLogin").focus();
            return false;
        }

        if ($.trim($("#txtAdMarketPassword").val()) == "") {
            alert("Password is required.");
            $("#txtAdMarketPassword").focus();
            return false;
        }

        if ($("#ddlAdMarketList").val() == "") {
            alert("Platform is required.");
            $("#ddlAdMarketList").focus();
            return false;
        }
        return true;
    },

    ShowAdAccountProcessing: function() {
        ProcessOverlay.show("dvEditStep");
    },

    HideAdAccountProcessing: function() {
        ProcessOverlay.hide("dvEditStep");
    }

}

var ModifyUserCredits = {
    ClientMerchantID: '',

    init: function() {
        $("#ModifyUserCredits_txtAddCredits").ForceNumericOnly();
        $("#ModifyUserCredits_txtRemoveCredits").ForceNumericOnly();
    },

    Load: function(clientMerchantID) {
        this.ClientMerchantID = clientMerchantID;
        this.GetCreditsRemaining();
    },

    GetCreditsRemaining: function() {
        this.ShowProcessing();
        $.post("/Admin/GetUserCreditsRemaining",
                            {
                                ClientMerchantID: this.ClientMerchantID
                            },
                            function(data) { ModifyUserCredits.GetCreditsRemaining_callback(data); }, "json");
    },
    GetCreditsRemaining_callback: function(resp) {
        this.HideProcessing();
        if (resp.Status == "Success") {
            $('#ModifyUserCredits_CreditsRemaining').html(resp.Value)
            $('#msgCreditsRemaining').html(resp.Value)
        }
        else
            $('#ModifyUserCredits_CreditsRemaining').html("Error")

    },
    addCredits: function() {
        if ($("#ModifyUserCredits_txtAddCredits").val() == "") {
            alert("Add credits required value");
            return false;
        }

        this.ShowProcessing();
        $.post("/Admin/AddUserCredits",
                            {
                                ClientMerchantID: this.ClientMerchantID,
                                NumberOfCredits: $("#ModifyUserCredits_txtAddCredits").val()
                            },
                            function(data) { ModifyUserCredits.addCredits_callback(data); }, "json");
    },
    addCredits_callback: function(resp) {
        this.HideProcessing();
        if (resp == "Success") {
            this.GetCreditsRemaining();
        }
        else
            alert("Error adding credits, Please try again.");
        tb_remove();
    },
    removeCredits: function() {
        if ($("#ModifyUserCredits_txtRemoveCredits").val() == "") {
            alert("Remove credits required value");
            return false;
        }
        this.ShowProcessing();
        $.post("/Admin/RemoveUserCredits",
                            {
                                ClientMerchantID: this.ClientMerchantID,
                                NumberOfCredits: $("#ModifyUserCredits_txtRemoveCredits").val()
                            },
                            function(data) { ModifyUserCredits.removeCredits_callback(data); }, "json");
    },
    removeCredits_callback: function(resp) {
        this.HideProcessing();
        if (resp == "Success") {
            this.GetCreditsRemaining();
        }
        else
            alert("Error removing credits, Please try again.");
        tb_remove();
    },
    ShowProcessing: function() {
        $('#ModifyUserCreditsModal_Processing').removeClass("nodisplay");
        $('#ModifyUserCreditsModal').addClass("ajaxContainer");
    },
    HideProcessing: function() {
        $('#ModifyUserCreditsModal_Processing').addClass("nodisplay");
        $('#ModifyUserCreditsModal').removeClass("ajaxContainer");
    }
}

var ModifyBillingCycleSubscription = {
    ClientMerchantID: '',

    init: function() { },

    Load: function(clientMerchantID) {
        this.ClientMerchantID = clientMerchantID;
        this.GetBillingCycleSubscription();
    },

    GetBillingCycleSubscription: function() {
        this.ShowProcessing();
        $.post("/Admin/GetBillingCycleSubscription",
                            {
                                ClientMerchantID: this.ClientMerchantID
                            },
                            function(data) { ModifyBillingCycleSubscription.GetBillingCycleSubscription_callback(data); }, "json");
    },

    GetBillingCycleSubscription_callback: function(resp) {
        this.HideProcessing();
        if (resp.Status == "Success") {
            $("#ModifyBillingCycleSubscription_txtNumberOfCredits").val(resp.NumberOfCredits);
            $("#ModifyBillingCycleSubscription_txtChargeAmount").val(resp.ChargeAmount);
        }
        else
            alert("Error during Load, Please try again.");
    },

    Save: function() {
        this.ShowProcessing();
        $.post("/Admin/UpdateBillingCycleSubscription",
            {
                ClientMerchantID: this.ClientMerchantID,
                numberOfCredits: $("#ModifyBillingCycleSubscription_txtNumberOfCredits").val(),
                chargeAmount: $("#ModifyBillingCycleSubscription_txtChargeAmount").val()
            },
            function(data) { ModifyBillingCycleSubscription.Save_callback(data); }, "json");
    },

    Save_callback: function(resp) {
        this.HideProcessing();
        if (resp == "Success") {
            AdvertiserDetailsClient.GetBillingCycleSubscription();
            tb_remove();
        }
        else
            alert("Error during save, Please try again.");

    },

    ShowProcessing: function() {
        ProcessOverlay.show("ModifyBillingCycleSubscriptionModal");
    },

    HideProcessing: function() {
        ProcessOverlay.hide("ModifyBillingCycleSubscriptionModal");
    }
}

var ModifyBillingItemClient = {
    BillingItemID: '',

    init: function() { },

    Load: function(billingItemID) {
        this.BillingItemID = billingItemID;
        this.GetBillingItem();
    },

    GetBillingItem: function() {
        this.ShowProcessing();
        $.post("/Admin/GetBillingItem",
                            {
                                BillingItemID: this.BillingItemID
                            },
                            function(data) { ModifyBillingItemClient.GetBillingItem_callback(data); }, "json");
    },

    GetBillingItem_callback: function(resp) {
        this.HideProcessing();
        if (resp.Status == "Success") {
            $("#ModifyBillingItem_txtCreditPrice").val(resp.CreditPrice);
            $("#ModifyBillingItem_txtWriterCost").val(resp.WriterCost);
        }
        else
            alert("Error during Load, Please try again.");
    },

    Save: function() {
        this.ShowProcessing();
        $.post("/Admin/UpdateBillingItem",
            {
                BillingItemID: this.BillingItemID,
                CreditPrice: $("#ModifyBillingItem_txtCreditPrice").val(),
                WriterCost: $("#ModifyBillingItem_txtWriterCost").val()
            },
            function(data) { ModifyBillingItemClient.Save_callback(data); }, "json");
    },

    Save_callback: function(resp) {
        this.HideProcessing();
        if (resp == "Success") {
            ProductListClient.GetBillingItemList();
            tb_remove();
        }
        else
            alert("Error during save, Please try again.");

    },

    ShowProcessing: function() {
        ProcessOverlay.show("ModifyBillingItemModal");
    },

    HideProcessing: function() {
        ProcessOverlay.hide("ModifyBillingItemModal");
    }
}

var AddBillingCycleSubscription = {
    ClientMerchantID: '',

    init: function() {
        $("#AddBillingCycleSubscription_txtNumberOfCredits").ForceNumericOnly();
        $("#AddBillingCycleSubscription_txtChargeAmount").ForceNumericOnly();
    },

    Load: function(clientMerchantID) {
        this.ClientMerchantID = clientMerchantID;
    },

    Add: function() {
        if ($("#AddBillingCycleSubscription_txtNumberOfCredits").val() == "") {
            alert("Please provide Number of Credits.");
            return;
        }

        if ($("#AddBillingCycleSubscription_txtChargeAmount").val() == "") {
            alert("Please provide Charge Amount.");
            return;
        }

        this.ShowProcessing();
        $.post("/Admin/AddBillingCycleSubscription",
                {
                    ClientMerchantID: this.ClientMerchantID,
                    numberOfCredits: $("#AddBillingCycleSubscription_txtNumberOfCredits").val(),
                    chargeAmount: $("#AddBillingCycleSubscription_txtChargeAmount").val()
                },
                function(data) { AddBillingCycleSubscription.Add_callback(data); }, "json");
    },

    Add_callback: function(resp) {
        this.HideProcessing();
        if (resp == "Success") {
            AdvertiserDetailsClient.GetBillingCycleSubscription();
            tb_remove();
        }
        else
            alert("Error during add, Please try again.");
    },

    ShowProcessing: function() {
        $('#AddBillingCycleSubscriptionModal_Processing').removeClass("nodisplay");
        $('#AddBillingCycleSubscriptionModal').addClass("ajaxContainer");
    },

    HideProcessing: function() {
        $('#AddBillingCycleSubscriptionModal_Processing').addClass("nodisplay");
        $('#AddBillingCycleSubscriptionModal').removeClass("ajaxContainer");
    }
}

var ProcessBillingCycleSubscription = {
    ClientMerchantID: '',

    init: function() { },

    Load: function(clientMerchantID) {
        this.ClientMerchantID = clientMerchantID;
    },

    Process: function() {
        this.ShowProcessing();
        $.post("/Admin/ProcessBillingCycleSubscription",
                            {
                                ClientMerchantID: this.ClientMerchantID
                            },
                            function(data) { ProcessBillingCycleSubscription.Process_callback(data); }, "json");
    },
    Process_callback: function(resp) {
        this.HideProcessing();
        if (resp == "Success") {
            AdvertiserDetailsClient.GetBillingCycleSubscription();
            tb_remove();
        }
        else
            alert("Error during process, Please try again.");

    },
    ShowProcessing: function() {
        $('#ProcessBillingCycleSubscriptionModal_Processing').removeClass("nodisplay");
        $('#ProcessBillingCycleSubscriptionModal').addClass("ajaxContainer");
    },
    HideProcessing: function() {
        $('#ProcessBillingCycleSubscriptionModal_Processing').addClass("nodisplay");
        $('#ProcessBillingCycleSubscriptionModal').removeClass("ajaxContainer");
    }
}

var FBUpdateAdGroupStatusBoxControl = {
    adgroupId: 0,
    adgroupName: '',
    statusId: 0,
    statusName: '',
    useConversion: false,

    init: function(id, name, adgrouptrialstatusid, useConversion) {
        this.adgroupId = id;
        this.adgroupName = name;
        this.useConversion = useConversion;
        $("#lblFBAdGroupName").text(name);
        $("#ddlFBAdGroupTrialStatusList").val(adgrouptrialstatusid);
        if (useConversion == false) { }
        $("#chkUseConversion").attr('checked', this.useConversion);
    },

    selected: function(obj) {
        this.statusId = obj.options[obj.selectedIndex].value;
        this.statusName = obj.options[obj.selectedIndex].text;
    },

    updateStatus: function() {
        ProcessOverlay.show("FBUpdateGroupStatusBatchBox");
        this.useConversion = $("#chkUseConversion").is(':checked');
        $.post("/FacebookAdmin/UpdateAdGroupTrialStatus",
               {
                   AdGroupID: this.adgroupId,
                   AdGroupTrialStatusID: this.statusId,
                   useConversion: this.useConversion
               },
               function(data) { FBUpdateAdGroupStatusBoxControl.updateStatus_callback(data); }, "json");
    },

    updateStatus_callback: function(resp) {
        this.reset(resp);
    },

    reset: function(resp) {
        $('#message').attr('value', resp);
        ProcessOverlay.hide("FBUpdateGroupStatusBatchBox");
        tb_remove();
    }
}

var UpdateAdGroupStatusBoxControl = {
    adgroupId: 0,
    adgroupName: '',
    statusId: 0,
    statusName: '',
    prize: 0,
    useConversion: false,
    autoClose: false,
    autoActiveChallengerWin: false,

    init: function(id, prize, name, adgrouptrialstatusid, useconversion, autoclose, autoactivechallengerwin) {
        this.adgroupId = id;
        this.adgroupName = name;
        this.prize = prize;
        this.statusId = adgrouptrialstatusid;
        this.useConversion = (useconversion == "True" ? true : false);
        this.autoClose = (autoclose == "True" ? true : false);
        this.autoActiveChallengerWin = (autoactivechallengerwin == "True" ? true : false);
        $("#lblAdGroupName").text(name);
        $('#txtPrize').attr('value', prize);
        $("#ddlAdGroupTrialStatusList").val(adgrouptrialstatusid);
        $("#ddlAutoActiveChallengerWins").val("" + this.autoActiveChallengerWin);
        if (this.useConversion)
            $("#chkUseConversion").attr("checked", "true");
        else
            $("#chkUseConversion").removeAttr('checked');
        $("#ddlautoClose").val("" + this.autoClose);
    },

    selected: function(obj) {
        this.statusId = obj.options[obj.selectedIndex].value;
        this.statusName = obj.options[obj.selectedIndex].text;
    },

    updateStatus: function() {
        ProcessOverlay.show("UpdateGroupStatusBatchBox");
        this.prize = $('#txtPrize').val();
        this.statusId = $("#ddlAdGroupTrialStatusList").val();
        this.useConversion = $("#chkUseConversion").is(':checked');
        this.autoClose = $("#ddlautoClose").val();
        this.autoActiveChallengerWin = $("#ddlAutoActiveChallengerWins").val();
        $.post("/Admin/UpdateAdGroupTrialStatus",
               {
                   AdGroupID: this.adgroupId,
                   AdGroupTrialStatusID: this.statusId,
                   Prize: this.prize,
                   useConversion: this.useConversion,
                   autoClose: this.autoClose,
                   autoActiveChallengerWin: this.autoActiveChallengerWin
               },
               function(data) { UpdateAdGroupStatusBoxControl.updateStatus_callback(data); }, "json");
    },

    updateStatus_callback: function(resp) {
        this.reset(resp);
    },

    reset: function(resp) {
        $('#message').attr('value', resp);
        ProcessOverlay.hide("UpdateGroupStatusBatchBox");
        tb_remove();
    }
}

var DeleteReportRequestBoxControl = {
    reportrequestId: 0,
    reportrequestName: '',

    init: function(id, name) {
        this.reportrequestId = id;
        this.reportrequestName = name;
        ProcessOverlay.hide('DeleteReportRequestBox');
        $("#lblRequestName").text(name);
    },

    deleteItem: function() {
        ProcessOverlay.show('DeleteReportRequestBox');

        $.post("/Admin/DeleteReportRequest",
               {
                   ReportRequestID: this.reportrequestId
               },
               function(data) { DeleteReportRequestBoxControl.delete_callback(data); }, "json");
    },

    delete_callback: function(resp) {
        this.reset(resp);
    },

    reset: function(resp) {
        $('#message').attr('value', resp);
        ProcessOverlay.hide('DeleteReportRequestBox');
        tb_remove();
    }
}

var DeleteReportSubscriptionBoxControl = {
    reportsubscriptionId: 0,
    reportsubscriptionName: '',

    init: function(id, name) {
        this.reportsubscriptionId = id;
        this.reportsubscriptionName = name;
        ProcessOverlay.hide('DeleteReportSubscriptionBox');
        $("#lblSubscriptionName").text(name);
    },

    deleteItem: function() {
        ProcessOverlay.show('DeleteReportSubscriptionBox');

        $.post("/Admin/DeleteReportSubscription",
               {
                   ReportSubscriptionID: this.reportsubscriptionId
               },
               function(data) { DeleteReportSubscriptionBoxControl.delete_callback(data); }, "json");
    },

    delete_callback: function(resp) {
        this.reset(resp);
    },

    reset: function(resp) {
        $('#message').attr('value', resp);
        ProcessOverlay.hide('DeleteReportSubscriptionBox');
        tb_remove();
    }
}

var AddAdGroupImageBoxControl = {
    adgroupId: 0,
    adgroupName: '',

    init: function(adgroupid, adgroupname) {
        this.adgroupId = adgroupid;
        this.adgroupName = adgroupname;
        this.clear();
        $("#lblAdGroupName").text(adgroupname);
    },

    clear: function() {
        ProcessOverlay.hide('AddAdGroupImageBatchBox');
        $('#txtAdImageNameValidate').addClass("nodisplay");
        $('#txtAdImageNameValidate').attr('value', '');
        $("#txtAdImageFileValidate").addClass("nodisplay");
        $("#txtAdImageFileValidate").attr('value', '');
        $('#txtAdImageDescriptionValidate').addClass("nodisplay");
        $("#txtAdImageDescriptionValidate").attr('value', '');
        $("#txtAdImageFile").attr('value', '');
        $("#txtAdImageName").attr('value', '');
        $("#txtAdImageDescription").attr('value', '');
        $('#message').attr('value', '');
        $("#lblAdGroupName").text('');
    },

    validateFileType: function(file) {
        if (file.indexOf(".gif") > 0) {
            return true;
        }
        if (file.indexOf(".jpg") > 0) {
            return true;
        }
        if (file.indexOf(".jpeg") > 0) {
            return true;
        }
        if (file.indexOf(".jpg") > 0) {
            return true;
        }
        if (file.indexOf(".png") > 0) {
            return true;
        }
        return false;
    },

    addValidate: function() {
        if (this.validate() == false) { return false; }
        ProcessOverlay.show('AddAdGroupImageBatchBox');
    },

    validate: function() {

        if ($("#ddlCampaignGroup").length != 0) {
            var adgroup = $("#ddlCampaignGroup").val();
            if (adgroup.length == 0) {
                $("#txtAdGroupValidate").text('Please select an item before continuing.');
                $('#txtAdGroupValidate').removeClass("nodisplay");
                return false;
            }
        }

        var file = $("#txtAdImageFile").val();
        if (file.length == 0) {
            $("#txtAdImageFileValidate").text('Please select file before continuing.');
            $('#txtAdImageFileValidate').removeClass("nodisplay");
            return false;
        }

        if (this.validateFileType(file) == false) {
            $("#txtAdImageFileValidate").text('Invalid file type. File must be in gif, jpeg, jpg, or png format.');
            $('#txtAdImageFileValidate').removeClass("nodisplay");
            $("#txtAdImageFile").attr('value', '');
            return false;
        }

        var name = $("#txtAdImageName").val();
        if (name.length == 0) {
            $("#txtAdImageNameValidate").text('Please enter name before continuing.');
            $('#txtAdImageNameValidate').removeClass("nodisplay");
            return false;
        }
        if (name.length > 100) {
            $("#txtAdImageNameValidate").text('Name cannot exceed 100 characters.');
            $('#txtAdImageNameValidate').removeClass("nodisplay");
            $("#txtAdImageName").attr('value', '');
            return false;
        }

        var description = $("#txtAdImageDescription").val();
        if (description.length == 0) {
            $("#txtAdImageDescriptionValidate").text('Please enter description before continuing.');
            $('#txtAdImageDescriptionValidate').removeClass("nodisplay");
            return false;
        }
        if (description.length > 1000) {
            $("#txtAdImageDescriptionValidate").text('Description cannot exceed 1000 characters.');
            $('#txtAdImageDescriptionValidate').removeClass("nodisplay");
            $("#txtAdImageDescription").attr('value', '');
            return false;
        }

        return true;
    },

    add: function() {
        if (this.validate() == false) { return false; }
        ProcessOverlay.show('AddAdGroupImageBatchBox');

        $.post("/Admin/AddAdGroupImage",
               {
                   AdGroupID: this.adgroupId,
                   File: file,
                   Name: name,
                   Description: description,
                   IsHiddenFromWriter: ishidden
               },
               function(data) { AddAdGroupImageBoxControl.add_callback(data); }, "json");
    },

    add_callback: function(resp) {
        this.reset(resp);
    },

    reset: function(resp) {
        this.clear();
        $('#message').attr('value', resp);
        ProcessOverlay.hide('AddAdGroupImageBatchBox');
        tb_remove();
    }
}

var DeleteAdGroupImageBoxControl = {
    adgroupimageId: 0,
    adgroupName: '',

    init: function(adgroupimageid, adgroupname) {
        this.adgroupimageId = adgroupimageid;
        this.adgroupName = adgroupname;
        ProcessOverlay.hide('DeleteAdGroupImageBatchBox');
        $("#lblDeleteAdGroupName").text(adgroupname);
    },

    deleteItem: function() {
        ProcessOverlay.show('DeleteAdGroupImageBatchBox');

        $.post("/Admin/DeleteAdGroupImage",
               {
                   AdGroupImageID: this.adgroupimageId
               },
               function(data) { DeleteAdGroupImageBoxControl.delete_callback(data); }, "json");
    },

    delete_callback: function(resp) {
        this.reset(resp);
    },

    reset: function(resp) {
        $('#message').attr('value', resp);
        ProcessOverlay.hide('DeleteAdGroupImageBatchBox');
        tb_remove();
    }
}

var UpdateAdGroupImageBoxControl = {
    adgroupimageId: 0,
    adgroupName: '',
    name: '',
    description: '',
    isHidden: false,

    init: function(adgroupimageid, adgroupname, name, description, ishidden) {
        this.adgroupimageId = adgroupimageid;
        this.adgroupName = adgroupname;
        this.name = name;
        this.description = description;
        this.isHidden = ishidden;
        this.clear();
        $("#lblUpdateAdGroupName").text(adgroupname);
        $("#txtUpdateName").attr('value', name);
        $("#txtUpdateDescription").attr('value', description);
        $('#chkUpdateHiddenFromWritter').attr('checked', ishidden);
    },

    clear: function() {
        ProcessOverlay.hide('UpdateAdGroupImageBatchBox');
        $('#txtUpdateNameValidate').addClass("nodisplay");
        $('#txtUpdateNameValidate').attr('value', '');
        $('#txtUpdateDescriptionValidate').addClass("nodisplay");
        $("#txtUpdateDescriptionValidate").attr('value', '');
        $("#txtUpdateName").attr('value', '');
        $("#txtUpdateDescription").attr('value', '');
    },

    validate: function() {

        var name = $("#txtUpdateName").val();
        if (name.length == 0) {
            $("#txtUpdateNameValidate").text('Please enter name before continuing.');
            $('#txtUpdateNameValidate').removeClass("nodisplay");
            return false;
        }
        if (name.length > 100) {
            $("#txtUpdateNameValidate").text('Name cannot exceed 100 characters.');
            $('#txtUpdateNameValidate').removeClass("nodisplay");
            $("#txtUpdateName").attr('value', '');
            return false;
        }

        var description = $("#txtUpdateDescription").val();
        if (description.length == 0) {
            $("#txtUpdateDescriptionValidate").text('Please enter description before continuing.');
            $('#txtUpdateDescriptionValidate').removeClass("nodisplay");
            return false;
        }
        if (description.length > 1000) {
            $("#txtUpdateDescriptionValidate").text('Description cannot exceed 1000 characters.');
            $('#txtUpdateDescriptionValidate').removeClass("nodisplay");
            $("#txtUpdateDescription").attr('value', '');
            return false;
        }

        return true;
    },

    update: function() {
        if (this.validate() == false) { return false; }
        ProcessOverlay.show('UpdateAdGroupImageBatchBox');

        this.name = $("#txtUpdateName").val();
        this.description = $("#txtUpdateDescription").val();
        this.isHidden = $('#chkUpdateHiddenFromWritter').is(':checked');
        $.post("/Admin/UpdateAdGroupImage",
               {
                   AdGroupImageID: this.adgroupimageId,
                   Name: this.name,
                   Description: this.description,
                   IsHiddenFromWriter: this.isHidden
               },
               function(data) { UpdateAdGroupImageBoxControl.update_callback(data); }, "json");
    },

    update_callback: function(resp) {
        this.reset(resp);
    },

    reset: function(resp) {
        this.clear();
        $('#message').attr('value', resp);
        ProcessOverlay.hide('UpdateAdGroupImageBatchBox');
        tb_remove();
    }
}

var UpdateContestAdsBoxControl = {
    adgroupid: 0,
    contestupdate: false,
    champheadline: '',
    champline1: '',
    champline2: '',
    champdisplayurl: '',
    champdestinationurl: '',
    challheadline: '',
    challline1: '',
    challline2: '',
    challdisplayurl: '',
    challdestinationurl: '',

    init: function() { },

    getAdBlock: function(displayurl, headline, line1, line2, trialadwordstatus) {
        var sb = "";
        sb += "<div class='boostab' style='width: 280px;'> ";
        sb += "<a class='main headline' href='";
        sb += displayurl + "'>";
        sb += headline + "</a> ";
        sb += "<p>";
        sb += line1 + "<br />" + line2 + "</p> ";
        sb += "<a class='site' href='";
        sb += displayurl + "'>";
        sb += displayurl + "</a> ";
        sb += "</div>";
        return sb;
    },

    updateContest: function() {
        var destinationurl = $.trim($('#editchallurldestination').val());
        if (destinationurl.startsWith("http://") == false && destinationurl.startsWith("https://") == false) {
            alert("Please provide http or https in challenger destination url");
            return;
        }

        destinationurl = $.trim($('#editchampurldestination').val());
        if (destinationurl.startsWith("http://") == false && destinationurl.startsWith("https://") == false) {
            alert("Please provide http or https in champion destination url");
            return;
        }

        var totalAdText = $.trim($('#editchampheadline').val()) + $.trim($("#editchampline1").val()) + $.trim($("#editchampline2").val());
        var cCheck = totalAdText.match(/!/ig) || [];
        if (cCheck.length > 1) {
            alert("No more than one exclamation point (!) allowed in ad.");
            return;
        }

        totalAdText = $.trim($('#editchallheadline').val()) + $.trim($("#editchallline1").val()) + $.trim($("#editchallline2").val());
        cCheck = totalAdText.match(/!/ig) || [];
        if (cCheck.length > 1) {
            alert("No more than one exclamation point (!) allowed in ad.");
            return;
        }

        if (this.contestupdate == false) {
            //spell checking ===================
            //Since spellchecker is designed to check 1 field at a time, multiple field spellcheck is done
            //using the callback function of the previous check
            myChecker = new SpellChecker();
            //tb_remove();
            myChecker.checkSpelling($('#editchampheadline'), function(status) {
                if (status)
                    myChecker.checkSpelling($('#editchampline1'), function(status) {
                        if (status)
                            myChecker.checkSpelling($('#editchampline2'), function(status) {
                                if (status)
                                    myChecker.checkSpelling($('#editchallheadline'), function(status) {
                                        if (status)
                                            myChecker.checkSpelling($('#editchallline1'), function(status) {
                                                if (status)
                                                    myChecker.checkSpelling($('#editchallline2'), function(status) {
                                                        if (status) {
                                                            //$("#btnEdit").click();
                                                            ProcessOverlay.show('dvEditAds');
                                                            $("#btnUpdateContest").removeClass("contestgreenbutton");
                                                            $("#btnUpdateContest").addClass("contestgraybutton");
                                                            this.contestupdate = true;

                                                            this.champheadline = $.trim($('#editchampheadline').val());
                                                            this.champline1 = $.trim($('#editchampline1').val());
                                                            this.champline2 = $.trim($('#editchampline2').val());
                                                            this.champdisplayurl = $.trim($('#editchampurldisplay').val());
                                                            this.champdestinationurl = $.trim($('#editchampurldestination').val());
                                                            this.challheadline = $.trim($('#editchallheadline').val());
                                                            this.challline1 = $.trim($('#editchallline1').val());
                                                            this.challline2 = $.trim($('#editchallline2').val());
                                                            this.challdisplayurl = $.trim($('#editchallurldisplay').val());
                                                            this.challdestinationurl = $.trim($('#editchallurldestination').val());
                                                            this.adgroupid = $('#hdnAdGroupID').val();

                                                            //This is the code that saves the ad
                                                            $.post("/Advertiser/UpdateContest",
                                                                   {
                                                                       AdGroupID: this.adgroupid,
                                                                       ChampionHeadline: this.champheadline,
                                                                       ChampionLine1: this.champline1,
                                                                       ChampionLine2: this.champline2,
                                                                       ChampionDisplayUrl: this.champdisplayurl,
                                                                       ChampionDestinationUrl: this.champdestinationurl,
                                                                       ChallengerHeadline: this.challheadline,
                                                                       ChallengerLine1: this.challline1,
                                                                       ChallengerLine2: this.challline2,
                                                                       ChallengerDisplayUrl: this.challdisplayurl,
                                                                       ChallengerDestinationUrl: this.challdestinationurl
                                                                   },
                                                                   function(data) { UpdateContestAdsBoxControl.updateContest_callback(data); }, "json");
                                                        }
                                                    })
                                            })
                                    })
                            })
                    })
            })
        }
    },

    updateContest_callback: function(response) {
        $("#btnUpdateContest").removeClass("contestgraybutton");
        $("#btnUpdateContest").addClass("contestgreenbutton");
        this.contestupdate = false;

        if (response.ErrorList.length > 0) {
            if (response.ErrorList[0].ErrorMessage.indexOf("login failed") > 0) {
                $("#lblUpdateErrorMsg").html(response.ErrorList[0].ErrorMessage + "<br/>" + "Please go to <b>\"Account &amp; Setting\"<b/> option from Header, " + "<br/>" + "Open <b>\"Edit Network Accounts\"<b/> option and verify your account credentials.");
            }
            else {
                $("#lblUpdateErrorMsg").html(response.ErrorList[0].ErrorMessage);
            }
            $('#updateerrorsummary').removeClass("nodisplay");
            setTimeout("$('#updateerrorsummary').addClass('nodisplay');", 10000);
            ProcessOverlay.hide('dvEditAds');
            return;
        }
        else if (response.IsRedirect) {
            window.location.href = response.Redirect;
            alert('Contest updated successfully');
        }

        $('#updateerrorsummary').addClass('nodisplay');
        ProcessOverlay.hide('dvEditAds');
        tb_remove();
    }
}


var AnswerBoxControl = {
    init: function() { },
    postId: 0,
    answerResponse: null,

    setCurrentPost: function(postid) {
        this.postId = postid;
    },

    reset: function(resp) {
        $("#txtAnswerMessage").attr('value', '');
        this.answerResponse = resp;
        this.postId = 0;
        tb_remove();
        ProcessOverlay.hide('dvAnswerAdd');
    },

    answerQuestion: function() {
        if ($.trim($("#txtAnswerMessage").val()) == "") {
            alert("Please enter reply");
            return;
        }
        ProcessOverlay.show('dvAnswerAdd');
        $.post("/Advertiser/AnswerQuestion",
                {
                    PostID: this.postId,
                    Message: $("#txtAnswerMessage").val()
                },
                function(data) { AnswerBoxControl.answerQuestion_callback(data); }, "json");
    },

    answerQuestion_callback: function(resp) {
        var newRow = AnswerBoxControl.getRow(resp);
        $("#btnReply_" + resp.TopicID).addClass("nodisplay");
        $("#dvPosts_" + resp.TopicID).append(newRow);
        this.reset(resp);
    },

    getRow: function(obj) {
        var content = "";
        var content = "<b>";
        content += $("#hdnUserName").val();
        content += "&nbsp;message:</b>&nbsp;&nbsp;";
        content += obj.Message;
        content += "<br /><br />";
        return content;
    }
}

var AdChallengeBatchControl = {
    adChallengeIdList: '',
    adChallengeBatchResponse: '',

    init: function() {
        $('#chkSelectorAll').click(this.checkAll);
    },

    checkAll: function() {
        var checked_status = this.checked;
        $("input[type='checkbox'][name='chkSelector']").click();
        $("input[type='checkbox'][name='chkSelector']").attr('checked', checked_status);
        AdChallengeBatchControl.adChallengeIdList = '';
    },

    checkItem: function(checked, selectid) {
        if (checked) {
            AdChallengeBatchControl.addChallenge(selectid);
        }
        else {
            AdChallengeBatchControl.removeChallenge(selectid);
        }
    },

    addChallenge: function(challengeid) {
        if (this.adChallengeIdList.search(challengeid) == -1) {
            this.adChallengeIdList += challengeid + ",";
        }
    },

    removeChallenge: function(challengeid) {
        if (this.adChallengeIdList.search(challengeid) == -1) { return; } //doesn't exist return
        if (this.adChallengeIdList.search(challengeid + ",") == -1) {
            this.adChallengeIdList = this.adChallengeIdList.replace(challengeid, "");
        }
        else {
            this.adChallengeIdList = this.adChallengeIdList.replace(challengeid + ",", "");
        }
    },

    getAdChallengeList: function(adchallengestatus, isreject, isapprove) {
        ProcessOverlay.show('AdChallengeBatchBox');
        $.get("/PartialView/AdChallengeBatch",
               {
                   AdChallengeStatus: adchallengestatus,
                   IsReject: isreject,
                   IsApprove: isapprove
               },
               function(data) { AdChallengeBatchControl.getAdChallengeList_callback(data); });
    },

    getAdChallengeList_callback: function(resp) {
        this.reset(resp);
    },

    approveAdList: function() {
        ProcessOverlay.show('AdChallengeBatchBox');
        try {
            $.post("/PartialView/ApproveAdChallengeList",
               {
                   AdChallengeIdList: this.adChallengeIdList
               },
               function(data) {
                   if (data == null) {
                       TopMessageAlert.showAlert("No response return from server.");
                   }
                   AdChallengeBatchControl.approveAdList_callback(data);
               }, "json");
        } catch (e) {
            TopMessageAlert.showAlert("Error: " + e);
        }
    },

    approveAdList_callback: function(resp) {
        this.reset(resp);
    },

    rejectAdList: function() {
        if (this.adChallengeIdList == '') {
            alert('No items selected.');
            return;
        }

        if ($("#txtBatchReasonDescription").val() == "Your reason for rejection will be visible to future writers so please provide detailed feedback" || $("#txtBatchReasonDescription").val().length < 2) {
            $(".rejecterror-box").removeClass("nodisplay");
        }
        else {
            ProcessOverlay.show('AdChallengeBatchBox');

            $("#txtBatchReasonDescription").val($("#txtBatchReasonDescription").val());

            try {
                $.post("/PartialView/RejectAdChallengeList",
                {
                    AdChallengeIdList: this.adChallengeIdList,
                    Reason: $('input[name=batchreason]:checked').val(),
                    ReasonDescription: $("#txtBatchReasonDescription").val()
                },
                function(data) {
                    if (data == null) {
                        TopMessageAlert.showAlert("No response return from server.");
                    }
                    AdChallengeBatchControl.rejectAd_callback(data);
                }, "json");
            } catch (e) {
                TopMessageAlert.showAlert("Error: " + e);
            }
        }
    },

    rejectAdList_callback: function(resp) {
        this.reset(resp);
    },

    reset: function(resp) {
        $("#txtBatchReasonDescription").attr('value', 'Your reason for rejection will be visible to future writers so please provide detailed feedback');
        this.adChallengeIdList = '';
        tb_remove();
        ProcessOverlay.hide('AdChallengeBatchBox');
    },

    resetReason: function() {
        if ($("#txtBatchReasonDescription").attr('value') == "")
            $("#txtBatchReasonDescription").attr('value', "");
    }
}

var RejectAdBoxControl = {
    init: function() {
        $(".rejecterror-box").addClass("nodisplay");
    },
    adChallengeId: 0,
    adGroupId: 0,
    adChallengeIds: '',
    rejectedTerms: '',
    adTrialId: 0,
    rejectResponse: null,

    setCurrentChallenge: function(adchallengeid) {
        this.adChallengeId = adchallengeid;
        if (this.adChallengeIds != "")
            this.adChallengeIds == "";
        $("#PastRejection").addClass("nodisplay");
        $("#AddBlockListWriter").removeClass("nodisplay");
        $("#PastRejection").html("");
        $("#linkShowPastReason").addClass("plussign").removeClass("minussign");
    },

    setRejectedTerms: function(rejectedterms) {
        if (this.rejectedTerms == "") {
            this.rejectedTerms = rejectedterms;
        }
        if (this.rejectedTerms != "") {
            $("#txtRejectedTerms").val(this.rejectedTerms);
            $("#txtRejectedTerms").removeClass("infotext");
        }
    },

    setMultiChallenge: function(adchallengeids) {
        this.adChallengeIds = adchallengeids;
        this.adChallengeId = 0;
        $("#AddBlockListWriter").addClass("nodisplay");
    },

    setCurrentTrial: function(adtrialid) {
        this.adTrialId = adtrialid;
    },

    reset: function(resp) {
        $(".rejecterror-box").addClass("nodisplay");
        $("#txtReasonDescription").attr('value', 'Your reason for rejection will be visible to future writers so please provide detailed feedback');
        this.rejectResponse = resp;
        this.adChallengeId = 0;
        this.adChallengeIds = '';
        tb_remove();
        ProcessOverlay.hide('dvRejectAdd');
    },

    ValidateReason: function(field) {
        //var RegexReason = '^[ ]|[ ]$';
        //var fieldvalue = field.toString();
        var isValidReason = true;

        //if (fieldvalue.search(RegexReason) != -1)
        //    isValidReason = false;
        return isValidReason;
    },

    rejectAd: function() {
        if (this.adChallengeIds.length == 0 && this.adChallengeId <= 0) {
            alert('No ad selected to reject');
            tb_remove();
            return false;
        }

        if ($("input[name=reason]:checked").val() == undefined) {
            $("#rejecterr-box").removeClass("nodisplay");
            $("#rejecterr-box").text("Please choose a reason.");
        }
        else if ($("input[name=reason]:checked").val() != undefined && !$("input[name=reason]:checked").val()) {
            $("#rejecterr-box").removeClass("nodisplay");
            $("#rejecterr-box").text("Please choose a reason.");
        }
        else if ($("#txtReasonDescription").val() == "Your reason for rejection will be visible to future writers so please provide detailed feedback"
             || $("#txtReasonDescription").val() == "") {
            $("#rejecterr-box").removeClass("nodisplay");
            $("#rejecterr-box").text("Please provide a valid reason.");
        }
        else if (!(this.ValidateReason($("#txtReasonDescription").val()))) {
            $("#rejecterr-box").removeClass("nodisplay");
            $("#rejecterr-box").text("Invalid reason.");
        }
        else if ($("#txtReasonDescription").val().length < 5 || $("#txtReasonDescription").val() == "") {
            $("#rejecterr-box").removeClass("nodisplay");
            $("#rejecterr-box").text("Reason is too short!");
        }
        else {
            ProcessOverlay.show('dvRejectAdd');

            $("#txtReasonDescription").val($("#txtReasonDescription").val());

            if ($('input[name=reason]:checked').val() == "TooSimilar" && $("#RejectAdAlertsInfo").length > 0)
                BoostModalBox.showPopupModal('RejectAdAlertsInfo', 160, 250);

            try {
                if (this.adChallengeIds != "") {
                    this.rejectedTerms = $("#txtRejectedTerms").val();
                    $.post("/Advertiser/RejectMulipleAds",
                    {
                        AdChallengeIdList: this.adChallengeIds,
                        Reason: $('input[name=reason]:checked').val(),
                        ReasonDescription: $("#txtReasonDescription").val(),
                        RejectedTerms: $("#txtRejectedTerms").val()
                    },
                    function(data) {
                        if (data == null) {
                            TopMessageAlert.showAlert("No response return from server.");
                        }
                        RejectAdBoxControl.rejectMultiAd_callback(data);
                    }, "json");
                } else {
                    this.rejectedTerms = $("#txtRejectedTerms").val();
                    $.post("/Advertiser/RejectAd",
                    {
                        AdTrialId: this.adTrialId,
                        AdChallengeId: this.adChallengeId,
                        Reason: $('input[name=reason]:checked').val(),
                        ReasonDescription: $("#txtReasonDescription").val(),
                        RejectedTerms: $("#txtRejectedTerms").val()
                    },
                    function(data) {
                        if (data == null) {
                            TopMessageAlert.showAlert("No response return from server.");
                        }
                        RejectAdBoxControl.rejectAd_callback(data);
                    }, "json");
                }
            } catch (e) {
                TopMessageAlert.showAlert("Error: " + e);
            }
        }
    },

    rejectAd_callback: function(resp) {
        this.reset(resp);
    },

    rejectMultiAd_callback: function(resp) {
        this.reset(resp);
    },

    addWriterToBlockList: function() {
        ProcessOverlay.show('dvRejectAdd');
        var content = '';
        content += '<div id="BlockWriterReason" class="boostmodalboxcontent round" style="border:solid 2px #d9d9d9; padding:10px; font-size:14px;" align=center>';
        content += '<div class="in-modal" align=center><p class="title" style="text-align:left;">Block Author</p>';
        content += '<hr/><br />';
        content += '<div align=left style="padding-left:10px;"><b>Please let us know why you want to block this writer?</b></div><br />';
        content += '<textarea cols=30 rows=4 id="txtAuthorBlockReason"></textarea><br /><br /><br />';
        content += '<a href="javascript:" class="mOrange-btn" style="display:inline; padding:4px 10px 4px 10px;" onclick="RejectAdBoxControl.submitWriterToBlockList();"> Block </a>';
        content += '<a href="javascript:" class="mOrange-btn" style="display:inline; padding:4px 10px 4px 10px;" id="lnkClose" onclick="BoostModalBox.remove(\'BlockWriterReason\'); ProcessOverlay.hide(\'dvRejectAdd\');"> Cancel </a></div>';
        content += '</div>';
        $("body").append(content);
        BoostModalBox.showPopupModal('BlockWriterReason', 220, 300);
    },

    submitWriterToBlockList: function() {
        var blockReason = $("#txtAuthorBlockReason").val();
        BoostModalBox.remove('BlockWriterReason');
        $.post("/Advertiser/BlockAdChallengeWriter",
                { AdChallengeId: this.adChallengeId,
                    AuthorBlockReason: blockReason
                },
                function(data) { RejectAdBoxControl.addWriterToBlockList_callback(data); }, "json");
    },

    addWriterToBlockList_callback: function(resp) {
        if (resp != null) {
            if (resp == "Success") {
                alert("Writer is blocked successfully.");
                $("#AddBlockListWriter").addClass("nodisplay");
            }
            else
                alert(resp);
        }
        ProcessOverlay.hide('dvRejectAdd');
    },

    showPastRejection: function() {
        if ($("#linkShowPastReason").attr("class") == "plussign") {
            ProcessOverlay.show('divOverlay');
            $.post("/Advertiser/GetPastRejectReasons",
                    { AdChallengeId: this.adChallengeId, AdGroupId: this.adGroupId },
                    function(data) { RejectAdBoxControl.showPastRejection_callback(data); }, "json");
        } else {
            $("#linkShowPastReason").removeClass("minussign").addClass("plussign");
            $("#PastRejection").addClass("nodisplay");
        }
    },

    showPastRejection_callback: function(resp) {
        if (resp != null) {
            $("#linkShowPastReason").removeClass("plussign").addClass("minussign");
            $("#PastRejection").removeClass("nodisplay");
            var sb = "";
            if (resp.length > 0) {
                for (var i = 0; i < resp.length; i++) {
                    var reason = resp[i].RejectionReasonText;
                    try {
                        reason = reason.substring(reason.indexOf("<br/>") + 5, reason.length);
                    } catch (e) { }
                    sb += "<div style='border:solid 1px #CCC; margin:1px; cursor:pointer;' onclick='RejectAdBoxControl.selectReason(\"" + resp[i].RejectionReason.Code + "\",\"" + reason.split("'").join("`").split("\"").join("`").split("\n").join(" ").split("\r").join(" ") + "\"); RejectAdBoxControl.showPastRejection();'>" + resp[i].RejectionReasonText + "</div>";
                }
            } else {
                sb += "<div style='border:solid 1px #CCC; margin:1px; cursor:pointer; padding:5px;'><b>No data found</b></div>";
            }
            $("#PastRejection").html(sb);
        }
        ProcessOverlay.hide('divOverlay');
    },

    selectReason: function(RejectionReasonCode, RejectionText) {
        $("#txtReasonDescription").val(RejectionText);
        var found = false;
        var j = 1;
        while ($("input[id=rdReason" + j + "]").length > 0 && found == false) {
            if ($.trim(RejectionReasonCode.toLowerCase()) == $.trim($("#rdReason" + j).val().toLowerCase())) {
                $("input[id=rdReason" + j + "]").removeAttr("checked");
                $("input[id=rdReason" + j + "]").attr("checked", "checked");
                found = true;
                break;
            }
            j++;
        }

        if (found == false) {
            for (var j = 1; j <= 5; j++) {
                $("input[id=rdReason" + j + "]").removeAttr("checked");
            }
        }
    }

    //    onclickReasonDescription: function() {
    //        if ($("#txtReasonDescription").attr('value') == "Your reason for rejection will be visible to future writers so please provide detailed feedback")
    //            $("#txtReasonDescription").attr('value', "");

    //        if ($("#txtRejectedTerms").attr('value') == "Please provide words here which should auto reject. For more than two words give comma separate format Like \"Word1,Word2\"")
    //            $("#txtRejectedTerms").attr('value', "");            
    //    },

    //    resetReason: function() {
    //        if ($("#txtReasonDescription").attr('value') == "")
    //            $("#txtReasonDescription").attr('value', "Your reason for rejection will be visible to future writers so please provide detailed feedback");

    //        if ($("#txtRejectedTerms").attr('value') == "")
    //            $("#txtRejectedTerms").attr('value', "Please provide words here which should auto reject. For more than two words give comma separate format Like \"Word1,Word2\"");
    //    }
}

var AddToQueueBoxControl = {
    init: function() { },
    adChallengeIds: '',
    addToQueueResponse: null,

    setCurrentChallenge: function(adchallengeid) {
        this.adChallengeIds = adchallengeid;
    },

    addChallenge: function(adchallengeid) {
        if (this.adChallengeIds.search(adchallengeid) == -1) {
            this.adChallengeIds += adchallengeid + ",";
        }
    },

    removeChallenge: function(adchallengeid) {
        if (this.adChallengeIds.search(adchallengeid) == -1) { return; } //doesn't exist return
        if (this.adChallengeIds.search(adchallengeid + ",") == -1) {
            this.adChallengeIds = this.adChallengeIds.replace(adchallengeid, "");
        }
        else {
            this.adChallengeIds = this.adChallengeIds.replace(adchallengeid + ",", "");
        }
    },

    reset: function(resp) {
        this.addToQueueResponse = resp;
        this.adChallengeIds = '';
        tb_remove();
        ProcessOverlay.hide('dvAddToQueue');
    },

    addToQueue: function() {
        if (this.adChallengeIds == '') {
            alert('No items selected.');
            return;
        }
        ProcessOverlay.show('TB_ajaxContent');
        try {
            $.post("/Advertiser/AddToQueue",
                    {
                        AdChallengeIdList: this.adChallengeIds
                    },
                    function(data) {
                        if (data == null) {
                            TopMessageAlert.showAlert("No response return from server.");
                        }
                        AddToQueueBoxControl.addToQueue_callback(data);
                    }, "json");
        } catch (e) {
            TopMessageAlert.showAlert("Error: " + e);
        }
    },

    addToQueue_callback: function(resp) {
        this.reset(resp);
        ProcessOverlay.hide('TB_ajaxContent');
    }
}

var ActivateContestBoxControl = {
    init: function() { },
    adGroupIds: '',
    groupResponse: null,

    setCurrentContest: function(adgroupid) {
        this.adGroupIds = adgroupid;
    },

    addContest: function(adgroupid) {
        if (this.adGroupIds.search(adgroupid) == -1) {
            this.adGroupIds += adgroupid + ",";
        }
    },

    removeContest: function(adgroupid) {
        if (this.adGroupIds.search(adgroupid) == -1) { return; } //doesn't exist return
        if (this.adGroupIds.search(adgroupid + ",") == -1) {
            this.adGroupIds = this.adGroupIds.replace(adgroupid, "");
        }
        else {
            this.adGroupIds = this.adGroupIds.replace(adgroupid + ",", "");
        }
    },

    reset: function(resp) {
        this.groupResponse = resp;
        this.adGroupIds = '';
        tb_remove();
        ProcessOverlay.hide('dvActivate');
    },

    activate: function() {
        if (this.adGroupIds == '') {
            alert('No items selected.');
            return;
        }
        ProcessOverlay.show('dvActivate');
        try {
            $.post("/Advertiser/ActivateContest",
                {
                    AdGroupIdList: this.adGroupIds
                },
                function(data) {
                    if (data == null) {
                        TopMessageAlert.showAlert("No response return from server.");
                    }
                    ActivateContestBoxControl.activate_callback(data);
                }, "json");
        } catch (e) {
            TopMessageAlert.showAlert("Error: " + e);
        }
    },

    activate_callback: function(resp) {
        this.reset(resp);
    }
}

var RemoveAdBoxControl = {
    init: function() { },
    adTrialId: 0,
    trialResponse: null,

    setCurrentTrial: function(adtrialid) {
        this.adTrialId = adtrialid;
    },

    reset: function(resp) {
        this.trialResponse = resp;
        this.adTrialId = 0;
        tb_remove();
        ProcessOverlay.hide('dvRemoveAdd');
        $('.ajaxContainer').removeClass("ajaxContainer");
        $('.ajaxMainProcessing').addClass("nodisplay");
    },

    removeAd: function() {
        if (this.adTrialId == 0) {
            alert('No item selected.');
            return;
        }
        ProcessOverlay.show('dvRemoveAdd');
        try {
            $.post("/Advertiser/RemoveAd",
                {
                    AdTrialId: this.adTrialId
                },
                function(data) {
                    if (data == null) {
                        TopMessageAlert.showAlert("No response return from server.");
                    }
                    RemoveAdBoxControl.removeAd_callback(data);
                }, "json");
        } catch (e) {
            TopMessageAlert.showAlert("Error: " + e);
        }
    },

    removeAd_callback: function(resp) {
        this.reset(resp);
    }
}

ApproveAdBoxControl = {
    init: function() { },
    adChallengeId: 0,
    challengeResponse: null,

    setCurrentChallenge: function(adchallengeid) {
        this.adChallengeId = adchallengeid;
    },

    reset: function(resp) {
        this.challengeResponse = resp;
        this.adChallengeId = 0;
        tb_remove();
        ProcessOverlay.hide('dvApproveAdd');
        $('.ajaxContainer').removeClass("ajaxContainer");
        $('.ajaxMainProcessing').addClass("nodisplay");
    },

    approveAd: function() {
        if (this.adChallengeId == 0) {
            alert('No item selected.');
            return;
        }
        ProcessOverlay.show('dvApproveAdd');
        try {
            $.post("/Advertiser/ApproveChallenger",
               {
                   AdChallengeId: this.adChallengeId
               },
               function(data) {
                   if (data == null) {
                       TopMessageAlert.showAlert("No response return from server.");
                   }
                   ApproveAdBoxControl.approveAd_callback(data);
               }, "json");
        } catch (e) {
            TopMessageAlert.showAlert("Error: " + e);
        }
    },

    approveAd_callback: function(resp) {
        this.reset(resp);
    }
}

ResubmitAdBoxControl = {
    init: function() { },
    adTrialId: 0,
    adChallengeId: 0,
    challengeResponse: null,

    setCurrentChallenge: function(adtrialid, adchallengeid) {
        this.adTrialId = adtrialid;
        this.adChallengeId = adchallengeid;
    },

    reset: function(resp) {
        this.challengeResponse = resp;
        this.adTrialId = 0;
        this.adChallengeId = 0;
        tb_remove();
        ProcessOverlay.hide('dvReSubmitAdd');
        $('.ajaxContainer').removeClass("ajaxContainer");
        $('.ajaxMainProcessing').addClass("nodisplay");
    },

    resubmitAd: function() {
        if (this.adChallengeId == 0) {
            alert('No item selected.');
            return;
        }
        ProcessOverlay.show('dvReSubmitAdd');
        $.post("/Advertiser/ResubmitChallenge",
               {
                   AdChallengeId: this.adChallengeId
               },
               function(data) { ResubmitAdBoxControl.resubmitAd_callback(data); }, "json");
    },

    resubmitAd_callback: function(resp) {
        this.reset(resp);
    }
}

var DeleteAdBoxControl = {
    init: function() { },
    adChallengeId: 0,
    adTrialId: 0,
    adId: 0,
    deletetype: '',
    rejectResponse: null,

    setCurrentChallenge: function(adtrialid, adchallengeid, adid, deltype) {
        $("#txtDeleteReason").attr('value', 'Please enter additional details. These will be viewable by future writers.');
        this.adChallengeId = 0;
        this.adTrialId = 0;
        this.adId = 0;
        this.deletetype = '';

        this.adChallengeId = adchallengeid;
        this.adTrialId = adtrialid;
        this.adId = adid;
        this.deletetype = deltype;

        $("#titleDeleteType").text(deltype);
        if (deltype == "Champion") {
            $("#titleMessage").text("Deleting the Champion ad will result in the Challenger ad winning this challenge. You will have to pay the prize associated with this Challenge.");
            $("#alertnote").removeClass("nodisplay");
        }
        else if (deltype == "Challenger") {
            $("#titleMessage").text("Deleting the Challenger ad will result in the Champion ad winning this challenge.");
            $("#alertnote").addClass("nodisplay");
        }
    },

    setCurrentTrial: function(adtrialid) {
        this.adTrialId = adtrialid;
    },

    reset: function(resp) {
        if (resp == "Successfull") {
            $("#txtDeleteReason").attr('value', 'Please enter additional details. These will be viewable by future writers.');
            this.rejectResponse = resp;
            this.adChallengeId = 0;
            this.adTrialId = 0;
            this.adId = 0;
            this.deletetype = '';
            tb_remove();
            window.location.reload();
        }
        else {
            $("#errMessage").attr("innerHTML", "Error: " + resp + "<br/>");
            $("#errMessage").removeClass("nodisplay");
            setTimeout("$('#errMessage').addClass('nodisplay');", 7000);
        }
        ProcessOverlay.hide('dvDeleteAd');
    },

    deleteAd: function() {
        ProcessOverlay.show('dvDeleteAd');

        if ($("#txtDeleteReason").val() == "Please enter additional details. These will be viewable by future writers.")
            $("#txtDeleteReason").val("");
        else
            $("#txtDeleteReason").val(", " + $("#txtDeleteReason").val());

        $.post("/Advertiser/DeleteAd",
                {
                    AdTrialId: this.adTrialId,
                    AdChallengeId: this.adChallengeId,
                    AdId: this.adId,
                    DeleteType: this.deletetype,
                    Reason: $('input[name=reason]:checked').val(),
                    ReasonDescription: $("#txtDeleteReason").val()
                },
                function(data) { DeleteAdBoxControl.deleteAd_callback(data); }, "json");
    },

    deleteAd_callback: function(resp) {
        this.reset(resp);
    },

    onclickReasonDescription: function() {
        if ($("#txtDeleteReason").attr('value') == "Please enter additional details. These will be viewable by future writers.")
            $("#txtDeleteReason").attr('value', "");
    },

    resetReason: function() {
        if ($("#txtDeleteReason").attr('value') == "")
            $("#txtDeleteReason").attr('value', "Please enter additional details. These will be viewable by future writers.");
    }
}

WriterResubmitAd = {
    adTrialId: 0,
    adChallengeId: 0,
    DestinationUrl: '',
    Headline: '',
    Line1: '',
    Line2: '',
    DisplayUrl: '',
    challengeResponse: null,

    init: function() {
        $("#txtheadline").bind("keyup", function() { var strVal = $("#txtheadline").val(); $("#lblheadline").text(25 - parseInt(strVal.length)); WriterResubmitAd.getAddBlock(); });
        $("#txtline1").bind("keyup", function() { var strVal = $("#txtline1").val(); $("#lblline1").text(35 - parseInt(strVal.length)); WriterResubmitAd.getAddBlock(); });
        $("#txtline2").bind("keyup", function() { var strVal = $("#txtline2").val(); $("#lblline2").text(35 - parseInt(strVal.length)); WriterResubmitAd.getAddBlock(); });
        $("#txturldisplay").bind("keyup", function() { var strVal = $("#txturldisplay").val().toLowerCase().replace(".com.au", ".com"); $("#lblurldisplay").text(35 - parseInt(strVal.length)); WriterResubmitAd.getAddBlock(); });
        $("#txtheadline").attr("maxlength", 25);
        $("#txtline1").attr("maxlength", 35);
        $("#txtline2").attr("maxlength", 35);
        $("#txturldisplay").attr("maxlength", 40);
        return true;
    },

    setCurrentChallenge: function(adtrialid, adchallengeid, desturl, headline, line1, line2, dispurl) {
        this.adTrialId = adtrialid;
        this.adChallengeId = adchallengeid;
        this.DestinationUrl = desturl.split("`").join("'");
        this.Headline = headline.split("`").join("'");
        this.Line1 = line1.split("`").join("'");
        this.Line2 = line2.split("`").join("'");
        this.DisplayUrl = dispurl.split("`").join("'");
        $("#txtheadline").val(this.Headline);
        $("#txtline1").val(this.Line1);
        $("#txtline2").val(this.Line2);
        $("#txturldisplay").val(this.DisplayUrl);
        WriterResubmitAd.getAddBlock();
    },

    getAddBlock: function() {
        var sb = "";
        sb += "<div class='boostab leftalign'> ";
        sb += "<a class='main headline' href='";
        sb += $("#txturldisplay").val() + "'>";
        sb += $("#txtheadline").val() + "</a> ";
        sb += "<p>";
        sb += $("#txtline1").val() + "<br />" + $("#txtline2").val() + "</p> ";
        sb += "<a class='site' href='";
        sb += $("#txturldisplay").val() + "'>";
        sb += $("#txturldisplay").val() + "</a> ";
        sb += "</div>";
        $("#addBox").html(sb);
    },

    resubmitAd: function() {
        if (this.adChallengeId == 0) {
            alert('No item selected.');
            return;
        }
        if (this.Headline == $("#txtheadline").val() && this.Line1 == $("#txtline1").val() && this.Line2 == $("#txtline2").val() && this.DisplayUrl == $("#txturldisplay").val()) {
            $("#fstError").attr("innerHTML", "You must change at least one character to resubmit");
            $("#errorsummary").show(500);
            setTimeout("$('#errorsummary').hide(500)", 5000);
            return;
        }
        ProcessOverlay.show('dvReSubmitAdd');
        $.post("/Writer/ResubmitChallenge",
               {
                   AdChallengeId: this.adChallengeId, Headline: $("#txtheadline").val(), Line1: $("#txtline1").val(), Line2: $("#txtline2").val(), DisplayUrl: $("#txturldisplay").val()
               },
               function(data) { WriterResubmitAd.resubmitAd_callback(data); }, "json");
    },

    resubmitAd_callback: function(resp) {
        try {
            if (resp.ErrorList.length > 0) {
                $("#fstError").attr("innerHTML", resp.ErrorList[0].ErrorMessage);
                $("#errorsummary").show(500);
                setTimeout("$('#errorsummary').hide(500)", 5000);
                ProcessOverlay.hide('dvReSubmitAdd');
                $('.ajaxContainer').removeClass("ajaxContainer");
                $('.ajaxMainProcessing').addClass("nodisplay");
                return;
            }
            else {
                $("#tr" + this.adChallengeId).addClass("nodisplay");
            }
        } catch (e) { }

        var count = parseInt($("#lblReSubmitAds").text()); //set submission tab count
        $("#lblReSubmitAds").text(count - 1);
        this.challengeResponse = resp;
        this.adTrialId = 0;
        this.adChallengeId = 0;
        tb_remove();
        ProcessOverlay.hide('dvReSubmitAdd');
        $('.ajaxContainer').removeClass("ajaxContainer");
        $('.ajaxMainProcessing').addClass("nodisplay");
    }
}

FBWriterEditAd = {
    adChallengeId: 0,
    Headline: '',
    Line1: '',
    DestinationURL: '',
    imageUrl: '',
    imageHeight: 0,
    imageWidth: 0,
    ChampionHeadline: '',
    ChampionLine1: '',
    challengeResponse: null,
    KeywordsExist: false,
    ChampionDifferencePercentage: '0',
    CapitalizationWhiteList: '',
    init: function() {
        $("#fbeditheadline").bind("keyup", function() {
            var strVal = $("#fbeditheadline").val();
            $("#lblfbeditheadline").text(25 - parseInt(strVal.length));
            FBWriterEditAd.getAddBlock();
        });
        $("#fbeditheadline").attr("maxlength", 25);
        $("#fbeditline1").bind("keyup", function() {
            var strVal = $("#fbeditline1").val();
            if (strVal.length > 135) {
                strVal = strVal.substring(0, 135);
                $("#fbeditline1").val(strVal);
            }
            $("#lblfbeditline1").text(135 - parseInt(strVal.length));
            FBWriterEditAd.getAddBlock();
        });
        $("#fbeditline1").attr("onkeypress", "return FBWriterEditAd.ImposeMaxLength(this, 134, event);");

        if ($("#fbdestinationurl").length != 0) {
            $("#fbdestinationurl").bind("keyup", function() {
                var strVal = $("#fbdestinationurl").val();
                $("#lblfbdestinationurl").text(1000 - parseInt(strVal.length));
                FBWriterEditAd.getAddBlock();
            });
        }
        return true;
    },

    setCurrentChallenge: function(adchallengeid) {
        FBWriterEditAd.adChallengeId = adchallengeid;

        ProcessOverlay.show('dvFBEditAdd');
        $.ajax({
            type: 'POST',
            url: "/Writer/GetFacebookAdChallenge",
            dataType: "json",
            async: false,
            data: { AdChallengeId: FBWriterEditAd.adChallengeId },
            success: function(result) {
                if (result != null) {
                    FBWriterEditAd.Headline = result.Headline.split("`").join("'");
                    FBWriterEditAd.Line1 = result.Line1.split("`").join("'");
                    FBWriterEditAd.DestinationURL = result.DestinationUrl;
                    FBWriterEditAd.imageUrl = result.ImageUrl;
                    FBWriterEditAd.imageHeight = result.Height;
                    FBWriterEditAd.imageWidth = result.Width;
                    FBWriterEditAd.ChampionHeadline = result.ChampionHeadline;
                    FBWriterEditAd.ChampionLine1 = result.ChampionLine1;
                    FBWriterEditAd.KeywordsExist = result.KeywordsExist;
                    FBWriterEditAd.ChampionDifferencePercentage = result.ChampionDifferencePercentage;
                    FBWriterEditAd.CapitalizationWhiteList = result.CapitalizationWhiteList.split(',').join(' ');
                    FBWriterEditAd.ShowChampDiff = result.ShowChampDiff;
                }
            },
            error: function(req, status, error) {
            }
        });

        ProcessOverlay.hide('dvFBEditAdd');
        $("#fbeditheadline").val(FBWriterEditAd.Headline);
        $("#lblfbeditheadline").text(25 - parseInt($("#fbeditheadline").val().length));
        $("#fbeditline1").val(FBWriterEditAd.Line1);
        $("#lblfbeditline1").text(135 - parseInt($("#fbeditline1").val().length));
        if ($("#fbdestinationurl").length != 0) {
            $("#fbdestinationurl").val(FBWriterEditAd.DestinationURL);
            $("#lblfbdestinationurl").text(1000 - parseInt($("#fbdestinationurl").val().length));
        }
        FBWriterEditAd.getAddBlock();
    },

    getAddBlock: function(showinfo) {
        var destinationurl = "#";
        if ($("#fbdestinationurl").length != 0) {
            destinationurl = $("#fbdestinationurl").val();
        }
        if (showinfo == undefined || showinfo == null)
            showinfo = false;

        var sb = "";
        if (showinfo)
            sb += '<a href="#" class="info tooltip" style="float:right;" title="<br/><b>Champion Character Difference:</b> ' + FBWriterEditAd.ChampionDifferencePercentage + '%<br/><br/>">info</a>';

        sb += "<div><a id='lnkHeadline_" + FBWriterEditAd.adChallengeId + "' class='fbheadline' style='text-decoration:none;' target='_blank' href='" + destinationurl + "'>" + $("#fbeditheadline").val() + "</a></div>";
        sb += "<div align='left' style='height:90px; width:120px; float:left; position:relative; padding-top:5px;' class='adimagethumb'>";
        if (FBWriterEditAd.imageUrl.length > 0) {
            sb += "<a href='javascript:' id='A4' style='display:inline;'>";
            sb += "<img src='" + FBWriterEditAd.imageUrl + "' alt=''  height='" + (FBWriterEditAd.imageHeight == undefined ? 80 : FBWriterEditAd.imageHeight) + "' width='" + (FBWriterEditAd.imageWidth == undefined ? 120 : FBWriterEditAd.imageWidth) + "' style='display:inline;' />";
            sb += "</a>";
        } else {
            sb += "<img src='/Content/images/not_available.gif' alt='' style='display:inline;' class='blackborder' height='80' width='120' />";
        }
        sb += "</div>";
        sb += "<div align='left' style='height:90px; width:135px; padding:5px; float:right; position:relative; overflow:hidden;'>";
        sb += "<div id='lblLine1_" + FBWriterEditAd.adChallengeId + "' class='adline1' style='font-size:8pt;'>" + $("#fbeditline1").val() + "</div>";
        sb += "</div>";
        $("#fbAddBox").html(sb);
    },

    ImposeMaxLength: function(object, maxlen, event) {
        if (event.keyCode == 8 || event.keyCode == 46)
            return true;
        else
            return (object.value.length <= maxlen);
    },

    adValidation: function() {
        try {
            var IsAdv = (IsAdvertiser != undefined && IsAdvertiser == "True" ? true : false);
            var IgnoreWords = FBWriterEditAd.ChampionHeadline + ' ' + FBWriterEditAd.ChampionLine1 + ' ' + FBWriterEditAd.CapitalizationWhiteList;
            if (this.adChallengeId == 0) {
                alert('No item selected.');
                return false;
            }

            if (FBWriterEditAd.Headline == $("#fbeditheadline").val() && FBWriterEditAd.Line1 == $("#fbeditline1").val() && (FBWriterEditAd.DestinationURL == ($("#fbdestinationurl").length != 0 ? $("#fbdestinationurl").val() : FBWriterEditAd.DestinationURL))) {
                $("#fbeditfstError").html("You must change at least one character before submit");
                $("#fbediterrorsummary").show(500);
                setTimeout("$('#fbediterrorsummary').hide(500)", 5000);
                return false;
            }

            var headln = $.trim($("#fbeditheadline").val());
            var showErr = false;
            if (headln.length > 25)
                showErr = true;
            if (showErr) {
                $("#fbeditfstError").html("Maximum 25 char allowed in Headline.");
                $("#fbediterrorsummary").show(500);
                setTimeout("$('#fbediterrorsummary').hide(500)", 5000);
                return false;
            }

            if ((!IsAdv) && FiledValidation.GetUpperWordCount(headln, 4, IgnoreWords) > 0) {
                $("#fbeditfstError").html("Excessive capitalization in headline.");
                $("#fbediterrorsummary").show(500);
                setTimeout("$('#fbediterrorsummary').hide(500)", 5000);
                return false;
            }

            if (headln.toLowerCase().indexOf("{keyword:") >= 0 && headln.toLowerCase().indexOf("}") > headln.toLowerCase().indexOf("{keyword:")) {
                $("#fbeditfstError").html("{Keyword:} is not allowed for facebook ad.");
                $("#fbediterrorsummary").show(500);
                setTimeout("$('#fbediterrorsummary').hide(500)", 5000);
                return false;
            }

            var line1 = $.trim($("#fbeditline1").val());
            if (line1.length > 135) {
                $("#fbeditfstError").html("Maximum 135 char allowed in body.");
                $("#fbediterrorsummary").show(500);
                setTimeout("$('#fbediterrorsummary').hide(500)", 5000);
                return false;
            }

            if ((!IsAdv) && FiledValidation.GetUpperWordCount(line1, 4, IgnoreWords) > 0) {
                $("#fbeditfstError").html("Excessive capitalization in body.");
                $("#fbediterrorsummary").show(500);
                setTimeout("$('#fbediterrorsummary').hide(500)", 5000);
                return false;
            }

            if (headln.length == 0) {
                $("#fbeditfstError").html("Headline is required to submit the ad.");
                $("#fbediterrorsummary").show(500);
                setTimeout("$('#fbediterrorsummary').hide(500)", 5000);
                return false;
            }

            if (headln.toLowerCase().indexOf("...") != -1 || line1.toLowerCase().indexOf("...") != -1) {
                $("#fbeditfstError").html("You are using invalid punctuation [...].");
                $("#fbediterrorsummary").show(500);
                setTimeout("$('#fbediterrorsummary').hide(500)", 5000);
                return false;
            }
        } catch (e) { return false; }
        return true;
    },

    editAd: function() {
        if (!FBWriterEditAd.adValidation())
            return false;

        var desturl = "";
        if ($("#fbdestinationurl").length != 0) {
            desturl = $("#fbdestinationurl").val();
        }
        this.DestinationURL = desturl;
        if ($("#blankFBEditOpen").length == 0) {
            $('body').append("<a id='blanckFBEditOpen' href='#TB_inline?500&width=700&inlineId=fbeditad-modal&modal=true' class='thickbox' style='display:none;'>&nbsp;</a>");
            tb_init('a.thickbox');
        }

        try {
            myChecker = new SpellChecker();
            //tb_remove();
            myChecker.checkSpelling($('#fbeditheadline'), function(status) {
                if (status)
                    myChecker.checkSpelling($('#fbeditline1'), function(status) {
                        if (status) {
                            if (FBWriterEditAd.adValidation()) {
                                this.Headline = $.trim($("#fbeditheadline").val());
                                this.Line1 = $.trim($("#fbeditline1").val());

                                $('input.button-submit').fadeTo('fast', 0.33).attr('disabled', 'disabled').css('cursor', 'default');
                                $('input.button-cancel').fadeTo('fast', 0.33).attr('disabled', 'disabled').css('cursor', 'default');
                                ProcessOverlay.show('dvFBEditAdd');
                                try {
                                    $.post("/Writer/EditFacebookAdChallenge",
                                   {
                                       AdChallengeId: FBWriterEditAd.adChallengeId,
                                       Headline: $.trim(this.Headline),
                                       Line1: $.trim(this.Line1),
                                       DestinationUrl: desturl
                                   },
                                   function(data) {
                                       if (data == null) {
                                           TopMessageAlert.showAlert("No response return from server.");
                                       }
                                       FBWriterEditAd.editAd_callback(data);
                                   }, "json");
                                } catch (e) {
                                    TopMessageAlert.showAlert("Error: " + e);
                                }
                            } else {
                                //$("#blankFBEditOpen").click();
                                return false;
                            }
                        }
                    })
            })
        } catch (e) {
            TopMessageAlert.showAlert("Error: " + e);
        }
    },

    editAd_callback: function(resp) {
        $("#fbediterrorsummary").hide();
        this.reset(resp);
    },

    reset: function(resp) {
        try {
            if (resp != null && resp.ErrorList != null) {
                if (resp.ErrorList.length > 0) {
                    try {
                        $("#fbeditfstError").html(resp.ErrorList[0].ErrorMessage);
                        tb_show("Using Rejected Terms", "#TB_inline?height=500&width=700&inlineId=fbeditad-modal&modal=true");
                        $("#fbediterrorsummary").show(500);
                        setTimeout("$('#fbediterrorsummary').hide(500)", 5000);
                        ProcessOverlay.hide('dvFBEditAdd');
                        $('.ajaxContainer').removeClass("ajaxContainer");
                        $('.ajaxMainProcessing').addClass("nodisplay");
                        $('input.button-submit')
                        .fadeTo('fast', 1.0)
                        .removeAttr('disabled')
                        .css('cursor', 'pointer');
                        $('input.button-cancel')
                        .fadeTo('fast', 1.0)
                        .removeAttr('disabled')
                        .css('cursor', 'pointer');
                        return false;
                    } catch (e) {
                        return false;
                    }
                }
                else {
                    alert("Changes have been successfully made");
                    tb_init('a.thickbox, area.thickbox, input.thickbox');

                    if (resp.adChallenge != null) {
                        FBWriterEditAd.KeywordsExist = resp.adChallenge.KeywordsExist;
                    } else {
                        $.ajax({
                            type: 'POST',
                            url: "/Writer/GetAdChallenge",
                            dataType: "json",
                            async: false,
                            data: { AdChallengeId: FBWriterEditAd.adChallengeId },
                            success: function(result) {
                                if (result != null) {
                                    FBWriterEditAd.KeywordsExist = result.KeywordsExist;
                                }
                            },
                            error: function(req, status, error) {
                            }
                        });
                    }
                    if (FBWriterEditAd.KeywordsExist)
                        $("#keyword_" + this.adChallengeId).addClass("nodisplay");
                    else
                        $("#keyword_" + this.adChallengeId).removeClass("nodisplay");
                }
            }
        } catch (e) { }
        $("#lnkHeadline_" + this.adChallengeId).html($("#fbeditheadline").val());
        try {
            $("#lblLine1_" + this.adChallengeId).text($("#fbeditline1").val());
            if ($("#lblLine1_" + this.adChallengeId).text() != $("#fbeditline1").val())
                $("#lblLine1_" + this.adChallengeId).html($("#fbeditline1").val());
        } catch (e) {
            $("#lblLine1_" + this.adChallengeId).html($("#fbeditline1").val());
        }

        if ($("#fbdestinationurl").length != 0)
            $("#destURL_" + this.adChallengeId).val($("#fbdestinationurl").val());

        $('input.button-submit').fadeTo('fast', 1.0).removeAttr('disabled').css('cursor', 'pointer');
        $('input.button-cancel').fadeTo('fast', 1.0).removeAttr('disabled').css('cursor', 'pointer');

        this.challengeResponse = resp;
        this.adChallengeId = 0;
        this.Headline = '';
        this.Line1 = '';
        this.DestinationURL = '';
        $("#fbeditheadline").val('');
        $("#fbeditline1").val('');
        ProcessOverlay.hide('dvFBEditAdd');
        $('.ajaxContainer').removeClass("ajaxContainer");
        $('.ajaxMainProcessing').addClass("nodisplay");
        $("#fbediterrorsummary").hide();
        tb_remove();
        tooltip();
    }
}


CustomAdWriterEditAd = {
    adChallengeId: 0,
    Headline: '',
    Line1: '',
    Line2: '',
    DisplayURL: '',
    DestinationURL: '',
    imageUrl: '',
    imageHeight: 0,
    imageWidth: 0,
    ChampionHeadline: '',
    ChampionLine1: '',
    ChampionLine2: '',
    CapitalizationWhiteList: '',
    challengeResponse: null,
    KeywordsExist: false,
    ChampionDifferencePercentage: '0',
    DisplayUrlDirectoryChangeAllowed: false,
    DisplayUrlIsUsedInAd: false,
    DisplayUrlMaxLength: 0,
    DisplayUrlSubDomainChangeAllowed: false,
    ImageIsUsedInAd: false,
    ImageSampleUrl: '',
    Line1ChangeAllowed: false,
    Line1IsUsedInAd: false,
    Line1MaxLength: 0,
    Line2ChangeAllowed: false,
    Line2IsUsedInAd: false,
    Line2MaxLength: 0,
    NewAdSubmissionAlertPostUrl: '',
    TitleChangeAllowed: false,
    TitleIsUsedInAd: false,
    TitleMaxLength: 0,
    ShowChampDiff: false,

    init: function(adchallengeid, adgroupid) {
        this.setCurrentData(adgroupid);
        this.setCurrentChallenge(adchallengeid);
        return true;
    },
    setCurrentData: function(adgroupid) {
        $.ajax({
            type: 'POST',
            url: "/Writer/GetCustomAdData",
            dataType: "json",
            async: false,
            data: { AdGroupId: adgroupid },
            success: function(result) {
                if (result != null) {
                    CustomAdWriterEditAd.DisplayUrlDirectoryChangeAllowed = result.DisplayUrlDirectoryChangeAllowed;
                    CustomAdWriterEditAd.DisplayUrlIsUsedInAd = result.DisplayUrlIsUsedInAd;
                    CustomAdWriterEditAd.DisplayUrlMaxLength = result.DisplayUrlMaxLength;
                    CustomAdWriterEditAd.DisplayUrlSubDomainChangeAllowed = result.DisplayUrlSubDomainChangeAllowed;
                    CustomAdWriterEditAd.ImageIsUsedInAd = result.ImageIsUsedInAd;
                    CustomAdWriterEditAd.ImageSampleUrl = result.ImageSampleUrl;
                    CustomAdWriterEditAd.Line1ChangeAllowed = result.Line1ChangeAllowed;
                    CustomAdWriterEditAd.Line1IsUsedInAd = result.Line1IsUsedInAd;
                    CustomAdWriterEditAd.Line1MaxLength = result.Line1MaxLength;
                    CustomAdWriterEditAd.Line2ChangeAllowed = result.Line2ChangeAllowed;
                    CustomAdWriterEditAd.Line2IsUsedInAd = result.Line2IsUsedInAd;
                    CustomAdWriterEditAd.Line2MaxLength = result.Line2MaxLength;
                    CustomAdWriterEditAd.TitleChangeAllowed = result.TitleChangeAllowed;
                    CustomAdWriterEditAd.TitleIsUsedInAd = result.TitleIsUsedInAd;
                    CustomAdWriterEditAd.TitleMaxLength = result.TitleMaxLength;
                }
            },
            error: function(req, status, error) {
            }
        });
        if (!CustomAdWriterEditAd.TitleIsUsedInAd) {
            var row = document.getElementById("customadeditheadlinerow");
            row.style.display = 'none';
        }
        else if (!CustomAdWriterEditAd.TitleChangeAllowed) {
            var textBox = document.getElementById("customadeditheadline");
            textBox.readOnly = true;
            textBox.style.color = "gray";
            var lengthTracker = document.getElementById('customadeditheadlinelengthtracker');
            lengthTracker.style.display = 'none';
        }
        else {
            $("#lblcustomadeditheadlinemax").text(CustomAdWriterEditAd.TitleMaxLength);
            var row = document.getElementById("customadeditheadlinerow");
            row.style.display = '';
            var textBox = document.getElementById("customadeditheadline");
            textBox.readOnly = false;
            textBox.style.color = "black";
            var lengthTracker = document.getElementById('customadeditheadlinelengthtracker');
            lengthTracker.style.display = '';
        }
        if (!CustomAdWriterEditAd.Line1IsUsedInAd) {
            var row = document.getElementById("customadeditline1row");
            row.style.display = 'none';
        }
        else if (!CustomAdWriterEditAd.Line1ChangeAllowed) {
            var textBox = document.getElementById("customadeditline1");
            textBox.readOnly = true;
            textBox.style.color = "gray";
            var lengthTracker = document.getElementById('customadeditline1lengthtracker');
            lengthTracker.style.display = 'none';
        }
        else {
            $("#lblcustomadeditline1max").text(CustomAdWriterEditAd.Line1MaxLength);
            var row = document.getElementById("customadeditline1row");
            row.style.display = '';
            var textBox = document.getElementById("customadeditline1");
            textBox.readOnly = false;
            textBox.style.color = "black";
            var lengthTracker = document.getElementById('customadeditline1lengthtracker');
            lengthTracker.style.display = '';
        }
        if (!CustomAdWriterEditAd.Line2IsUsedInAd) {
            var row = document.getElementById("customadeditline2row");
            row.style.display = 'none';
        }
        else if (!CustomAdWriterEditAd.Line2ChangeAllowed) {
            var textBox = document.getElementById("customadeditline2");
            textBox.readOnly = true;
            textBox.style.color = "gray";
            var lengthTracker = document.getElementById('customadeditline2lengthtracker');
            lengthTracker.style.display = 'none';
        }
        else {
            $("#lblcustomadeditline2max").text(CustomAdWriterEditAd.Line2MaxLength);
            var row = document.getElementById("customadeditline2row");
            row.style.display = '';
            var textBox = document.getElementById("customadeditline2");
            textBox.readOnly = false;
            textBox.style.color = "black";
            var lengthTracker = document.getElementById('customadeditline2lengthtracker');
            lengthTracker.style.display = '';
        }
        if (!CustomAdWriterEditAd.DisplayUrlIsUsedInAd) {
            var row = document.getElementById("customadeditdisplayurlrow");
            row.style.display = 'none';
        }
        else if (!CustomAdWriterEditAd.Line2ChangeAllowed) {
            var textBox = document.getElementById("customadeditdisplayurl");
            textBox.readOnly = true;
            textBox.style.color = "gray";
            var lengthTracker = document.getElementById('customadeditdisplayurllengthtracker');
            lengthTracker.style.display = 'none';
        }
        else {
            $("#lblcustomadeditdisplayurlmax").text(CustomAdWriterEditAd.DisplayUrlMaxLength);
            var row = document.getElementById("customadeditdisplayurlrow");
            row.style.display = '';
            var textBox = document.getElementById("customadeditdisplayurl");
            textBox.readOnly = false;
            textBox.style.color = "black";
            var lengthTracker = document.getElementById('customadeditdisplayurllengthtracker');
            lengthTracker.style.display = '';
        }
        $("#dvCustomAdEditAdd #customadeditheadline").bind("keyup", function() {
            var strVal = $("#dvCustomAdEditAdd #customadeditheadline").val();
            $("#dvCustomAdEditAdd #lblcustomadeditheadline").text(CustomAdWriterEditAd.TitleMaxLength - parseInt(strVal.length));
            CustomAdWriterEditAd.getAddBlock();
        });
        $("#dvCustomAdEditAdd #customadeditheadline").attr("maxlength", CustomAdWriterEditAd.TitleMaxLength);
        $("#dvCustomAdEditAdd #customadeditline1").bind("keyup", function() {
            var strVal = $("#dvCustomAdEditAdd #customadeditline1").val();
            $("#dvCustomAdEditAdd #lblcustomadeditline1").text(CustomAdWriterEditAd.Line1MaxLength - parseInt(strVal.length));
            CustomAdWriterEditAd.getAddBlock();
        });
        $("#dvCustomAdEditAdd #customadeditline1").attr("maxlength", CustomAdWriterEditAd.Line1MaxLength);
        $("#dvCustomAdEditAdd #customadeditline2").bind("keyup", function() {
            var strVal = $("#dvCustomAdEditAdd #customadeditline2").val();
            $("#lblcustomadeditline2").text(CustomAdWriterEditAd.Line2MaxLength - parseInt(strVal.length));
            CustomAdWriterEditAd.getAddBlock();
        });
        $("#dvCustomAdEditAdd #customadeditline2").attr("maxlength", CustomAdWriterEditAd.Line2MaxLength);

        $("#dvCustomAdEditAdd #customadeditdisplayurl").bind("keyup", function() {
            var strVal = $("#dvCustomAdEditAdd #customadeditdisplayurl").val().toLowerCase().replace(".com.au", ".com");
            $("#dvCustomAdEditAdd #lblcustomadeditdisplayurl").text(CustomAdWriterEditAd.DisplayUrlMaxLength - parseInt(strVal.length));
            CustomAdWriterEditAd.getAddBlock();
        });
        $("#dvCustomAdEditAdd #customadeditdisplayurl").attr("maxlength", CustomAdWriterEditAd.DisplayUrlMaxLength);

        if ($("#dvCustomAdEditAdd #customaddestinationurl").length != 0) {
            $("#dvCustomAdEditAdd #customaddestinationurl").bind("keyup", function() {
                var strVal = $("#dvCustomAdEditAdd #customaddestinationurl").val();
                $("#dvCustomAdEditAdd #lblcustomaddestinationurl").text(1000 - parseInt(strVal.length));
                CustomAdWriterEditAd.getAddBlock();
            });
        }
    },
    setCurrentChallenge: function(adchallengeid) {
        try {
            CustomAdWriterEditAd.adChallengeId = adchallengeid;
            ProcessOverlay.show('dvCustomAdEditAdd');
            $.ajax({
                type: 'POST',
                url: "/Writer/GetCustomAdChallenge",
                dataType: "json",
                async: false,
                data: { AdChallengeId: CustomAdWriterEditAd.adChallengeId },
                success: function(result) {
                    if (result != null) {
                        CustomAdWriterEditAd.Headline = result.Headline.split("`").join("'");
                        CustomAdWriterEditAd.Line1 = result.Line1.split("`").join("'");
                        CustomAdWriterEditAd.Line2 = result.Line2.split("`").join("'");
                        CustomAdWriterEditAd.DisplayURL = result.DisplayURL;
                        CustomAdWriterEditAd.DestinationURL = result.DestinationURL;
                        CustomAdWriterEditAd.imageUrl = result.ImageURL;
                        CustomAdWriterEditAd.imageHeight = result.ImageHeight;
                        CustomAdWriterEditAd.imageWidth = result.ImageWidth;
                        CustomAdWriterEditAd.ChampionHeadline = result.ChampionHeadline;
                        CustomAdWriterEditAd.ChampionLine1 = result.ChampionLine1;
                        CustomAdWriterEditAd.ChampionLine2 = result.ChampionLine2;
                        CustomAdWriterEditAd.KeywordsExist = result.KeywordsExist;
                        CustomAdWriterEditAd.ChampionDifferencePercentage = result.ChampionDifferencePercentage;
                        CustomAdWriterEditAd.CapitalizationWhiteList = result.CapitalizationWhiteList.split(',').join(' ');
                        CustomAdWriterEditAd.ShowChampDiff = result.ShowChampDiff;
                    }
                },
                error: function(req, status, error) {
                }
            });
            ProcessOverlay.hide('dvCustomAdEditAdd');
            $("#customadeditheadline").val(CustomAdWriterEditAd.Headline);
            $("#lblcustomadeditheadline").text(CustomAdWriterEditAd.TitleMaxLength - parseInt($("#customadeditheadline").val().length));
            $("#customadeditline1").val(CustomAdWriterEditAd.Line1);
            $("#customadeditline2").val(CustomAdWriterEditAd.Line2);
            $("#customadeditdisplayurl").val(CustomAdWriterEditAd.DisplayURL);
            if (CustomAdWriterEditAd.Line1IsUsedInAd)
                $("#lblcustomadeditline1").text(CustomAdWriterEditAd.Line1MaxLength - parseInt($("#customadeditline1").val().length));
            if (CustomAdWriterEditAd.Line2IsUsedInAd)
                $("#lblcustomadeditline2").text(CustomAdWriterEditAd.Line2MaxLength - parseInt($("#customadeditline2").val().length));
            if (CustomAdWriterEditAd.DisplayUrlIsUsedInAd)
                $("#lblcustomadeditdisplayurl").text(CustomAdWriterEditAd.DisplayUrlMaxLength - parseInt($("#customadeditdisplayurl").val().length));

            if ($("#customaddestinationurl").length != 0) {
                $("#customaddestinationurl").val(CustomAdWriterEditAd.DestinationURL);
                $("#lblcustomaddestinationurl").text(1000 - parseInt($("#customaddestinationurl").val().length));
            }
            CustomAdWriterEditAd.getAddBlock();
        } catch (e) { alert(e); }
    },
    getAddBlock: function(showinfo) {
        var destinationurl = "#";
        if ($("#customaddestinationurl").length != 0) {
            destinationurl = $("#customaddestinationurl").val();
        }
        if (showinfo == undefined || showinfo == null)
            showinfo = false;

        var sb = "";
        if (showinfo)
            sb += '<a href="#" class="info tooltip" style="float:right;" title="<br/><b>Champion Character Difference:</b> ' + CustomAdWriterEditAd.ChampionDifferencePercentage + '%<br/><br/>">info</a>';

        if (CustomAdWriterEditAd.TitleIsUsedInAd)
            sb += "<div><a id='lnkHeadline_" + CustomAdWriterEditAd.adChallengeId + "' class='customadheadline' style='text-decoration:none;' target='_blank' href='" + destinationurl + "'>" + $("#customadeditheadline").val() + "</a></div>";
        if (CustomAdWriterEditAd.imageUrl != undefined && CustomAdWriterEditAd.ImageIsUsedInAd) {
            sb += "<div align='left' style='height:90px; width:120px; float:left; position:relative; padding-top:5px;' class='adimagethumb'>";
            if (CustomAdWriterEditAd.imageUrl.length > 0) {
                sb += "<a href='javascript:' id='A4' style='display:inline;'>";
                sb += "<img src='" + CustomAdWriterEditAd.imageUrl + "' alt=''  height='" + (CustomAdWriterEditAd.imageHeight == undefined ? 80 : CustomAdWriterEditAd.imageHeight) + "' width='" + (CustomAdWriterEditAd.imageWidth == undefined ? 120 : CustomAdWriterEditAd.imageWidth) + "' style='display:inline;' />";
                sb += "</a>";
            } else {
                sb += "<img src='/Content/images/not_available.gif' alt='' style='display:inline;' class='blackborder' height='80' width='120' />";
            }
            sb += "</div>";
        }
        sb += "<div align='left' style='height:90px; width:135px; padding:5px; float:left; position:relative; overflow:hidden;'>";
        if (CustomAdWriterEditAd.Line1IsUsedInAd)
            sb += "<div id='lblLine1_" + CustomAdWriterEditAd.adChallengeId + "' class='customadline1' style='font-size:8pt;'>" + $("#customadeditline1").val() + "</div>";
        if (CustomAdWriterEditAd.Line2IsUsedInAd)
            sb += "<div id='lblLine2_" + CustomAdWriterEditAd.adChallengeId + "' class='customadadline2' style='font-size:8pt;'>" + $("#customadeditline2").val() + "</div>";
        if (CustomAdWriterEditAd.DisplayUrlIsUsedInAd)
            sb += "<a class='site' href='" + destinationurl + "' style='font-size:8pt;'>" + $("#customadeditdisplayurl").val() + "</a>";
        sb += "</div>";
        $("#customadAddBox").html(sb);
    },

    ImposeMaxLength: function(object, maxlen, event) {
        if (event.keyCode == 8 || event.keyCode == 46)
            return true;
        else
            return (object.value.length <= maxlen);
    },

    adValidation: function() {
        try {
            var IsAdv = (IsAdvertiser != undefined && IsAdvertiser == "True" ? true : false);
            var IgnoreWords = CustomAdWriterEditAd.ChampionHeadline + ' ' + CustomAdWriterEditAd.ChampionLine1 + ' ' + CustomAdWriterEditAd.ChampionLine2;
            if (this.adChallengeId == 0) {
                alert('No item selected.');
                return false;
            }

            if (CustomAdWriterEditAd.Headline == $("#customadeditheadline").val() && CustomAdWriterEditAd.Line1 == $("#customadeditline1").val() && CustomAdWriterEditAd.Line2 == $("#customadeditline2").val() && CustomAdWriterEditAd.DisplayURL == $("#customadeditdisplayurl").val() && (CustomAdWriterEditAd.DestinationURL == ($("#customaddestinationurl").length != 0 ? $("#customaddestinationurl").val() : CustomAdWriterEditAd.DestinationURL))) {
                $("#customadeditfstError").html("You must change at least one character before submit");
                $("#customadediterrorsummary").show(500);
                setTimeout("$('#customadediterrorsummary').hide(500)", 5000);
                return false;
            }

            var headln = $.trim($("#customadeditheadline").val());
            var showErr = false;
            if (headln.length > CustomAdWriterEditAd.TitleMaxLength)
                showErr = true;
            if (showErr) {
                $("#customadeditfstError").html("Maximum " + CustomAdWriterEditAd.TitleMaxLength + " char allowed in Headline.");
                $("#customadediterrorsummary").show(500);
                setTimeout("$('#customadediterrorsummary').hide(500)", 5000);
                return false;
            }

            if ((!IsAdv) && FiledValidation.GetUpperWordCount(headln, 4, IgnoreWords) > 0) {
                $("#customadeditfstError").html("Excessive capitalization in headline.");
                $("#customadediterrorsummary").show(500);
                setTimeout("$('#customadediterrorsummary').hide(500)", 5000);
                return false;
            }

            if (headln.toLowerCase().indexOf("{keyword:") >= 0 && headln.toLowerCase().indexOf("}") > headln.toLowerCase().indexOf("{keyword:")) {
                $("#customadeditfstError").html("{Keyword:} is not allowed for the custom ad network.");
                $("#customadediterrorsummary").show(500);
                setTimeout("$('#customadediterrorsummary').hide(500)", 5000);
                return false;
            }

            var line1 = $.trim($("#customadeditline1").val());
            if (line1.length > CustomAdWriterEditAd.Line1MaxLength) {
                $("#customadeditfstError").html("Maximum  " + CustomAdWriterEditAd.Line1MaxLength + " char allowed in body.");
                $("#customadediterrorsummary").show(500);
                setTimeout("$('#customadediterrorsummary').hide(500)", 5000);
                return false;
            }

            var line2 = $.trim($("#customadeditline2").val());
            if (line2.length > CustomAdWriterEditAd.Line2MaxLength) {
                $("#customadeditfstError").html("Maximum  " + CustomAdWriterEditAd.Line2MaxLength + " char allowed in body.");
                $("#customadediterrorsummary").show(500);
                setTimeout("$('#customadediterrorsummary').hide(500)", 5000);
                return false;
            }

            if ((!IsAdv) && FiledValidation.GetUpperWordCount(line1, 4, IgnoreWords) > 0) {
                $("#customadeditfstError").html("Excessive capitalization in body.");
                $("#customadediterrorsummary").show(500);
                setTimeout("$('#customadediterrorsummary').hide(500)", 5000);
                return false;
            }

            if ((!IsAdv) && FiledValidation.GetUpperWordCount(line2, 4, IgnoreWords) > 0) {
                $("#customadeditfstError").html("Excessive capitalization in body.");
                $("#customadediterrorsummary").show(500);
                setTimeout("$('#customadediterrorsummary').hide(500)", 5000);
                return false;
            }

            if (headln.length == 0) {
                $("#customadeditfstError").html("Headline is required to submit the ad.");
                $("#customadediterrorsummary").show(500);
                setTimeout("$('#customadediterrorsummary').hide(500)", 5000);
                return false;
            }

            if (headln.toLowerCase().indexOf("...") != -1 || line1.toLowerCase().indexOf("...") != -1 || line2.toLowerCase().indexOf("...") != -1) {
                $("#customadeditfstError").html("You are using invalid punctuation [...].");
                $("#customadediterrorsummary").show(500);
                setTimeout("$('#customadediterrorsummary').hide(500)", 5000);
                return false;
            }

        } catch (e) { return false; }
        return true;
    },

    editAd: function() {
        if (!CustomAdWriterEditAd.adValidation())
            return false;

        var desturl = "";
        if ($("#customaddestinationurl").length != 0) {
            desturl = $("#customaddestinationurl").val();
        }
        this.DestinationURL = desturl;
        if ($("#blankCustomAdEditOpen").length == 0) {
            $('body').append("<a id='blanckCustomAdEditOpen' href='#TB_inline?500&width=700&inlineId=customadeditad-modal&modal=true' class='thickbox' style='display:none;'>&nbsp;</a>");
            tb_init('a.thickbox');
        }

        try {
            myChecker = new SpellChecker();
            //tb_remove();
            myChecker.checkSpelling($('#customadeditheadline'), function(status) {
                if (status) {
                    myChecker.checkSpelling($('#customadeditline1'), function(status) {
                        if (status) {
                            myChecker.checkSpelling($('#customadeditline2'), function(status) {
                                if (status) {
                                    if (CustomAdWriterEditAd.adValidation()) {
                                        this.Headline = $.trim($("#customadeditheadline").val());
                                        this.Line1 = $.trim($("#customadeditline1").val());

                                        $('input.button-submit').fadeTo('fast', 0.33).attr('disabled', 'disabled').css('cursor', 'default');
                                        $('input.button-cancel').fadeTo('fast', 0.33).attr('disabled', 'disabled').css('cursor', 'default');
                                        ProcessOverlay.show('dvCustomAdEditAdd');
                                        try {
                                            $.post("/Writer/EditCustomAdAdChallenge",
                                       {
                                           AdChallengeId: CustomAdWriterEditAd.adChallengeId,
                                           Headline: $("#customadeditheadline").val(),
                                           Line1: $("#customadeditline1").val(),
                                           Line2: $("#customadeditline2").val(),
                                           DisplayURL: $("#customadeditdisplayurl").val(),
                                           DestinationUrl: desturl
                                       },
                                       function(data) {
                                           if (data == null) {
                                               TopMessageAlert.showAlert("No response return from server.");
                                           }
                                           CustomAdWriterEditAd.editAd_callback(data);
                                       }, "json");
                                        } catch (e) {
                                            TopMessageAlert.showAlert("Error: " + e);
                                        }
                                    } else {
                                        //$("#blankCustomAdEditOpen").click();
                                        return false;
                                    }
                                }
                            })
                        }
                    })
                }
            })
        } catch (e) {
            TopMessageAlert.showAlert("Error: " + e);
        }
    },

    editAd_callback: function(resp) {
        $("#customadediterrorsummary").hide();
        this.reset(resp);
    },

    reset: function(resp) {
        try {
            if (resp != null && resp.ErrorList != null) {
                if (resp.ErrorList.length > 0) {
                    try {
                        $("#customadeditfstError").html(resp.ErrorList[0].ErrorMessage);
                        tb_show("Using Rejected Terms", "#TB_inline?height=500&width=700&inlineId=customadeditad-modal&modal=true");
                        $("#customadediterrorsummary").show(500);
                        setTimeout("$('#customadediterrorsummary').hide(500)", 5000);
                        ProcessOverlay.hide('dvCustomAdEditAdd');
                        $('.ajaxContainer').removeClass("ajaxContainer");
                        $('.ajaxMainProcessing').addClass("nodisplay");
                        $('input.button-submit')
                        .fadeTo('fast', 1.0)
                        .removeAttr('disabled')
                        .css('cursor', 'pointer');
                        $('input.button-cancel')
                        .fadeTo('fast', 1.0)
                        .removeAttr('disabled')
                        .css('cursor', 'pointer');
                        return false;
                    } catch (e) {
                        return false;
                    }
                }
                else {
                    alert("Changes have been successfully made");
                    tb_init('a.thickbox, area.thickbox, input.thickbox');

                    if (resp.adChallenge != null) {
                        CustomAdWriterEditAd.KeywordsExist = resp.adChallenge.KeywordsExist;
                    } else {
                        $.ajax({
                            type: 'POST',
                            url: "/Writer/GetAdChallenge",
                            dataType: "json",
                            async: false,
                            data: { AdChallengeId: CustomAdWriterEditAd.adChallengeId },
                            success: function(result) {
                                if (result != null) {
                                    CustomAdWriterEditAd.KeywordsExist = result.KeywordsExist;
                                }
                            },
                            error: function(req, status, error) {
                            }
                        });
                    }
                    if (CustomAdWriterEditAd.KeywordsExist)
                        $("#keyword_" + this.adChallengeId).addClass("nodisplay");
                    else
                        $("#keyword_" + this.adChallengeId).removeClass("nodisplay");
                }
            }
        } catch (e) { }
        $("#lnkHeadline_" + this.adChallengeId).html($("#customadeditheadline").val());
        try {
            $("#lblLine1_" + this.adChallengeId).text($("#customadeditline1").val());
            if ($("#lblLine1_" + this.adChallengeId).text() != $("#customadeditline1").val())
                $("#lblLine1_" + this.adChallengeId).html($("#customadeditline1").val());
        } catch (e) {
            $("#lblLine1_" + this.adChallengeId).html($("#customadeditline1").val());
        }

        try {
            $("#lblLine2_" + this.adChallengeId).text($("#customadeditline2").val());
            if ($("#lblLine2_" + this.adChallengeId).text() != $("#customadeditline2").val())
                $("#lblLine2_" + this.adChallengeId).html($("#customadeditline2").val());
        } catch (e) {
            $("#lblLine2_" + this.adChallengeId).html($("#customadeditline2").val());
        }

        try {
            $("#lblDisplayURL_" + this.adChallengeId).text($("#customadeditdisplayurl").val());
            if ($("#lblDisplayURL_" + this.adChallengeId).text() != $("#customadeditdisplayurl").val())
                $("#lblDisplayURL_" + this.adChallengeId).html($("#customadeditdisplayurl").val());
        } catch (e) {
            $("#lblDisplayURL_" + this.adChallengeId).html($("#customadeditdisplayurl").val());
        }

        if ($("#customaddestinationurl").length != 0)
            $("#destURL_" + this.adChallengeId).val($("#customaddestinationurl").val());

        $('input.button-submit').fadeTo('fast', 1.0).removeAttr('disabled').css('cursor', 'pointer');
        $('input.button-cancel').fadeTo('fast', 1.0).removeAttr('disabled').css('cursor', 'pointer');

        this.challengeResponse = resp;
        this.adChallengeId = 0;
        this.Headline = '';
        this.Line1 = '';
        this.Line2 = '';
        this.DisplayURL = '';
        this.DestinationURL = '';
        $("#customadeditheadline").val('');
        $("#customadeditline1").val('');
        $("#customadeditline2").val('');
        ProcessOverlay.hide('dvCustomAdEditAdd');
        $('.ajaxContainer').removeClass("ajaxContainer");
        $('.ajaxMainProcessing').addClass("nodisplay");
        $("#customadediterrorsummary").hide();
        tb_remove();
        tooltip();
    }
}


AdCenterWriterEditAd = {
    adChallengeId: 0,
    DestinationUrl: '',
    Headline: '',
    Line1: '',
    Line2: '',
    DisplayUrl: '',
    ChampionHeadline: '',
    ChampionLine1: '',
    ChampionLine2: '',
    challengeResponse: null,
    IsContentNetwork: false,
    KeywordsExist: false,
    ChampionDifferencePercentage: '0',
    ShowChampDiff: true,

    init: function() {
        //$("#editheadline").bind("keyup", function() { var strVal = $("#editheadline").val(); $("#lbleditheadline").text(25 - parseInt(strVal.length)); AdCenterWriterEditAd.getAddBlock(); });
        $("#dvAdCenterEditAdd #adcentereditheadline").bind("keyup", function() {
            var cnt = AdWordsFunction.getHeadlineLength("dvAdCenterEditAdd #adcentereditheadline", AdCenterWriterEditAd.IsContentNetwork);
            if (cnt >= 0)
                $("#dvAdCenterEditAdd #lbladcentereditheadline").text(cnt);
            else
                $("#dvAdCenterEditAdd #lbladcentereditheadline").text(0);
            AdCenterWriterEditAd.getAddBlock();
        });

        $("#dvAdCenterEditAdd #adcentereditline1").bind("keyup", function() {
            var cnt = AdCenterFunction.getLine1Length("dvAdCenterEditAdd #adcentereditline1", AdCenterWriterEditAd.IsContentNetwork);
            if (cnt >= 0)
                $("#dvAdCenterEditAdd #lbladcentereditline1").text(cnt);
            else
                $("#dvAdCenterEditAdd #lbladcentereditline1").text(0);
            AdCenterWriterEditAd.getAddBlock();
        });

        $("#dvAdCenterEditAdd #adcenterediturldisplay").bind("keyup", function() { var strVal = $("#dvAdCenterEditAdd #adcenterediturldisplay").val().toLowerCase().replace(".com.au", ".com"); $("#dvAdCenterEditAdd #lbladcenterediturldisplay").text(35 - parseInt(strVal.length)); AdCenterWriterEditAd.getAddBlock(); });
        if ($("#dvAdCenterEditAdd #adcentereditdesturl").length != 0) {
            $("#dvAdCenterEditAdd #adcentereditdesturl").bind("keyup", function() { var strVal = $("#dvAdCenterEditAdd #adcentereditdesturl").val(); $("#dvAdCenterEditAdd #lbladcentereditdesturl").text(1000 - parseInt(strVal.length)); AdCenterWriterEditAd.getAddBlock(); });
        }
        $("#dvAdCenterEditAdd #adcentereditline1").attr("maxlength", 70);
        $("#dvAdCenterEditAdd #adcenterediturldisplay").attr("maxlength", 40);
        if ($("#dvAdCenterEditAdd #adcentereditdesturl").length != 0) {
            $("#dvAdCenterEditAdd #adcentereditdesturl").attr("maxlength", 1000);
        }
        return true;
    },

    setCurrentChallenge: function(adchallengeid) {
        AdCenterWriterEditAd.adChallengeId = adchallengeid;

        ProcessOverlay.show('dvAdCenterEditAdd');
        $.ajax({
            type: 'POST',
            url: "/Writer/GetAdChallenge",
            dataType: "json",
            async: false,
            data: { AdChallengeId: AdCenterWriterEditAd.adChallengeId },
            success: function(result) {
                if (result != null) {
                    AdCenterWriterEditAd.Headline = result.Headline.split("`").join("'");
                    AdCenterWriterEditAd.Line1 = result.Line1.split("`").join("'");
                    AdCenterWriterEditAd.Line2 = "";
                    AdCenterWriterEditAd.DisplayUrl = result.DisplayUrl.split("`").join("'");
                    AdCenterWriterEditAd.DestinationUrl = result.DestinationUrl;
                    AdCenterWriterEditAd.ChampionHeadline = result.ChampionHeadline;
                    AdCenterWriterEditAd.ChampionLine1 = result.ChampionLine1;
                    AdCenterWriterEditAd.ChampionLine2 = "";
                    AdCenterWriterEditAd.IsContentNetwork = (result.Network == "Content Network" ? true : false);
                    AdCenterWriterEditAd.KeywordsExist = result.KeywordsExist;
                    AdCenterWriterEditAd.ChampionDifferencePercentage = result.ChampionDifferencePercentage;
                    AdCenterWriterEditAd.ShowChampDiff = result.ShowChampDiff;
                }
            },
            error: function(req, status, error) {
            }
        });

        ProcessOverlay.hide('dvAdCenterEditAdd');
        $("#dvAdCenterEditAdd #adcentereditheadline").val(AdCenterWriterEditAd.Headline);
        $("#dvAdCenterEditAdd #lbladcentereditheadline").text(AdWordsFunction.getHeadlineLength("dvAdCenterEditAdd #adcentereditheadline", AdCenterWriterEditAd.IsContentNetwork));
        $("#dvAdCenterEditAdd #adcentereditline1").val(AdCenterWriterEditAd.Line1);
        $("#dvAdCenterEditAdd #lbladcentereditline1").text(AdCenterFunction.getLine1Length("dvAdCenterEditAdd #adcentereditline1", AdCenterWriterEditAd.IsContentNetwork));
        $("#dvAdCenterEditAdd #adcenterediturldisplay").val(AdCenterWriterEditAd.DisplayUrl);
        $("#dvAdCenterEditAdd #lbladcenterediturldisplay").text(35 - parseInt($("#dvAdCenterEditAdd #adcenterediturldisplay").val().toLowerCase().replace(".com.au", ".com").length));
        if ($("#dvAdCenterEditAdd #adcentereditdesturl").length != 0) {
            $("#dvAdCenterEditAdd #adcentereditdesturl").val(AdCenterWriterEditAd.DestinationUrl);
            $("#dvAdCenterEditAdd #lbladcentereditdesturl").text(1000 - parseInt($("#dvAdCenterEditAdd #adcentereditdesturl").val().length));
        }
        AdCenterWriterEditAd.getAddBlock();
    },

    getAddBlock: function(showkeyword, showinfo) {
        if (showkeyword == undefined || showkeyword == null)
            showkeyword = false;
        if (showinfo == undefined || showinfo == null)
            showinfo = false;

        var sb = "";
        if (showinfo)
            sb += '<a href="#" class="info tooltip" style="float:right;" title="<br/><b>Champion Character Difference:</b> ' + AdCenterWriterEditAd.ChampionDifferencePercentage + '%<br/><br/>">info</a>';

        sb += "<div class='boostab leftalign'> ";
        sb += "<a class='main headline' href='";
        if ($("#dvAdCenterEditAdd #adcentereditdesturl").length != 0)
            sb += $("#dvAdCenterEditAdd #adcentereditdesturl").val()
        else
            sb += "javascript:";
        sb += "'>";
        if (showkeyword)
            sb += $("#dvAdCenterEditAdd #adcentereditheadline").val() + "</a> ";
        else
            sb += (AdCenterWriterEditAd.IsContentNetwork ? $("#dvAdCenterEditAdd #adcentereditheadline").val() : AdWordsFunction.getKeywordfilter($("#dvAdCenterEditAdd #adcentereditheadline").val())) + "</a> ";
        sb += "<p>";
        if (showkeyword)
            sb += $("#dvAdCenterEditAdd #adcentereditline1").val() + "<br /></p> ";
        else
            sb += (AdCenterWriterEditAd.IsContentNetwork ? $("#dvAdCenterEditAdd #adcentereditline1").val() : AdWordsFunction.getKeywordfilter($("#dvAdCenterEditAdd #adcentereditline1").val())) + "<br /></p> ";
        sb += "<a class='site' href='";
        if ($("#dvAdCenterEditAdd #adcentereditdesturl").length != 0)
            sb += $("#dvAdCenterEditAdd #adcentereditdesturl").val()
        else
            sb += "javascript:";
        sb += "'>";
        sb += $("#dvAdCenterEditAdd #adcenterediturldisplay").val() + "</a> ";
        sb += "</div>";
        $("#dvAdCenterEditAdd #adcentereditadBox").html(sb);
        return sb;
    },

    adValidation: function() {
        try {
            var IsAdv = (IsAdvertiser != undefined && IsAdvertiser == "True" ? true : false);
            var IgnoreWords = AdCenterWriterEditAd.ChampionHeadline + ' ' + AdCenterWriterEditAd.ChampionLine1;
            if (this.adChallengeId == 0) {
                alert('No item selected.');
                return false;
            }

            if (this.Headline == $("#dvAdCenterEditAdd #adcentereditheadline").val() && this.Line1 == $("#dvAdCenterEditAdd #adcentereditline1").val() && this.DisplayUrl == $("#dvAdCenterEditAdd #adcenterediturldisplay").val() && ($("#dvAdCenterEditAdd #adcentereditdesturl").length != 0 ? (this.DestinationUrl == $("#dvAdCenterEditAdd #adcentereditdesturl").val()) : true)) {
                $("#dvAdCenterEditAdd #adcentereditfstError").html("You must change at least one character before submit");
                $("#dvAdCenterEditAdd #adcenterediterrorsummary").show(500);
                setTimeout("$('#dvAdCenterEditAdd #adcenterediterrorsummary').hide(500)", 5000);
                return false;
            }

            var strVal = $("#dvAdCenterEditAdd #adcentereditheadline").val();
            strVal = (AdCenterWriterEditAd.IsContentNetwork ? strVal : AdWordsFunction.getKeywordfilter(strVal));
            if (strVal.length > 25) {
                $("#dvAdCenterEditAdd #adcentereditfstError").html("Maximum 25 char allowed in Headline.");
                $("#dvAdCenterEditAdd #adcenterediterrorsummary").show(500);
                setTimeout("$('#dvAdCenterEditAdd #adcenterediterrorsummary').hide(500)", 5000);
                return false;
            }

            strVal = (AdCenterWriterEditAd.IsContentNetwork ? $("#dvAdCenterEditAdd #adcentereditline1").val() : AdWordsFunction.getKeywordfilter($("#dvAdCenterEditAdd #adcentereditline1").val()));
            if (strVal.length > 70) {
                $("#dvAdCenterEditAdd #adcentereditfstError").html("Maximum 70 char allowed in Line1.");
                $("#dvAdCenterEditAdd #adcenterediterrorsummary").show(500);
                setTimeout("$('#dvAdCenterEditAdd #adcenterediterrorsummary').hide(500)", 5000);
                return false;
            }

            if (AdCenterWriterEditAd.IsContentNetwork) {
                var completeadtext = $("#dvAdCenterEditAdd #adcentereditheadline").val() + $("#dvAdCenterEditAdd #adcentereditline1").val();
                if (completeadtext.toLowerCase().indexOf("{keyword:") >= 0 && completeadtext.indexOf("}") > completeadtext.toLowerCase().indexOf("{keyword:")) {
                    $("#dvAdCenterEditAdd #adcentereditfstError").html("{Keyword:[A-Z]} not allowed in Content Network adgroups.");
                    $("#dvAdCenterEditAdd #adcenterediterrorsummary").show(500);
                    setTimeout("$('#dvAdCenterEditAdd #adcenterediterrorsummary').hide(500)", 5000);
                    return false;
                }
            }

            if ($.trim($("#dvAdCenterEditAdd #adcenterediturldisplay").val()).toLowerCase().replace(".com.au", ".com").length > 35) {
                $("#dvAdCenterEditAdd #adcentereditfstError").html("Maximum 35 char allowed in Display URL.");
                $("#dvAdCenterEditAdd #adcenterediterrorsummary").show(500);
                setTimeout("$('#dvAdCenterEditAdd #adcenterediterrorsummary').hide(500)", 5000);
                return false;
            }

            if ((!IsAdv) && FiledValidation.GetUpperWordCount($("#dvAdCenterEditAdd #adcentereditheadline").val(), 4, IgnoreWords) > 0) {
                $("#dvAdCenterEditAdd #adcentereditfstError").html("Excessive capitalization in Headline");
                $("#dvAdCenterEditAdd #adcenterediterrorsummary").show(500);
                setTimeout("$('#dvAdCenterEditAdd #adcenterediterrorsummary').hide(500)", 5000);
                return false;
            }

            if ((!IsAdv) && FiledValidation.GetUpperWordCount($("#dvAdCenterEditAdd #adcentereditline1").val(), 4, IgnoreWords) > 0) {
                $("#dvAdCenterEditAdd #adcentereditfstError").html("Excessive capitalization in Line 1");
                $("#dvAdCenterEditAdd #adcenterediterrorsummary").show(500);
                setTimeout("$('#dvAdCenterEditAdd #adcenterediterrorsummary').hide(500)", 5000);
                return false;
            }

            if ($("#dvAdCenterEditAdd #adcentereditheadline").val().toLowerCase().indexOf("...") != -1
                || $("#dvAdCenterEditAdd #adcentereditline1").val().toLowerCase().indexOf("...") != -1
                || $("#dvAdCenterEditAdd #adcenterediturldisplay").val().toLowerCase().indexOf("...") != -1) {
                $("#dvAdCenterEditAdd #adcentereditfstError").html("You are using invalid punctuation [...].");
                $("#dvAdCenterEditAdd #adcenterediterrorsummary").show(500);
                setTimeout("$('#dvAdCenterEditAdd #adcenterediterrorsummary').hide(500)", 5000);
                return false;
            }

            var destinationurl = "";
            if ($("#dvAdCenterEditAdd #adcentereditdesturl").length != 0) {
                destinationurl = $.trim($("#dvAdCenterEditAdd #adcentereditdesturl").val());
                if (destinationurl.startsWith("http://") == false && destinationurl.startsWith("https://") == false) {
                    $("#dvAdCenterEditAdd #adcentereditfstError").html("Please provide http or https in destination url");
                    $("#dvAdCenterEditAdd #adcenterediterrorsummary").show(500);
                    setTimeout("$('#dvAdCenterEditAdd #adcenterediterrorsummary').hide(500)", 5000);
                    return false;
                }
            }

            var totalAdText = $.trim($("#dvAdCenterEditAdd #adcentereditheadline").val()) + $.trim($("#dvAdCenterEditAdd #adcentereditline1").val());
            var cCheck = totalAdText.match(/!/ig) || [];
            if (cCheck.length > 1) {
                $("#dvAdCenterEditAdd #adcentereditfstError").html("No more than one exclamation point (!) allowed in ad.");
                $("#dvAdCenterEditAdd #adcenterediterrorsummary").show(500);
                setTimeout("$('#dvAdCenterEditAdd #adcenterediterrorsummary').hide(500)", 5000);
                return false;
            }
        } catch (e) {
            return false;
        }
        return true;
    },

    editAd: function() {
        if (!AdCenterWriterEditAd.adValidation()) {
            return false;
        }
        var destinationurl = "";
        if ($("#dvAdCenterEditAdd #adcentereditdesturl").length != 0) {
            destinationurl = $.trim($("#dvAdCenterEditAdd #adcentereditdesturl").val());
        }
        if ($("#blankEditOpen").length == 0) {
            $('body').append("<a id='blankEditOpen' href='#TB_inline?height=430&width=600&inlineId=editad-modal&modal=true' class='thickbox' style='display:none;'>&nbsp;</a>");
            tb_init('a.thickbox');
        }

        try {
            myChecker = new SpellChecker();
            //tb_remove();
            myChecker.checkSpelling($('#dvAdCenterEditAdd #adcentereditheadline'), function(status) {
                if (status)
                    myChecker.checkSpelling($('#dvAdCenterEditAdd #adcentereditline1'), function(status) {
                        if (status)
                            myChecker.checkSpelling($('#dvAdCenterEditAdd #adcentereditline1'), function(status) {
                                if (status)
                                    myChecker.checkSpelling($('#dvAdCenterEditAdd #adcenterediturldisplay'), function(status) {
                                        if (status) {
                                            if (AdCenterWriterEditAd.adValidation()) {
                                                //if ($("#lnkEditShow") != null) { $("#lnkEditShow").click(); }
                                                this.Headline = $.trim($("#dvAdCenterEditAdd #adcentereditheadline").val());
                                                this.Line1 = $.trim($("#dvAdCenterEditAdd #adcentereditline1").val());
                                                this.Line2 = "";
                                                this.DisplayUrl = $.trim($("#dvAdCenterEditAdd #adcenterediturldisplay").val());
                                                this.DestinationUrl = ($("#dvAdCenterEditAdd #adcentereditdesturl").length != 0 ? $.trim($("#dvAdCenterEditAdd #adcentereditdesturl").val()) : "");

                                                ProcessOverlay.show('dvAdCenterEditAdd');

                                                $.post("/Writer/EditAdCenterAdChallenge",
                                                   {
                                                       AdChallengeId: AdCenterWriterEditAd.adChallengeId, Headline: $.trim($("#dvAdCenterEditAdd #adcentereditheadline").val()), Line1: $.trim($("#dvAdCenterEditAdd #adcentereditline1").val()), DisplayUrl: $.trim($("#dvAdCenterEditAdd #adcenterediturldisplay").val()), DestinationUrl: (destinationurl != "" ? destinationurl : "")
                                                   },
                                                   function(data) {
                                                       if (data == null) {
                                                           TopMessageAlert.showAlert("No response return from server.");
                                                       }
                                                       AdCenterWriterEditAd.editAd_callback(data);
                                                   }, "json");
                                            } else {
                                                //$("#blankEditOpen").click();
                                                return false;
                                            }
                                        }
                                    })
                            })
                    })
            })
        } catch (e) {
            TopMessageAlert.showAlert("Error: " + e);
        }
    },

    editAd_callback: function(resp) {
        try {
            $("#dvAdCenterEditAdd #adcenterediterrorsummary").hide();
            if (resp.ErrorList.length > 0) {
                if (resp.ErrorList[0].ErrorMessage.indexOf("login failed") > 0)
                    $("#dvAdCenterEditAdd #adcentereditfstError").html("Adwords Login failed,<br/>Please go to \"Account & Settings\" option from Header,<br/>Open \"Edit Network Accounts\" option and verify your account credentials.");
                else
                    $("#dvAdCenterEditAdd #adcentereditfstError").html(resp.ErrorList[0].ErrorMessage);
                $("#dvAdCenterEditAdd #adcenterediterrorsummary").show(500);
                setTimeout("$('#dvAdCenterEditAdd #adcenterediterrorsummary').hide(500)", 5000);
                ProcessOverlay.hide('dvAdCenterEditAdd');
                $('.ajaxContainer').removeClass("ajaxContainer");
                $('.ajaxMainProcessing').addClass("nodisplay");
                return;
            }
            else {
                alert("Changes have been successfully made");
                //var instr = "<a id='btnEdit" + this.adChallengeId + "' href='#TB_inline?height=350&width=560&inlineId=editad-modal&modal=true' onclick='AdCenterWriterEditAd.setCurrentChallenge(" + this.adTrialId + "," + this.adChallengeId + ",\"" + $.trim($("#dvAdCenterEditAdd #adcentereditdesturl").val()).split("'").join("`") + "\",\"" + $.trim($("#dvAdCenterEditAdd #adcentereditheadline").val()).split("'").join("`") + "\",\"" + $.trim($("#dvAdCenterEditAdd #adcentereditline1").val()).split("'").join("`") + "\",\"" + $.trim($("#dvAdCenterEditAdd #adcentereditline2").val()).split("'").join("`") + "\",\"" + $.trim($("#dvAdCenterEditAdd #adcenterediturldisplay").val()).split("'").join("`") + "\");' class='thickbox mbutton mbutton-green'>Edit</a>";
                //$("#link" + this.adChallengeId).html(instr);
                if (window.location.href.toLowerCase().indexOf("writeradmin/submissionlist") > 0)
                    $("#editad" + this.adChallengeId).html(AdCenterWriterEditAd.getAddBlock(true, false));
                else
                    $("#editad" + this.adChallengeId).html(AdCenterWriterEditAd.getAddBlock(true, AdCenterWriterEditAd.ShowChampDiff));
                tb_init('a.thickbox, area.thickbox, input.thickbox');

                if (resp.adChallenge != null) {
                    AdCenterWriterEditAd.KeywordsExist = resp.adChallenge.KeywordsExist;
                } else {
                    $.ajax({
                        type: 'POST',
                        url: "/Writer/GetAdChallenge",
                        dataType: "json",
                        async: false,
                        data: { AdChallengeId: AdCenterWriterEditAd.adChallengeId },
                        success: function(result) {
                            if (result != null) {
                                AdCenterWriterEditAd.KeywordsExist = result.KeywordsExist;
                            }
                        },
                        error: function(req, status, error) {
                        }
                    });
                }
                if (AdCenterWriterEditAd.KeywordsExist)
                    $("#keyword_" + this.adChallengeId).addClass("nodisplay");
                else
                    $("#keyword_" + this.adChallengeId).removeClass("nodisplay");
            }
        } catch (e) { }
        this.challengeResponse = resp;
        this.adChallengeId = 0;
        $("#dvAdCenterEditAdd #adcenterediterrorsummary").hide();
        tb_remove();
        AdWordsFunction.formatHeadline();
        ProcessOverlay.hide('dvAdCenterEditAdd');
        $('.ajaxContainer').removeClass("ajaxContainer");
        $('.ajaxMainProcessing').addClass("nodisplay");
        tooltip();        
    }

}

WriterEditAd = {
    adChallengeId: 0,
    DestinationUrl: '',
    Headline: '',
    Line1: '',
    Line2: '',
    DisplayUrl: '',
    ChampionHeadline: '',
    ChampionLine1: '',
    ChampionLine2: '',
    challengeResponse: null,
    IsContentNetwork: false,
    KeywordsExist: false,
    ChampionDifferencePercentage: '0',
    CapitalizationWhiteList: '',
    ShowChampDiff: false,

    init: function() {
        //$("#editheadline").bind("keyup", function() { var strVal = $("#editheadline").val(); $("#lbleditheadline").text(25 - parseInt(strVal.length)); WriterEditAd.getAddBlock(); });
        $("#dvEditAdd #editheadline").bind("keyup", function() {
            var cnt = AdWordsFunction.getHeadlineLength("dvEditAdd #editheadline", WriterEditAd.IsContentNetwork);
            if (cnt >= 0)
                $("#dvEditAdd #lbleditheadline").text(cnt);
            else
                $("#dvEditAdd #lbleditheadline").text(0);
            WriterEditAd.getAddBlock();
        });

        $("#dvEditAdd #editline1").bind("keyup", function() {
            var cnt = AdWordsFunction.getLine1Length("dvEditAdd #editline1", WriterEditAd.IsContentNetwork);
            if (cnt >= 0)
                $("#dvEditAdd #lbleditline1").text(cnt);
            else
                $("#dvEditAdd #lbleditline1").text(0);
            WriterEditAd.getAddBlock();
        });

        $("#dvEditAdd #editline2").bind("keyup", function() {
            var cnt = AdWordsFunction.getLine2Length("dvEditAdd #editline2", WriterEditAd.IsContentNetwork);
            if (cnt >= 0)
                $("#dvEditAdd #lbleditline2").text(cnt);
            else
                $("#dvEditAdd #lbleditline2").text(0);
            WriterEditAd.getAddBlock();
        });

        $("#dvEditAdd #editurldisplay").bind("keyup", function() { var strVal = $("#dvEditAdd #editurldisplay").val().toLowerCase().replace(".com.au", ".com"); $("#dvEditAdd #lblediturldisplay").text(35 - parseInt(strVal.length)); WriterEditAd.getAddBlock(); });
        if ($("#dvEditAdd #editdesturl").length != 0) {
            $("#dvEditAdd #editdesturl").bind("keyup", function() { var strVal = $("#dvEditAdd #editdesturl").val(); $("#dvEditAdd #lbleditdesturl").text(1000 - parseInt(strVal.length)); WriterEditAd.getAddBlock(); });
        }
        $("#dvEditAdd #editline1").attr("maxlength", 35);
        $("#dvEditAdd #editline2").attr("maxlength", 35);
        $("#dvEditAdd #editurldisplay").attr("maxlength", 40);
        if ($("#dvEditAdd #editdesturl").length != 0) {
            $("#dvEditAdd #editdesturl").attr("maxlength", 1000);
        }
        return true;
    },

    setCurrentChallenge: function(adchallengeid) {
        WriterEditAd.adChallengeId = adchallengeid;

        ProcessOverlay.show('dvEditAdd');
        $.ajax({
            type: 'POST',
            url: "/Writer/GetAdChallenge",
            dataType: "json",
            async: false,
            data: { AdChallengeId: WriterEditAd.adChallengeId },
            success: function(result) {
                if (result != null) {
                    WriterEditAd.Headline = result.Headline.split("`").join("'");
                    WriterEditAd.Line1 = result.Line1.split("`").join("'");
                    WriterEditAd.Line2 = result.Line2.split("`").join("'");
                    WriterEditAd.DisplayUrl = result.DisplayUrl.split("`").join("'");
                    WriterEditAd.DestinationUrl = result.DestinationUrl;
                    WriterEditAd.ChampionHeadline = result.ChampionHeadline;
                    WriterEditAd.ChampionLine1 = result.ChampionLine1;
                    WriterEditAd.ChampionLine2 = result.ChampionLine2;
                    WriterEditAd.IsContentNetwork = (result.Network == "Content Network" ? true : false);
                    WriterEditAd.KeywordsExist = result.KeywordsExist;
                    WriterEditAd.ChampionDifferencePercentage = result.ChampionDifferencePercentage;
                    WriterEditAd.CapitalizationWhiteList = result.CapitalizationWhiteList;
                    WriterEditAd.ShowChampDiff = result.ShowChampDiff;
                }
            },
            error: function(req, status, error) {
            }
        });

        ProcessOverlay.hide('dvEditAdd');
        $("#dvEditAdd #editheadline").val(WriterEditAd.Headline);
        $("#dvEditAdd #lbleditheadline").text(AdWordsFunction.getHeadlineLength("dvEditAdd #editheadline", WriterEditAd.IsContentNetwork));
        $("#dvEditAdd #editline1").val(WriterEditAd.Line1);
        $("#dvEditAdd #lbleditline1").text(AdWordsFunction.getLine1Length("dvEditAdd #editline1", WriterEditAd.IsContentNetwork));
        $("#dvEditAdd #editline2").val(WriterEditAd.Line2);
        $("#dvEditAdd #lbleditline2").text(AdWordsFunction.getLine2Length("dvEditAdd #editline2", WriterEditAd.IsContentNetwork));
        $("#dvEditAdd #editurldisplay").val(WriterEditAd.DisplayUrl);
        $("#dvEditAdd #lblediturldisplay").text(35 - parseInt($("#dvEditAdd #editurldisplay").val().toLowerCase().replace(".com.au", ".com").length));
        if ($("#dvEditAdd #editdesturl").length != 0) {
            $("#dvEditAdd #editdesturl").val(WriterEditAd.DestinationUrl);
            $("#dvEditAdd #lbleditdesturl").text(1000 - parseInt($("#dvEditAdd #editdesturl").val().length));
        }
        WriterEditAd.getAddBlock();
    },

    getAddBlock: function(showkeyword, showinfo) {
        if (showkeyword == undefined || showkeyword == null)
            showkeyword = false;
        if (showinfo == undefined || showinfo == null)
            showinfo = false;

        var sb = "";
        if (showinfo)
            sb += '<a href="#" class="info tooltip" style="float:right;" title="<br/><b>Champion Character Difference:</b> ' + WriterEditAd.ChampionDifferencePercentage + '%<br/><br/>">info</a>';

        sb += "<div class='boostab leftalign'> ";
        sb += "<a class='main headline' href='";
        if ($("#dvEditAdd #editdesturl").length != 0)
            sb += $("#dvEditAdd #editdesturl").val()
        else
            sb += "javascript:";
        sb += "'>";
        if (showkeyword)
            sb += $("#dvEditAdd #editheadline").val() + "</a> ";
        else
            sb += (WriterEditAd.IsContentNetwork ? $("#dvEditAdd #editheadline").val() : AdWordsFunction.getKeywordfilter($("#dvEditAdd #editheadline").val())) + "</a> ";
        sb += "<p>";
        if (showkeyword)
            sb += $("#dvEditAdd #editline1").val() + "<br />" + $("#dvEditAdd #editline2").val() + "</p> ";
        else
            sb += (WriterEditAd.IsContentNetwork ? $("#dvEditAdd #editline1").val() : AdWordsFunction.getKeywordfilter($("#dvEditAdd #editline1").val())) + "<br />" + (WriterEditAd.IsContentNetwork ? $("#dvEditAdd #editline2").val() : AdWordsFunction.getKeywordfilter($("#dvEditAdd #editline2").val())) + "</p> ";
        sb += "<a class='site' href='";
        if ($("#dvEditAdd #editdesturl").length != 0)
            sb += $("#dvEditAdd #editdesturl").val()
        else
            sb += "javascript:";
        sb += "'>";
        sb += $("#dvEditAdd #editurldisplay").val() + "</a> ";
        sb += "</div>";
        $("#dvEditAdd #editadBox").html(sb);
        return sb;
    },

    adValidation: function() {
        try {
            var IsAdv = (IsAdvertiser != undefined && IsAdvertiser == "True" ? true : false);
            var IgnoreWords = WriterEditAd.ChampionHeadline + ' ' + WriterEditAd.ChampionLine1 + ' ' + WriterEditAd.ChampionLine2 + ' ' + WriterEditAd.CapitalizationWhiteList.split(' ').join(' ');
            if (this.adChallengeId == 0) {
                alert('No item selected.');
                return false;
            }

            if (this.Headline == $("#dvEditAdd #editheadline").val() && this.Line1 == $("#dvEditAdd #editline1").val() && this.Line2 == $("#dvEditAdd #editline2").val() && this.DisplayUrl == $("#dvEditAdd #editurldisplay").val() && ($("#dvEditAdd #editdesturl").length != 0 ? (this.DestinationUrl == $("#dvEditAdd #editdesturl").val()) : true)) {
                $("#dvEditAdd #editfstError").html("You must change at least one character before submit");
                $("#dvEditAdd #editerrorsummary").show(500);
                setTimeout("$('#dvEditAdd #editerrorsummary').hide(500)", 5000);
                return false;
            }

            var strVal = $("#dvEditAdd #editheadline").val();
            strVal = (WriterEditAd.IsContentNetwork ? strVal : AdWordsFunction.getKeywordfilter(strVal));
            if (strVal.length > 25) {
                $("#dvEditAdd #editfstError").html("Maximum 25 char allowed in Headline.");
                $("#dvEditAdd #editerrorsummary").show(500);
                setTimeout("$('#dvEditAdd #editerrorsummary').hide(500)", 5000);
                return false;
            }

            strVal = (WriterEditAd.IsContentNetwork ? $("#dvEditAdd #editline1").val() : AdWordsFunction.getKeywordfilter($("#dvEditAdd #editline1").val()));
            if (strVal.length > 35) {
                $("#dvEditAdd #editfstError").html("Maximum 35 char allowed in Line1.");
                $("#dvEditAdd #editerrorsummary").show(500);
                setTimeout("$('#dvEditAdd #editerrorsummary').hide(500)", 5000);
                return false;
            }

            strVal = (WriterEditAd.IsContentNetwork ? $("#dvEditAdd #editline2").val() : AdWordsFunction.getKeywordfilter($("#dvEditAdd #editline2").val()));
            if (strVal.length > 35) {
                $("#dvEditAdd #editfstError").html("Maximum 35 char allowed in Line2.");
                $("#dvEditAdd #editerrorsummary").show(500);
                setTimeout("$('#dvEditAdd #editerrorsummary').hide(500)", 5000);
                return false;
            }

            if (WriterEditAd.IsContentNetwork) {
                var completeadtext = $("#dvEditAdd #editheadline").val() + $("#dvEditAdd #editline1").val() + $("#dvEditAdd #editline2").val();
                if (completeadtext.toLowerCase().indexOf("{keyword:") >= 0 && completeadtext.indexOf("}") > completeadtext.toLowerCase().indexOf("{keyword:")) {
                    $("#dvEditAdd #editfstError").html("{Keyword:[A-Z]} not allowed in Content Network adgroups.");
                    $("#dvEditAdd #editerrorsummary").show(500);
                    setTimeout("$('#dvEditAdd #editerrorsummary').hide(500)", 5000);
                    return false;
                }
            }

            if ($.trim($("#dvEditAdd #editurldisplay").val()).toLowerCase().replace(".com.au", ".com").length > 35) {
                $("#dvEditAdd #editfstError").html("Maximum 35 char allowed in Display URL.");
                $("#dvEditAdd #editerrorsummary").show(500);
                setTimeout("$('#dvEditAdd #editerrorsummary').hide(500)", 5000);
                return false;
            }

            if ((!IsAdv) && FiledValidation.GetUpperWordCount($("#dvEditAdd #editheadline").val(), 4, IgnoreWords) > 0) {
                $("#dvEditAdd #editfstError").html("Excessive capitalization in Headline");
                $("#dvEditAdd #editerrorsummary").show(500);
                setTimeout("$('#dvEditAdd #editerrorsummary').hide(500)", 5000);
                return false;
            }

            if ((!IsAdv) && FiledValidation.GetUpperWordCount($("#dvEditAdd #editline1").val(), 4, IgnoreWords) > 0) {
                $("#dvEditAdd #editfstError").html("Excessive capitalization in Line 1");
                $("#dvEditAdd #editerrorsummary").show(500);
                setTimeout("$('#dvEditAdd #editerrorsummary').hide(500)", 5000);
                return false;
            }

            if ((!IsAdv) && FiledValidation.GetUpperWordCount($("#dvEditAdd #editline2").val(), 4, IgnoreWords) > 0) {
                $("#dvEditAdd #editfstError").html("Excessive capitalization in Line 2");
                $("#dvEditAdd #editerrorsummary").show(500);
                setTimeout("$('#dvEditAdd #editerrorsummary').hide(500)", 5000);
                return false;
            }
            if ($("#dvEditAdd #editheadline").val().toLowerCase().indexOf("...") != -1
                || $("#dvEditAdd #editline1").val().toLowerCase().indexOf("...") != -1
                || $("#dvEditAdd #editline2").val().toLowerCase().indexOf("...") != -1
                || $("#dvEditAdd #editurldisplay").val().toLowerCase().indexOf("...") != -1) {
                $("#dvEditAdd #editfstError").html("You are using invalid punctuation [...].");
                $("#dvEditAdd #editerrorsummary").show(500);
                setTimeout("$('#dvEditAdd #editerrorsummary').hide(500)", 5000);
                return false;
            }

            var destinationurl = "";
            if ($("#dvEditAdd #editdesturl").length != 0) {
                destinationurl = $.trim($("#dvEditAdd #editdesturl").val());
                if (destinationurl.startsWith("http://") == false && destinationurl.startsWith("https://") == false) {
                    $("#dvEditAdd #editfstError").html("Please provide http or https in destination url");
                    $("#dvEditAdd #editerrorsummary").show(500);
                    setTimeout("$('#dvEditAdd #editerrorsummary').hide(500)", 5000);
                    return false;
                }
            }

            var totalAdText = $.trim($("#dvEditAdd #editheadline").val()) + $.trim($("#dvEditAdd #editline1").val()) + $.trim($("#dvEditAdd #editline2").val());
            var cCheck = totalAdText.match(/!/ig) || [];
            if (cCheck.length > 1) {
                $("#dvEditAdd #editfstError").html("No more than one exclamation point (!) allowed in ad.");
                $("#dvEditAdd #editerrorsummary").show(500);
                setTimeout("$('#dvEditAdd #editerrorsummary').hide(500)", 5000);
                return false;
            }
        } catch (e) {
            return false;
        }
        return true;
    },

    editAd: function() {
        if (!WriterEditAd.adValidation()) {
            return false;
        }
        var destinationurl = "";
        if ($("#dvEditAdd #editdesturl").length != 0) {
            destinationurl = $.trim($("#dvEditAdd #editdesturl").val());
        }
        if ($("#blankEditOpen").length == 0) {
            $('body').append("<a id='blankEditOpen' href='#TB_inline?height=430&width=600&inlineId=editad-modal&modal=true' class='thickbox' style='display:none;'>&nbsp;</a>");
            tb_init('a.thickbox');
        }

        try {
            myChecker = new SpellChecker();
            //tb_remove();
            myChecker.checkSpelling($('#dvEditAdd #editheadline'), function(status) {
                if (status)
                    myChecker.checkSpelling($('#dvEditAdd #editline1'), function(status) {
                        if (status)
                            myChecker.checkSpelling($('#dvEditAdd #editline1'), function(status) {
                                if (status)
                                    myChecker.checkSpelling($('#dvEditAdd #editurldisplay'), function(status) {
                                        if (status) {
                                            if (WriterEditAd.adValidation()) {
                                                //if ($("#lnkEditShow") != null) { $("#lnkEditShow").click(); }
                                                this.Headline = $.trim($("#dvEditAdd #editheadline").val());
                                                this.Line1 = $.trim($("#dvEditAdd #editline1").val());
                                                this.Line2 = $.trim($("#dvEditAdd #editline2").val());
                                                this.DisplayUrl = $.trim($("#dvEditAdd #editurldisplay").val());
                                                this.DestinationUrl = ($("#dvEditAdd #editdesturl").length != 0 ? $.trim($("#dvEditAdd #editdesturl").val()) : "");

                                                ProcessOverlay.show('dvEditAdd');

                                                $.post("/Writer/EditAdChallenge",
                                                   {
                                                       AdChallengeId: WriterEditAd.adChallengeId, Headline: $.trim($("#dvEditAdd #editheadline").val()), Line1: $.trim($("#dvEditAdd #editline1").val()), Line2: $.trim($("#dvEditAdd #editline2").val()), DisplayUrl: $.trim($("#dvEditAdd #editurldisplay").val()), DestinationUrl: (destinationurl != "" ? destinationurl : "")
                                                   },
                                                   function(data) {
                                                       if (data == null) {
                                                           TopMessageAlert.showAlert("No response return from server.");
                                                       }
                                                       WriterEditAd.editAd_callback(data);
                                                   }, "json");
                                            } else {
                                                //$("#blankEditOpen").click();
                                                return false;
                                            }
                                        }
                                    })
                            })
                    })
            })
        } catch (e) {
            TopMessageAlert.showAlert("Error: " + e);
        }
    },

    editAd_callback: function(resp) {
        try {
            $("#dvEditAdd #editerrorsummary").hide();
            if (resp.ErrorList.length > 0) {
                if (resp.ErrorList[0].ErrorMessage.indexOf("login failed") > 0)
                    $("#dvEditAdd #editfstError").html("Adwords Login failed,<br/>Please go to \"Account & Settings\" option from Header,<br/>Open \"Edit Network Accounts\" option and verify your account credentials.");
                else
                    $("#dvEditAdd #editfstError").html(resp.ErrorList[0].ErrorMessage);
                $("#dvEditAdd #editerrorsummary").show(500);
                setTimeout("$('#dvEditAdd #editerrorsummary').hide(500)", 5000);
                ProcessOverlay.hide('dvEditAdd');
                $('.ajaxContainer').removeClass("ajaxContainer");
                $('.ajaxMainProcessing').addClass("nodisplay");
                return;
            }
            else {
                alert("Changes have been successfully made");
                //var instr = "<a id='btnEdit" + this.adChallengeId + "' href='#TB_inline?height=350&width=560&inlineId=editad-modal&modal=true' onclick='WriterEditAd.setCurrentChallenge(" + this.adTrialId + "," + this.adChallengeId + ",\"" + $.trim($("#dvEditAdd #editdesturl").val()).split("'").join("`") + "\",\"" + $.trim($("#dvEditAdd #editheadline").val()).split("'").join("`") + "\",\"" + $.trim($("#dvEditAdd #editline1").val()).split("'").join("`") + "\",\"" + $.trim($("#dvEditAdd #editline2").val()).split("'").join("`") + "\",\"" + $.trim($("#dvEditAdd #editurldisplay").val()).split("'").join("`") + "\");' class='thickbox mbutton mbutton-green'>Edit</a>";
                //$("#link" + this.adChallengeId).html(instr);
                $("#editad" + this.adChallengeId).html(WriterEditAd.getAddBlock(true, true));
                tb_init('a.thickbox, area.thickbox, input.thickbox');

                if (resp.adChallenge != null) {
                    WriterEditAd.KeywordsExist = resp.adChallenge.KeywordsExist;
                } else {
                    $.ajax({
                        type: 'POST',
                        url: "/Writer/GetAdChallenge",
                        dataType: "json",
                        async: false,
                        data: { AdChallengeId: WriterEditAd.adChallengeId },
                        success: function(result) {
                            if (result != null) {
                                WriterEditAd.KeywordsExist = result.KeywordsExist;
                            }
                        },
                        error: function(req, status, error) {
                        }
                    });
                }
                if (WriterEditAd.KeywordsExist)
                    $("#keyword_" + this.adChallengeId).addClass("nodisplay");
                else
                    $("#keyword_" + this.adChallengeId).removeClass("nodisplay");
            }
        } catch (e) { }
        this.challengeResponse = resp;
        this.adChallengeId = 0;
        $("#dvEditAdd #editerrorsummary").hide();
        tb_remove();
        AdWordsFunction.formatHeadline();
        ProcessOverlay.hide('dvEditAdd');
        $('.ajaxContainer').removeClass("ajaxContainer");
        $('.ajaxMainProcessing').addClass("nodisplay");
        tooltip();
    }

}
var WriterSignupModal = {
    isValid: true,

    init: function() {
        $("input[type='text']").change(function() { if ($(this).val() != "") { $(this).removeClass("errorfield"); $("#spn" + this.id).addClass("nodisplay"); } });
        $("input[type='password']").change(function() { if ($(this).val() != "") { $(this).removeClass("errorfield"); $("#spn" + this.id).addClass("nodisplay"); } });
        $("#Password").blur(function() { if ($(this).val() != "") { $(this).removeClass("errorfield"); $("#spn" + this.id).addClass("nodisplay"); } });
        $("#UserName").blur(function() { WriterSignupModal.checkUserExist(); });

        $("#drpWCountry").change(function() {
            if ($("#drpWCountry").val() == "US") {
                $("#dvStateTextfield").addClass("nodisplay");
                $("#dvStateDropdown").removeClass("nodisplay");
            } else {
                $("#dvStateTextfield").removeClass("nodisplay");
                $("#dvStateDropdown").addClass("nodisplay");
            }
        });
        $("#drpWCountry").change();
    },

    submitUserData: function() {


        WriterSignupModal.isValid = WriterSignupModal.validation();
        ProcessOverlay.show("dvCreateAcc");
        if ($("input[name='writerlanguage']").attr('checked') || $("#otherlanguage").attr('checked')) {
            if (WriterSignupModal.isValid) {

                var Languages = "";
                $("input[name='writerlanguage']:checked").each(function() {
                    Languages += (Languages == "" ? $(this).val() : "," + $(this).val());
                });

                if ($("#otherlanguage:checked").val() != undefined)
                    Languages += (Languages == "" ? $("#txtotherlanguage").val() : "," + $("#txtotherlanguage").val());

                $.post("/Account/writerSignup",
                {
                    Email: $("#Email").val(),
                    FirstName: $("#FirstName").val(),
                    LastName: $("#LastName").val(),
                    Phone: $("#Phone").val(),
                    UserName: $("#UserName").val(),
                    Password: $("#Password").val(),
                    Languages: Languages,
                    Terms: $("#Terms").val(),
                    PayPal: $("#PayPal").val(),
                    State: ($("#drpWCountry").val() == "US" ? $("#drpWState").val() : $("#State").val()),
                    Country: $("#drpWCountry").val(),
                    Industry: $("#drpWIndustry").val()
                },
                function(data) { WriterSignupModal.submitUserData_callback(data); }, "json");
            }
            else {
                ProcessOverlay.hide("dvCreateAcc");
            }
        }
        else {
            alert("Select at least one language.");
            ProcessOverlay.hide("dvCreateAcc");
        }
    },

    submitUserData_callback: function(resp) {
        if (resp == "Incorrect Data") {
            WriterSignupModal.validation();
            ProcessOverlay.hide("dvCreateAcc");
        }
        else if (resp == "Successfull") {
            window.location.href = "/Writer/Dashboard";
        }
        else {
            WriterSignupModal.validation();
            ProcessOverlay.hide("dvCreateAcc");
        }
    },

    checkUserExist: function() {
        $.post("/Account/checkUserExist",
        {
            UserName: $("#UserName").val()
        },
        function(data) { WriterSignupModal.checkUserExist_callback(data); }, "json");
    },

    checkUserExist_callback: function(resp) {
        if (resp == "Exists" || resp == "Error") {
            $("#spnUserNameExist").removeClass("nodisplay");
            WriterSignupModal.isValid = false;
        }
        else
            $("#spnUserNameExist").addClass("nodisplay");
    },

    ValidateField: function(field, allow) {
        var regex = '^[A-Za-z\s]+[^&~#{,?;:!§*%$£¨^=0-9]*[A-Za-z]+[ÀÁÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ]*[ \t]*$';
        var badcitychars = '[&+~#{,?;:!(§)\\]*%\[$£"°¨^=0-9]';
        var fieldvalue = field.toString();
        var isValidField = true;

        if (allow == "punct") {
            if (fieldvalue.search(regex) == -1) {
                isValidField = false;
            }
            if (fieldvalue.search(badcitychars) != -1) {
                var fieldFromRegex = fieldvalue.substr(0, fieldvalue.search(badcitychars));
                if (fieldFromRegex.length != fieldvalue.length) {
                    isValidField = false;
                }
            }
        }
        else if (!allow) {
            if (fieldvalue.search(regex) == -1) {
                isValidField = false;
            }
        }
        return isValidField;
    },

    /* Valid Formats
    / 2155552527
    / (215) 555 2527
    / 215.555.2527
    / +1 215-555-2527
    / +1.215.555.2527
    */
    ValidatePhone: function() {
        var isPhoneValid = false;
        var phoneRegExp = /^((\+)?[1-9]{1,2})?([-\s\.])?((\(\d{1,4}\))|\d{1,4})(([-\s\.])?[0-9]{1,12}){1,2}$/;
        var phoneVal = $("#Phone").val();
        var numbers = phoneVal.split("").length;
        if (10 <= numbers && numbers <= 20 && phoneRegExp.test(phoneVal))
            isPhoneValid = true;
        return isPhoneValid;
    },

    validation: function() {
        WriterSignupModal.isValid = true;
        WriterSignupModal.checkUserExist();

        if ($("#Email").val() == "" || !FiledValidation.IsValidEmail($("#Email"))) {
            if (!$("#Email").val() == "")
                $("#spnEmail").text("Invalid");
            else
                $("#spnEmail").text("Required");
            $("#spnEmail").removeClass("nodisplay");
            $("#Email").addClass("errorfield");
            WriterSignupModal.isValid = false;
        }
        else
            $("#spnEmail").addClass("nodisplay");

        if ($("#State").val() != "") {
            if (!(this.ValidateField($("#State").val()))) {
                $("#spnState").html("Invalid");
                $("#spnState").removeClass("nodisplay");
                $("#State").addClass("errorfield");
                WriterSignupModal.isValid = false;
            }
        }
        else
            $("#spnState").addClass("nodisplay");

        if ($("#UserName").val() == "") {
            $("#spnUserName").html("Required");
            $("#spnUserName").removeClass("nodisplay");
            $("#UserName").addClass("errorfield");
            WriterSignupModal.isValid = false;
        }
        else
            $("#spnUserName").addClass("nodisplay");

        if ($("#Password").val() == "") {
            $("#spnPassword").html("Required");
            $("#spnPassword").removeClass("nodisplay");
            $("#Password").addClass("errorfield");
            WriterSignupModal.isValid = false;
        }
        else
            $("#spnPassword").addClass("nodisplay");

        if ($("#Password").val() != "" && $("#Password").val().length < 6) {
            $("#spnLenPassword").html("<div class='cl'>&nbsp;</div><label>&nbsp;</label>Password should be a minimum of 6 characters long.");
            $("#spnLenPassword").removeClass("nodisplay");
            $("#Password").addClass("errorfield");
            WriterSignupModal.isValid = false;
        }
        else if ($("#ConfirmPassword").val() == "") {
            $("#spnConfirmPassword").html("Required");
            $("#spnConfirmPassword").removeClass("nodisplay");
            $("#ConfirmPassword").addClass("errorfield");
            WriterSignupModal.isValid = false;
        }
        else if ($("#Password").val() != $("#ConfirmPassword").val()) {
            $("#spnLenPassword").html("<div class='cl'>&nbsp;</div><label>&nbsp;</label>Confirm Password not matched.");
            $("#spnLenPassword").removeClass("nodisplay");
            $("#Password").addClass("errorfield");
            $("#ConfirmPassword").addClass("errorfield");
            WriterSignupModal.isValid = false;
        }
        else
            $("#spnLenPassword").addClass("nodisplay");


        if ($("#FirstName").val() == "") {
            $("#spnFirstName").removeClass("nodisplay");
            $("#FirstName").addClass("errorfield");
            WriterSignupModal.isValid = false;
        }
        else if (!(this.ValidateField($("#FirstName").val()))) {
            $("#spnFirstName").html("Invalid");
            $("#spnFirstName").removeClass("nodisplay");
            $("#FirstName").addClass("errorfield");
            WriterSignupModal.isValid = false;
        }
        else
            $("#spnFirstName").addClass("nodisplay");

        if ($("#LastName").val() == "") {
            $("#spnLastName").removeClass("nodisplay");
            $("#LastName").addClass("errorfield");
            WriterSignupModal.isValid = false;
        }
        else if (!(this.ValidateField($("#LastName").val()))) {
            $("#spnLastName").html("Invalid");
            $("#spnLastName").removeClass("nodisplay");
            $("#LastName").addClass("errorfield");
            WriterSignupModal.isValid = false;
        }
        else
            $("#spnLastName").addClass("nodisplay");

        if ($("#Phone").val() == "") {
            $("#spnPhone").removeClass("nodisplay");
            $("#Phone").addClass("errorfield");
            WriterSignupModal.isValid = false;
        }
        else {
            $("#spnPhone").addClass("nodisplay");
        }

        if ($("#otherlanguage:checked").val() != undefined) {
            if ($("#txtotherlanguage").val() == "") {
                $("#spnLanguages").html("Required");
                $("#spnLanguages").removeClass("nodisplay");
                $("#txtotherlanguage").addClass("errorfield");
                WriterSignupModal.isValid = false;
            }
            else if (!this.ValidateField($("#txtotherlanguage").val())) {
                $("#spnLanguages").html("Invalid");
                $("#spnLanguages").removeClass("nodisplay");
                $("#txtotherlanguage").addClass("errorfield");
                WriterSignupModal.isValid = false;
            }
            else {
                $("#spnLanguages").addClass("nodisplay");
                $("#txtotherlanguage").removeClass("errorfield");
            }
        }
        else if ($("#otherlanguage:checked").val() == undefined && $("#txtotherlanguage").val() != "") {
            $("#spnLanguages").html("Check the 'Other' box");
            $("#spnLanguages").removeClass("nodisplay");
            $("#txtotherlanguage").addClass("errorfield");
            WriterSignupModal.isValid = false;
        }
        else {
            $("#spnLanguages").addClass("nodisplay");
            $("#txtotherlanguage").removeClass("errorfield");
        }

        //        if($("input[name='writerlanguage']:checked").val() == undefined && $("#otherlanguage:checked").val() == undefined)
        //        {
        //            $("#spnLanguages").removeClass("nodisplay");
        //            WriterSignupModal.isValid = false;
        //        }
        //        else
        //            $("#spnLanguages").addClass("nodisplay");

        if ($("#Terms").is(':checked') == false) {
            $("#spnTerms").removeClass("nodisplay");
            $("#Terms").addClass("errorfield");
            WriterSignupModal.isValid = false;
        }
        else
            $("#spnTerms").addClass("nodisplay");

        return WriterSignupModal.isValid;
    }
}

var PopupModal = {
    reSize: function(Height, Width) {
        setTimeout('PopupModal.doreSize(' + Height + ',' + Width + ');', 500);
    },
    doreSize: function(Height, Width) {
        var leftMargin = 0;
        try {
            var left = (parseInt(Width) / 2);
            $("#TB_window").css("margin-left", "-" + left + "px");
            var top = (parseInt(Height) / 2);
            $("#TB_window").css("margin-top", "-" + top + "px");
        } catch (e) { }

        $("#TB_window").css("width", parseInt(Width) + "px");
        $("#TB_ajaxContent").css("width", (parseInt(Width) - 30) + "px");
        $("#TB_ajaxContent").css("height", parseInt(Height) + "px");
    }
}



var CustomAdContestDetailAddImageBox = {
    adgroupId: 0,
    adgroupName: '',

    init: function(adgroupid, adgroupname) {
        this.adgroupId = adgroupid;
        this.adgroupName = adgroupname;
        this.clear();
        $("#lblAdGroupName").text(adgroupname);
    },

    clear: function() {
        $('#txtAdImageNameValidate').addClass("nodisplay");
        $('#txtAdImageNameValidate').attr('value', '');
        $("#txtAdImageFileValidate").addClass("nodisplay");
        $("#txtAdImageFileValidate").attr('value', '');
        $('#txtAdImageDescriptionValidate').addClass("nodisplay");
        $("#txtAdImageDescriptionValidate").attr('value', '');
        $("#txtAdImageFile").attr('value', '');
        $("#txtAdImageName").attr('value', '');
        $("#txtAdImageDescription").attr('value', '');
        $('#message').attr('value', '');
        $("#lblAdGroupName").text('');
    },

    validateFileType: function(file) {
        if (file.indexOf(".gif") > 0) {
            return true;
        }
        if (file.indexOf(".jpg") > 0) {
            return true;
        }
        if (file.indexOf(".jpeg") > 0) {
            return true;
        }
        if (file.indexOf(".jpg") > 0) {
            return true;
        }
        if (file.indexOf(".png") > 0) {
            return true;
        }
        return false;
    },

    addValidate: function() {
        if (this.validate() == false) { return false; }
    },

    validate: function() {

        var file = $("#txtAdImageFile").val();
        if (file.length == 0) {
            $("#txtAdImageFileValidate").text('Please select file before continuing.');
            $('#txtAdImageFileValidate').removeClass("nodisplay");
            return false;
        }

        if (this.validateFileType(file) == false) {
            $("#txtAdImageFileValidate").text('Invalid file type. File must be in gif, jpeg, jpg, or png format.');
            $('#txtAdImageFileValidate').removeClass("nodisplay");
            $("#txtAdImageFile").attr('value', '');
            return false;
        }

        var name = $("#txtAdImageName").val();
        if (name.length == 0) {
            $("#txtAdImageNameValidate").text('Please enter name before continuing.');
            $('#txtAdImageNameValidate').removeClass("nodisplay");
            return false;
        }
        if (name.length > 100) {
            $("#txtAdImageNameValidate").text('Name cannot exceed 100 characters.');
            $('#txtAdImageNameValidate').removeClass("nodisplay");
            $("#txtAdImageName").attr('value', '');
            return false;
        }

        var description = $("#txtAdImageDescription").val();
        if (description.length == 0) {
            $("#txtAdImageDescriptionValidate").text('Please enter description before continuing.');
            $('#txtAdImageDescriptionValidate').removeClass("nodisplay");
            return false;
        }
        if (description.length > 1000) {
            $("#txtAdImageDescriptionValidate").text('Description cannot exceed 1000 characters.');
            $('#txtAdImageDescriptionValidate').removeClass("nodisplay");
            $("#txtAdImageDescription").attr('value', '');
            return false;
        }

        return true;
    }
}


var FBContestDetailAddImageBox = {
    adgroupId: 0,
    adgroupName: '',

    init: function(adgroupid, adgroupname) {
        this.adgroupId = adgroupid;
        this.adgroupName = adgroupname;
        this.clear();
        $("#AddAdGroupImageBatchBox #lblAdGroupName").text(adgroupname);
    },

    clear: function() {
        $('#AddAdGroupImageBatchBox #txtAdImageNameValidate').addClass("nodisplay");
        $('#AddAdGroupImageBatchBox #txtAdImageNameValidate').attr('value', '');
        $("#AddAdGroupImageBatchBox #txtAdImageFileValidate").addClass("nodisplay");
        $("#AddAdGroupImageBatchBox #txtAdImageFileValidate").attr('value', '');
        $('#AddAdGroupImageBatchBox #txtAdImageDescriptionValidate').addClass("nodisplay");
        $("#AddAdGroupImageBatchBox #txtAdImageDescriptionValidate").attr('value', '');
        $("#AddAdGroupImageBatchBox #txtAdImageFile").attr('value', '');
        $("#AddAdGroupImageBatchBox #txtAdImageName").attr('value', '');
        $("#AddAdGroupImageBatchBox #txtAdImageDescription").attr('value', '');
        $('#AddAdGroupImageBatchBox #message').attr('value', '');
        $("#AddAdGroupImageBatchBox #lblAdGroupName").text('');
    },

    validateFileType: function(file) {
        if (file.indexOf(".gif") > 0) {
            return true;
        }
        if (file.indexOf(".jpg") > 0) {
            return true;
        }
        if (file.indexOf(".jpeg") > 0) {
            return true;
        }
        if (file.indexOf(".jpg") > 0) {
            return true;
        }
        if (file.indexOf(".png") > 0) {
            return true;
        }
        return false;
    },

    addValidate: function() {
        if (this.validate() == false) { return false; }
    },

    validate: function() {
        var file = $("#AddAdGroupImageBatchBox #txtAdImageFile").val();
        if (file.length == 0) {
            $("#AddAdGroupImageBatchBox #txtAdImageFileValidate").text('Please select file before continuing.');
            $("#AddAdGroupImageBatchBox #txtAdImageFileValidate").html('Please select file before continuing.');
            $('#AddAdGroupImageBatchBox #txtAdImageFileValidate').removeClass("nodisplay");
            return false;
        }

        if (this.validateFileType(file) == false) {
            $("#AddAdGroupImageBatchBox #txtAdImageFileValidate").text('Invalid file type. File must be in gif, jpeg, jpg, or png format.');
            $('#AddAdGroupImageBatchBox #txtAdImageFileValidate').removeClass("nodisplay");
            $("#AddAdGroupImageBatchBox #txtAdImageFile").attr('value', '');
            return false;
        }

        var name = $("#AddAdGroupImageBatchBox #txtAdImageName").val();
        if (name.length == 0) {
            $("#AddAdGroupImageBatchBox #txtAdImageNameValidate").text('Please enter name before continuing.');
            $('#AddAdGroupImageBatchBox #txtAdImageNameValidate').removeClass("nodisplay");
            return false;
        }
        if (name.length > 100) {
            $("#AddAdGroupImageBatchBox #txtAdImageNameValidate").text('Name cannot exceed 100 characters.');
            $('#AddAdGroupImageBatchBox #txtAdImageNameValidate').removeClass("nodisplay");
            $("#AddAdGroupImageBatchBox #txtAdImageName").attr('value', '');
            return false;
        }

        var description = $("#AddAdGroupImageBatchBox #txtAdImageDescription").val();
        if (description.length == 0) {
            $("#AddAdGroupImageBatchBox #txtAdImageDescriptionValidate").text('Please enter description before continuing.');
            $('#AddAdGroupImageBatchBox #txtAdImageDescriptionValidate').removeClass("nodisplay");
            return false;
        }
        if (description.length > 1000) {
            $("#AddAdGroupImageBatchBox #txtAdImageDescriptionValidate").text('Description cannot exceed 1000 characters.');
            $('#AddAdGroupImageBatchBox #txtAdImageDescriptionValidate').removeClass("nodisplay");
            $("#AddAdGroupImageBatchBox #txtAdImageDescription").attr('value', '');
            return false;
        }

        return true;
    }
}

var ConfigurationModal = {
    init: function() {
        $("#txtMaxRunningAdCount").ForceNumericOnly();
        $("#txtMinimumChampionDifference").ForceNumericOnly();
    },
    submitData: function(adgroupid) {
        if ($("#txtMaxRunningAdCount").length > 0) {
            if ($("#txtMaxRunningAdCount").val() > 20 || $("#txtMaxRunningAdCount").val() < 0) {
                alert("Ads only Accept between 0 to 20.");
                return false;
            }
        }
        var acceptTextAd = $('input[name=AcceptAd]:checked').val();
        var acceptImageAd = $('input[name=AcceptImageAd]:checked').val();
        var MinDiff = ($.trim($("#txtMinimumChampionDifference").val()) == "" ? 0 : $("#txtMinimumChampionDifference").val());
        if (MinDiff >= 0 && MinDiff <= 100) {
            ProcessOverlay.show('dvConfiguration');
            $.post("/Advertiser/SaveConfigurationSetting",
            {
                AdGroupId: adgroupid,
                AcceptTextAd: acceptTextAd,
                AcceptImageAd: acceptImageAd,
                langID: $("#ddlLanguages").val(),
                ContestType: $('input[name=rdContestType]:checked').val(),
                UseMinimumChampionDifference: $('#chkUseMinimumChampionDifference').is(":checked"),
                MinimumChampionDifference: $("#txtMinimumChampionDifference").val(),
                MaxRunningAdCount: ($("#txtMaxRunningAdCount").length > 0 ? $("#txtMaxRunningAdCount").val() : ""),
                AutoActivate: $("#autoActivateCheckBox").attr("checked"),
                MeasuredAction: $('input[name=rdMeasuredAction]:checked').val(),
                LosingChampion: $('input[name=rdLosingChamp]:checked').val()
            },
            function(data) { ConfigurationModal.submitData_callback(data); }, "json");
        } else {
            alert("Minimum Champion Character Difference should between 0 to 100");
            return;
        }
    },
    submitData_callback: function(resp) {
        if (resp == "Success") {
            alert("Your settings were successfully saved");
            if ($('input[name=rdContestType]:checked').val() == "Private") {
                $("#InviteWriterPrivate").removeClass("nodisplay");
            } else
                $("#InviteWriterPrivate").addClass("nodisplay");
			window.location.reload();
        }
        else if (resp.search("75") > 0)
            alert(resp);
        else
            alert("Error while saving your settings.");

        ProcessOverlay.hide('dvConfiguration');
        tb_remove();
    }
}


var StopCurrentContestRound = {
    adtrialid: 0,
    stopContest: function(adTrialId, applyCreditOnChampionLost) {
        StopCurrentContestRound.adtrialid = adTrialId;
        var content = "";
        content += '<div id="Confirm-Stop" class="boostmodalboxcontent round" style="border:solid 2px #d9d9d9; padding:10px; font-size:14px;" align=center>';
        content += '<div class="in-modal" align=left><p class="title" style="text-align:left;">Please confirm</p>';
        content += '<hr />';
        if (applyCreditOnChampionLost.toLowerCase() == "true") {
            content += '<div align=left>In order to stop the contest before a true winner is found, you must purchase each writer ad at the pay-on-approval price of <b>$5</b> per ad.</div><br /><br />';
            content += '<div align=left style="padding-left:10px;"><b>Are you sure you want to stop the current contest round?</b></div><br />';
        } else
            content += '<div align=left style="padding-left:10px;"><b>Are you sure you want to stop the current contest round?</b></div><br /><br /><br />';
        content += '<div style="text-align:center">';
        content += '<a align="center" href="javascript:" class="mOrange-btn" style="display:inline; padding:3px;" onclick="StopCurrentContestRound.confirmStop();">&nbsp;&nbsp;Yes, I want to proceed&nbsp;&nbsp;</a><br /><br />';
        content += '<a align="center" href="javascript:" class="mOrange-btn" style="display:inline; padding:3px;" onclick="BoostModalBox.remove(\'Confirm-Stop\');">&nbsp;&nbsp;Cancel&nbsp;&nbsp;</a><br />';
        content += '</div>';
        content += '</div>';
        $("body").append(content);
        BoostModalBox.showPopupModal('Confirm-Stop', 230, 300);
    },

    confirmStop: function() {
        ProcessOverlay.show('main-block');
        $.post("/Advertiser/StopCurrentContestRound",
            { adTrialId: StopCurrentContestRound.adtrialid },
                function(data) {
                    StopCurrentContestRound.confirmStop_callback(data);
                });
    },

    confirmStop_callback: function(res) {
        if (res != null && res == "success") {
            alert("Current contest round is stopped.");
            window.location.reload();
        } else if (res != null && res == "nocredit")
            alert("You do not have enough credits available in account.\nPlease contact BoostCTR support for more help.");
        else
            alert(res);
        ProcessOverlay.hide('main-block');
        tb_remove();
        window.location.reload();
    }
}
