﻿/// <reference path="jquery-1.2.6-vsdoc.js" />
/// <reference path="common.js" />
/// <reference path="extensions.js" />

$(function() {
    subscribeToGuaranteeManager();
    subscribeToPublisers();
    dataBind(AjaxManager.Guarantee.getAll());
});

//Binds guarantee data to the page
function dataBind(data) {
    if (data.length === 0) {
        return;
    }

    $('#my_account_clean_guarantees').show();
    $('#GuarList').hide();

    for (var j in data) {
        bindGuarantee(data[j]);
        $('#GuarList').appendLine('');
    }

    showRecentOrdersNote();

    $('#GuarList').show();
}

//Called when there is no guarantee infomration avaialable
function bindEmpty() {
    $('#GuarList').empty().append('<p>Currently, there is no record of a One-Year-Clean Guarantee '
    + 'for your account. ' + createLearnMoreLink() + '</p>');
}

//shows disclaimers about when order history/guarantee might appear
function showRecentOrdersNote() {
    if ($.cookie(SESSION_GUID, 'hasRecentOrderUpdate') !== null) {
        $('#recent_order_note').show();
    }
}

//creates the Learn More link for the empty guarantee section
function createLearnMoreLink() {
    var operation = AjaxManager.Operation.getOperation();
    var url = '/Home/CleanGuarantee.aspx';
    var text = 'Click here to learn more';
    var linkId = 'GuaranteeLearnMore';

    if (operation === undefined || operation == null) {
        return hyperlink(url, text, '', linkId);
    } else {
        var id = operation.OperationID;
        var zip = operation.Zip;
        return hyperlink(url + '?zip=' + zip + '&oid=' + id, text, '', linkId);
    }
}

//changes the url of the Learn More link for the current op
var changeQueryString = function(op) {
    try {
        var url = '/Home/CleanGuarantee.aspx';
        $('#GuaranteeLearnMore').attr('href', url + '?zip=' + op.Zip + '&oid=' + op.OperationID);
    } catch (ex) { /* Link may not exist; precautionary try/catch */ }
}

//Binds the information for a single guarantee
function bindGuarantee(guar) {
    $('#GuarList').appendLine('<strong>Location:</strong> ' + guar.Address);
    bindAreas(guar);
    bindLastCleaning(guar);
    bindRemainCleanings(guar);
    bindExpiration(guar);
    bindFollowUpButton(guar);
}

//Binds the areas for a guarantee
function bindAreas(guar) {
    var tb = new table();
    var tr = new row();
    var html = '';
    var KiB = $('#GuarList');

    html += tb.begin();
    for (var i = 0; i < guar.Areas.length; i++) {
        html += tr.begin();

        if (i === 0) {
            html += cell('<strong>Areas:</strong> ');
        } else {
            html += cell();
        }

        html += cell(guar.Areas[i]);
        html += tr.end();
    }
    html += tb.end();

    KiB.append(html);
}

//Binds the last cleaning information
function bindLastCleaning(guar) {
    var dateStr = guar.LastCleaning;
    var date = new Date(parseInt(dateStr.replace(/\D/g, ''), 10));

    if (dateStr != common.getDefaultNullDate()) {
        $('#GuarList').append(div("<strong>Last Cleaning:</strong> "
            + date.toShortDateString(), 'GuarenteeItem'));
    }
}

//Binds the number of cleanings remaining
function bindRemainCleanings(guar) {
    $('#GuarList').append(div('<strong>Remaining Cleanings:</strong> '
        + guar.RemainingCleanings, 'GuarenteeItem'));
}

//Binds the expiration date
function bindExpiration(guar) {
    var dateStr = guar.Expiration;
    var date = new Date(parseInt(dateStr.replace(/\D/g, ''), 10));
    $('#GuarList').append(div("<strong>Expiration Date:</strong> "
        + date.toShortDateString(), 'GuarenteeItem'));
}

//Creates the button used to schedule a follow-up cleaning
function bindFollowUpButton(guar) {
    var isActive = guar.active;
    var buttonID = "guar_" + guar.Id;
    var imageURL;
    var eventHandler;
    var altText;
    var callMessage = $(div());

    if (!guar.IsScheduleAllowed) {
        with (callMessage) {
            append("Call 1-800-STEEMER to schedule the above cleaning.");
            css('margin-top', '5px');
            css('font-size', '10px');
        }

        $('#GuarList').append(callMessage);
        return false;
    }

    if (isActive) {
        imageURL = '/images/button_remove_guarantee.gif';
        altText = 'Remove this guarantee >>';
        eventHandler = function() {
            removeGuarantee(guar.Id);
        }
    }

    else {
        imageURL = '/images/button_followup_cleaning.gif';
        altText = 'Schedule Follow-up Cleaning >>';
        eventHandler = function() {
            scheduleFollowUp(guar.Id);
        }
    }

    $('#GuarList').append(div('<img id="' + buttonID
        + '" alt="' + altText + '" src="' + imageURL + '" />', 'GuarenteeButton'));
    $('#' + buttonID).click(eventHandler);
}

//handles renewing a guarantee when the renew button is clicked
function renewGuarantee(guar) {
    SchedulingTool.addGuaranteeRenewal(guar);
    SchedulingTool.updateTotal();
}

//Change button to a remove selected guarantee button
$.fn.changeToDeactivateButton = function() {
    with (this) {
        var id = attr('id').split('_')[1];
        unbind();
        attr('src', '/images/button_remove_guarantee.gif');
        attr('alt', 'Remove this guarantee >>');
        click(function() {
            removeGuarantee(id);
        });
    }
}

//Calls the scheduling tool to have it add a guarantee
//Changes to guarantee's state to selected
function scheduleFollowUp(id) {
    var selected = AjaxManager.Guarantee.inactive[id];
    var button = $('#guar_' + id);

    AjaxManager.Guarantee.activate(id);
    addGuarantee(selected);
}

//calls the schedule tool and has it add a guarantee
function addGuarantee(guar) {
    var op = AjaxManager.Operation.getOperation();
    var terr = AjaxManager.Territory.getTerritory();
    var onRenewal;
    var onNoRenewal;

    if (op === null || op === undefined) {
        onRenewal = function() {
            AjaxManager.Guarantee.active[guar.Id].isRenewed = true;
            AjaxManager.Guarantee.save();
            SchedulingTool.setZipCodeBox(guar.Zip);
            SchedulingTool.changeLocation(guar.Zip, null);
        }
        onNoRenewal = function() {
            SchedulingTool.setZipCodeBox(guar.Zip);
            SchedulingTool.changeLocation(guar.Zip, null);
        }
    } else if (terr.Zip === guar.Zip) {
        onRenewal = function() {
            SchedulingTool.setZipCodeBox(guar.Zip);
            SchedulingTool.addGuarantee(guar, false, true);
        }
        onNoRenewal = function() {
            AjaxManager.Guarantee.active[guar.Id].isRenewed = false;
            AjaxManager.Guarantee.save();
            SchedulingTool.setZipCodeBox(guar.Zip);
            SchedulingTool.addGuarantee(guar, false, false);
        }
    } else {
        onRenewal = function() {
            AjaxManager.Guarantee.active[guar.Id].isRenewed = true;
            AjaxManager.Guarantee.save();
            showGuaranteeZipWarning(guar);
        }
        onNoRenewal = function() {
            showGuaranteeZipWarning(guar);
        }
    }

    checkRenewal(guar, onRenewal, onNoRenewal);
}

//checks to see if a guarantee is up for renewal
//prompts the user to renew if it is
function checkRenewal(guar, onRenewal, onNoRenewal) {
    if (guar.RemainingCleanings == 1) {
        createRenewDialog(onRenewal, onNoRenewal);
    } else {
        onNoRenewal();
    }
}

//creates a dialog that prompts the user to renew their guarantee
//accepts functions for affirmative and negative actions
function createRenewDialog(onRenewal, onNoRenewal) {
    var box = $(div('', '', 'renewalDialog'));
    var buttons = $(div());
    var buttonOk = $('<img alt="Renew" src="/images/button_renew.gif" />');
    var buttonNo = $('<a href="#">No Thanks</a>');

    buttonOk.css('cursor', 'pointer');
    buttonOk.click(function() {
        $('#renewalDialog').dialog('destroy');
        $('#renewalDialog').remove();
        onRenewal();
    });

    buttonNo.css('padding-bottom', '5px');
    buttonNo.click(function() {
        $('#renewalDialog').dialog('destroy');
        $('#renewalDialog').remove();
        onNoRenewal();
        return false;
    });

    with (buttons) {
        append(buttonOk);
        append('&nbsp;&nbsp;');
        append(buttonNo);
        css('text-align', 'center');
    }

    box.append('<p style="padding-bottom:5px">This is your third follow-up cleaning.  Renew today to keep saving with your '
        + 'One-Year-Clean Guarantee.  <a href="/Home/CleanGuarantee/Renewal.aspx">Read More</a>');
    box.append(buttons);
    box.dialog({
        modal: true,
        resizable: false
    });
}

//shows a warnging when the user tries to use a guarantee outside the current zip
//ok - deletes order, changes zip, and adds guarantee
//cancel - cancels the current action
function showGuaranteeZipWarning(guar) {
    var error = $('<div></div>');
    var buttons = $('<div style="text-align: right; margin-top:10px"></div>');
    var ok = $('<a href="#">OK</a>');
    var cancel = $('<a href="#">CANCEL</a>');

    ok.click(function() {
        SchedulingTool.setZipCodeBox(guar.Zip);
        SchedulingTool.changeLocation(guar.Zip, null);
        error.dialog('destroy');
    });

    cancel.click(function() {
        AjaxManager.Guarantee.deactivate(guar.Id);
        error.dialog('destroy');
    });

    with (error) {
        append('The cleaning you are about to schedule is outsite the currently selected ZIP Code.<br />');
        append('<br />Continuing will delete any order that you have currently started.  Continue?');
        with (buttons) {
            append(cancel);
            append('&nbsp;&nbsp;&nbsp;');
            append(ok);
        }
        append(buttons);
        dialog({
            modal: true,
            resizable: false
        });
    }
}

//changes button to an add this special type state
$.fn.changeToActivateButton = function() {
    with (this) {
        var id = attr('id').split('_')[1];
        unbind();
        attr('src', '/images/button_followup_cleaning.gif');
        attr('alt', 'Schedule Follow-up Cleaning >>');
        click(function() {
            scheduleFollowUp(id);
        });
    }
}

//calls the scheduling tool to have it remove a guarantee
//changes the guarantee's state to selectable
function removeGuarantee(id) {
    var button = $('#guar_' + id);
    var renewalButton = $('#guar_renewal_' + id);
    var guar = AjaxManager.Guarantee.active[id];

    if (renewalButton.length > 0) {
        renewalButton.unbind();
        renewalButton.click(function() {
            renewGuarantee(guar);
            $(this).unbind();
            $(this).click(function() {
                toggleRenewal(guar);
            });
        });
    }

    AjaxManager.Guarantee.deactivate(id);
    SchedulingTool.removeGuarantee(id);
}

//subscribes to the activation/desactivation of guarantees
//changes the button images and handlers accordingly
function subscribeToGuaranteeManager() {
    var onAct = function handleActivation(id) {
        var button = $('#guar_' + id);
        button.changeToDeactivateButton();
        disableUnusableGuarantees();
    }

    var onDeact = function handleDeactivation(id) {
        var button = $('#guar_' + id);
        button.changeToActivateButton();
        disableUnusableGuarantees();
    }

    onAct.subscribe(AjaxManager.Guarantee.onActivation);
    onDeact.subscribe(AjaxManager.Guarantee.onDeactivation);
}

//disables guarantees that can not be used with the currently selected one
function disableUnusableGuarantees() {
    var active = AjaxManager.Guarantee.active;
    var inactive = AjaxManager.Guarantee.inactive;
    var cusomterId = 0;

    for (var i in active) {
        var cusomterId = active[i].CustomerID;
    }

    if (cusomterId == 0) {
        enableAllGuarantees();
    } else {
        for (var x in inactive) {
            if (inactive[x].CustomerID !== cusomterId) {
                disableGuarantee(inactive[x].Id);
            }
        }
    }
}

//subscribe to misc publishers
function subscribeToPublisers() {
    changeQueryString.subscribe(AjaxManager.Operation.onOperationChanged);
}

//hides the add button on a guarantee
function disableGuarantee(Id) {
    var button = $('#guar_' + Id);
    button.parent().hide();
}

//shows the hide on a guarantee
function enableAllGuarantees() {
    $('.GuarenteeButton').show();
}