﻿/// <reference path="jquery-1.2.6-vsdoc.js" />

var specials = [];
var priceBook = [];
var slidePanel_contentWidth;
var isGoClicked = false;

function isSpecialsPage() {
    return $('#specials_container_page').css('display') != undefined;
}

function getSpecialsForPage() {
    $('#specials_zip_code_form').append("<img id='ffbz_wait_image' src='/Images/wait.gif' style='height: 22px; width: 22px; vertical-align:bottom;' />");

    $('#specials_go').unbind();
    var zipCode = $('#specials_zip_code').val();

    try {
        $('#zip_code').val(zipCode);
    } catch (ex) {
        // do nothing
    }

    var ci = loadCleaningInfo();
    ci.ZipCode = zipCode;
    ci.Save();

    AjaxManager.Territory.changeZipCode(zipCode);
}

function buildSpecialsFranchiseListing(response) {
    var fl = $('#franchise_list').clone();
    $(fl).attr('id', 'specials_franchise_list');
    $(fl).empty();
    $(fl).click(specialsFranchiseOkClick);
    for (var t in response) {
        /*
        PARSE FORMAT
        City_County_OperationID_State_TerritoryDescription_TerritoryID_Zip_ZoneCode___type
        spaces in names will be replaced with '-'
        */
        var id = response[t].City + "_" + response[t].County + "_" + response[t].OperationID + "_" + response[t].State + "_" + response[t].TerritoryDescription + "_" + response[t].TerritoryID + "_" + response[t].Zip + "_" + response[t].ZoneCode + "_" + response[t].__type;

        id = id.replace(/ /g, '-');

        $(fl).append('<div class="franchise">' + '<input type="radio" class="franchise_select" name="franchise" id="' + id + '"/>' + '<span class="franchise_location">' + response[t].City + ', ' + response[t].State + ' ' + response[t].Zip + '</span><br />' + '<span class="franchise_description">' + response[t].TerritoryDescription + '</span>' + '</div>');
    }

    if (isSpecialsPage()) {
        var x = $('#specials_zip_code_form').position().left;
        var y = $('#specials_zip_code_form').position().top;

        $('#specials_zip_code_form').parent().append($(fl));

        $(fl).css({
            'top': y + 'px',
            'left': x + 'px'
        });

        $(fl).fadeIn('slow');
    }
}

function clearSpecialContainerDivs() {
    var d = $('.specials_items_container');
    var f = $('.pricebook_items_container');

    if (d !== null) {
        d.remove();
    }

    if (f !== null) {
        f.remove();
    }
}
function showNoneAvailableMessage() {
    clearSpecialContainerDivs();
    hideSpecialsButton();

    var specials_html = "<div class='specials_items_container'>";
    specials_html += specialsNotAvailableMessage();
    specials_html += "</div>";

    var priceBook_html = "<div class='pricebook_items_container'>";
    priceBook_html += priceBookCallForInfoMessage();
    priceBook_html += "</div>";

    if (isSpecialsPage()) {
        $('#specials_form').hide();
        $('#specials_page_content img').show();
        $('#specials_content').append(specials_html);
        $('#pricebook_content').append(priceBook_html);
    }

    $('#slideout_panel_content').append(specials_html);
}

function showSpecialsError() {
    if (isSpecialsPage()) {
        var top = $('#specials_form').position().top;
        var left = $('#specials_form').position().left;
        var width = $('#specials_form').width();
        var height = window.screen.height;

        try {
            $('.quote_wait_div').eq(0).fadeOut().remove();
        } catch (ex) { }

        $('#disable_panel').css({
            'top': top + 'px',
            'left': left + 'px',
            'height': height + 'px',
            'width': width + 'px'
        });

        $('#disable_panel').show();
        $('#disable_panel').after('<div class="warning" id="web_service_warning">' +
					'<div class="warning_text">' +
					'Sorry for the inconvenience, but we\'re experiencing technical issues at this moment. Please try again in a few minutes. If the problem persists please contact us at 1-800-STEEMER.' +
					'<span style="cursor:pointer;" id="web_service_warning_ok" class="warning_dismiss"><u>OK</u></span>' +
					'</div></div>');
        $('#format_warning').css('top', $('#specials_form').position().top)
							.css('left', $('#specials_form').position().left);

        //popup handler
        $('#web_service_warning_ok').click(function() {
            $('#web_service_warning').remove();
            $('#disable_panel').hide();
        });

        $('#ffbz_wait_image').fadeOut();
    }
}

function getSpecialsForTerritory() {
    var territoryManager = AjaxManager.Territory || {};
    var territory = territoryManager.getTerritory();
    var j_territory = JSON.stringify({ Territory: territory });

    $.ajax({
        url: '/Service.asmx/GetSpecialsAndPricingForTerritory',
        type: 'POST',
        datatype: 'json',
        data: j_territory,
        timeout: 10000,
        contentType: 'application/json; charset=utf-8',
        success: getSpecialsForTerritorySuccess,
        error: showSpecialsError
    });
}

function specialsFranchiseOkClick() {
    var id = $('.franchise_select:checked').attr('id');
    $('#specials_franchise_list').fadeOut('slow');

    var data = id.replace(/-/g, ' ').split('_');

    var terr = {
        City: data[0],
        County: data[1],
        OperationID: parseInt(data[2], 10),
        State: data[3],
        TerritoryDescription: data[4],
        TerritoryID: parseInt(data[5], 10),
        Zip: data[6],
        ZoneCode: data[7],
        __type: data[8]
    }

    var territoryManager = AjaxManager.Territory || {};
    territoryManager.setTerritory(terr);
}

function getSpecialsForTerritorySuccess(json) {
    $('.landing_content_container').css({ 'height': '' });


    var rVal = true;
    var selected_specialID;

    clearSpecialContainerDivs();

    specialsAndPricing = JSON.parse(json);
    specials = specialsAndPricing.Offers;
    priceBook = specialsAndPricing.PriceBook;
    var operation = cache.getItem('Operation');
    var isPricebookVisible = false;
    if (operation !== null && operation !== undefined) {
        isPricebookVisible = operation.IsPricebookVisible;
    }

    var specials_html = "<div class='specials_items_container'>";
    var priceBook_html = "<div class='pricebook_items_container'>";

    if (specials.length == 0) {
        specials_html += specialsNotAvailableMessage();
        specials_html += "</div>";
        hideSpecialsButton();
        rVal = false;
    } else {
        if (operation.DoesGuaranteeOnline) {
            specials_html += createGuaranteeSpecialLink();
        }

        ci = loadCleaningInfo();
        selected_specialID = (ci !== null) ? ci.SpecialID : ci;

        for (var i in specials) {
            if (specials[i].Title === undefined) {
                specials[i].Title = '';
            }

            specials_html += createSpecial(specials[i], selected_specialID);
        }

        specials_html += "</div>";
    }

    pb = createPriceBook(priceBook);
    if (pb.length === 0) {
        if (isPricebookVisible) {
            priceBook_html += priceBookUseQuoteToolMessage();
        } else {
            priceBook_html += priceBookCallForInfoMessage();
        }

        priceBook_html += "</div>";
        $('#view_price_list').hide();
    } else {
        if (isPricebookVisible) {
            priceBook_html += pb;
            priceBook_html += "</div>";
            $('#view_price_list').show();
        } else {
            $('#view_price_list').hide();
            priceBook_html += priceBookUseQuoteToolMessage();
        }
    }

    if (isSpecialsPage()) {
        $('#specials_form').hide();
        $('#specials_page_content img').show();
        $('#specials_content').append(specials_html);
        $('#pricebook_content').append(priceBook_html);
    }

    $('#slideout_panel_content').append(specials_html);

    if (AjaxManager.Estimate.isGuaranteed) {
        $('.specials_items_container').hide();
    }

    $('#specials_content .specials_items_container > div:first').css('padding-top', '0');

    $("A:contains('SCHEDULE ONLINE USING THIS SPECIAL')").each(function() {
        $(this).bind('click', chooseSpecial);
    });

    if (selected_specialID !== undefined && selected_specialID !== null) {
        $('a[id*="special_' + selected_specialID + '"]').eq(0).click();
    }

    $("A:contains('DISCLAIMER')").bind('click', toggleDisclaimer);

    $('#slideout_panel_content *').each(function() {
        if ($(this).attr('id').length > 0) {
            $(this).attr('id', $(this).attr('id') + '_slideout');
        }
    });

    $('.pricebook_header').click(function() {
        if ($(this).next().css('display') == 'none') {
            $('.jq_open').slideUp(600).removeClass('jq_open');
            $(this).next().slideDown(600).addClass('jq_open');
        } else {
            $('.jq_open').slideUp(600).removeClass('jq_open');
        }
    })

    $('.pricebook_items_container').find('div:first').click();

    if ($.browser.msie && $('.landing_content_container').height() < 650) {
        $('.landing_content_container').height(650);
    } else if ($('.landing_content_container').height() < 610) {
        $('.landing_content_container').height(610);
    }

    try {
        resizeSidebar();
    } catch (x) {
        // FAIL!!
    }

    if (rVal) {
        positionViewSpecialsButton();
    }

    return rVal;
}

function specialsNotAvailableMessage() {
    return "<span class='specials_pricing_none'>There are currently no specials available in your area.</span>";
}

function priceBookCallForInfoMessage() {
    var s = "<span class='specials_pricing_none'>We're sorry...Online pricing is not currently available in your area.</span>";
    s += "<p>Please call 1-800-STEEMER to speak directly to your local Stanley Steemer Customer Service Representative.</p>";

    return s;
}

function priceBookUseQuoteToolMessage() {
    var s = "<span class='specials_pricing_none'>Looking to price service in your area?</span>";
    s += "<p>Get a real-time price quote. Complete the No Obligation Quote on the left.</p>";

    return s;
}

function createGuaranteeSpecialLink() {
    op = AjaxManager.Operation.getOperation();

    return '<div style="margin-top:5px;border-bottom:3px dotted #FFCC33;margin-bottom:3px;padding-bottom:5px"><strong>One-Year Clean Guarantee </strong> ' +
        '<a href="/Home/CleanGuarantee.aspx?zip=' + op.Zip + '&oid=' + op.OperationID + '">LEARN MORE</a></div>';
}

function createSpecial(special, selected_specialID) {
    var s = '<div id="special_' + special.OfferID + '_container" class="special_' + special.OfferID + '_container ';

    if (selected_specialID !== null && selected_specialID === special.OfferID) {
        s += 'selected_special_offer_list_item">';
    }
    else {
        s += 'special_offer_list_item">';
    }

    s += '<div><span class="selected_special_tag">(Selected Special)</span><span class="coupon_offer">' + special.Title + '</span> ';
    s += special.Description + '</div>';
    s += '<p class="special_schedule_online"><a id="special_' + special.OfferID + '">SCHEDULE ONLINE USING THIS SPECIAL</a></p>';
    s += '<div id="view_specials_disclaimer_container">';
    s += '<a id="special_' + special.OfferID + '_anchor">VIEW DISCLAIMER</a>';
    s += '<div  id="specials_disclaimer_' + special.OfferID + '_container"  style="display:none;" class="coupon_disclaimer">';
    s += special.OfferDisclaimer;
    s += '</div>';
    s += '</div>';
    s += '</div>';

    return s;
}

function createPriceBook(priceBook) {
    var s = '';
    for (var i in priceBook) {
        if (priceBook[i].Details.length === 0) {
            continue;
        }

        s += '<div class="pricebook_header">' + priceBook[i].Description.toUpperCase() + ' CLEANING</div>';
        s += '<div style="display:none;">';
        s += '<table class="pricing_info">';
        s += '<tbody>' + createPriceBookDetails(priceBook[i].Details) + '</tbody>';
        s += '</table>'
        s += '</div>';
    }

    return s;
}

function createPriceBookDetails(priceBookDetails) {
    var s = '';
    for (var i in priceBookDetails) {
        s += '<tr>'
        s += '<td>' + priceBookDetails[i].Description + '</td>';
        s += '<td align="right">' + priceBookDetails[i].CleaningPrice.toFixed(2) + '</td>';
        s += '</tr>';
    }

    return s;
}

function chooseSpecial() {
    var special = $(this).parent().parent().clone();
    var dom_id = $(this).attr('id');
    var pos = dom_id.split('_')[1]; // pos is also the OfferID of the special

    for (var i in specials) {
        if (specials[i].OfferID == pos) {
            $.cookie(SESSION_GUID, 'current_special', JSON.stringify(specials[i]), { path: '/' });
        }
    }

    $('.selected_special_offer_list_item').toggleClass('selected_special_offer_list_item')
		.addClass('special_offer_list_item');

    $('.special_' + pos + '_container').toggleClass('selected_special_offer_list_item');

    $(special).find('*').each(function() {
        if ($(this).attr('id').length > 0) {
            $(this).attr('id', $(this).attr('id') + '_coupon');
        }
    });

    var chosen_special = $(special);

    var contents = $(special).html();

    var currentCI = loadCleaningInfo();
    if (currentCI.SpecialID == pos) {
        if (currentCI.SpecialHTML === null || currentCI.SpecialHTML.length === 0) {
            currentCI.SpecialHTML = contents;
            currentCI.Save();
        }

        setCouponText(currentCI);
        hideSlideoutPanel();
        return false;
    }

    var ci = new CleaningInfo(document, 'saved_quote');
    ci.Load();

    ci.SpecialID = pos;
    ci.SpecialHTML = contents;
    var zip_code = $.cookie(SESSION_GUID, 'zip_code');

    if (zip_code) {
        ci.ZipCode = zip_code;
    }

    ci.Save();

    setCouponText(ci);
    AjaxManager.Discount.setActiveDiscountType('SPECIAL');
    hideSlideoutPanel();
    updateTotal();

}

function setCouponText(cleaningInfo) {
    if (!(cleaningInfo.hasOwnProperty("SpecialHTML")) || cleaningInfo === null || cleaningInfo === undefined) {
        var ci = new CleaningInfo(document, 'saved_quote');
        ci.Load();
        cleaningInfo = ci;
    }

    if (cleaningInfo.SpecialHTML != null) {
        var id = $('.coupon a').eq(0).attr('id');

        if (id !== undefined && id.search(cleaningInfo.SpecialID) > -1) {
            //don't reset the coupon text if set to the selected one already.
            return false;
        }

        $('.coupon').empty();
        $('.coupon').append(cleaningInfo.SpecialHTML);
        $('.coupon a').eq(0).hide();
        $('.coupon a').eq(2).show();

        if ($('#schedule_now').is(':visible')) {
            $('.coupon').find("a:contains('DISCLAIMER')").bind('click', toggleDisclaimer).after(' &nbsp &nbsp<a href="#" id="remove_special">REMOVE SPECIAL</a>');
            $('.coupon').find("a:contains('REMOVE')").bind('click', removeSpecial);
        } else {
            $('.coupon').find("a:contains('DISCLAIMER')").bind('click', toggleDisclaimer);
        }


        $('.coupon').show();
    } else {
        $('.coupon').empty().hide();
    }
}

function removeSpecial(update) {
    var ci = new CleaningInfo(document, 'saved_quote');
    ci.Load();
    ci.SpecialID = null;
    ci.SpecialHTML = null;
    ci.Save();

    $.cookie(SESSION_GUID, 'current_special', null, { async: false });

    $('.coupon').empty().hide();
    $('.selected_special_offer_list_item').toggleClass('selected_special_offer_list_item')
		.addClass('special_offer_list_item');
    AjaxManager.Discount.setActiveDiscountType('NONE');

    if (update !== false) {
        updateTotal();
    }
    return false;
}

function toggleDisclaimer() {
    var d = $(this).next('div');
    if (d.length === 0) {
        //account for the remove special link
        d = $(this).next('a').next('div');
    }

    if ($(d).css('display') === 'none') {
        $(this).text('HIDE DISCLAIMER');
        $(d).show('blind', {}, 'slow');
    } else {
        $(this).text('VIEW DISCLAIMER');
        $(d).hide('blind', {}, 'slow');
    }
    return false;
}

function autoShowSlideoutPanel() {
    if (!(isSpecialsPage()) && isGoClicked && $('.specials_items_container div').length > 0) {
        showSlideoutPanel();
    }
    isGoClicked = false;
}

function showSlideoutPanel() {
    if ($('#zip_code').val().search(/^(\d{5}-\d{4})|(\d{5})$/) == -1) {
        $('#zip_warning_text').empty()
		.append('This zip code is not valid');
        $('#zip_warning').fadeIn('slow');
        $('#zip_wait').fadeOut();
        return false;
    }

    $('#view_specials_open').unbind('click', showSlideoutPanel);

    l = $('#view_specials_open').position().left + $('#view_specials_open').width();
    t = $('#schedule_section').position().top;

    $('.slideout_panel').css({
        'left': (l + 'px'),
        'top': (t + 'px'),
        'height': (($('#schedule_section').height() + 4) + 'px')
    })

    $("#schedule_section > div[class='top']").toggleClass('top-noBackground').toggleClass('top');
    $('.tab-bg').toggleClass('tab-bg-noBackground').toggleClass('tab-bg');

    h = $('.slideout_panel').height();
    h2 = $('#slideout_panel_top').height() + $('#slideout_panel_header').height();

    $('#slideout_panel_content').css({
        'height': (h - h2) + 'px'
    });

    $('.slideout_panel').show("blind", { direction: "horizontal" }, 'slow', function() {
        $('#view_specials_open').bind('click', hideSlideoutPanel)
			.attr('src', '/Images/Hide_Specials_Button.gif');
        if (slidePanel_contentWidth === undefined) {
            /* get the content width only the first time to prevent growing each time you show it */
            slidePanel_contentWidth = $('.slideout_panel').width();
        }

        $('#slideout_panel_top').css({
            'width': slidePanel_contentWidth + 'px'
        });

        $('#slideout_panel_top_left').css({
            'width': (slidePanel_contentWidth - $('#slideout_panel_top_right').width()) + 'px'
        });

        $('#slideout_panel_shadow_box .slideout_panel_shadow').css({
            'top': $('#slideout_panel_header').position().top + 'px',
            'height': ($('#slideout_panel_header').height() + $('#slideout_panel_content').height() - 4) + 'px'
        });

        $('#slideout_panel_top .slideout_panel_shadow').css({
            'top': ($('#slideout_panel_top').position().top) + 'px',
            'height': $('#slideout_panel_top').height() + 'px'
        });

        $(document).bind('click', closeSlideoutPanelOnClick);
    });
}

function hideSlideoutPanel() {
    if ($('.slideout_panel').css('display') !== 'block') {
        return;
    }

    $('#view_specials_open').unbind('click', hideSlideoutPanel);
    $(document).unbind('click', closeSlideoutPanelOnClick);

    $('.slideout_panel').hide("blind", { direction: "horizontal" }, 'slow', function() {
        $('#view_specials_open').bind('click', showSlideoutPanel)
			.attr('src', '/Images/View_Specials_Button.gif');
        $("#schedule_section > div[class='top-noBackground']").toggleClass('top').toggleClass('top-noBackground');
        $('.tab-bg-noBackground').toggleClass('tab-bg').toggleClass('tab-bg-noBackground');
    });

    $('#slideout_panel_drop_shadow').remove();
}

function closeSlideoutPanelOnClick(e) {
    if ($(e.target).parents('.slideout_panel').length == 0) {
        hideSlideoutPanel();
        return;
    }
}
function hideSpecialsButton() {
    $('#view_specials').hide();
    $('#view_specials_open').hide();
}

function positionViewSpecialsButton() {
    if ($('#zip_entry .go').css('display') === 'none') {
        hideSpecialsButton();
    } else if ($('#view_specials_open').css('display') === 'none') {

        $('#view_specials').css('height', '0');
        $('#view_specials').show();
        var left_original = $('#view_specials').position().left; ;

        //need to show the button to be able to determine image width;
        $('#view_specials').css('left', '-9999px');
        $('#view_specials_open').css('left', '-9999px');
        $('#view_specials_open').show();

        l = $('#create_quote').position().left;
        w = $('#create_quote').width();

        t2 = $('#view_specials_open').position().top;
        w2 = $('#view_specials_open').width();

        $('#view_specials').hide();
        $('#view_specials_open').hide();

        $('#view_specials_open').css({
            'position': 'absolute',
            'left': ((w - w2) + 'px'),
            'z-index': '2050'
        });

        $('#view_specials').css({
            'left': left_original + 'px',
            'height': '20px'
        });

        $('#view_specials').slideDown('fast', function() {
            $('#view_specials_open').fadeIn(function() {
                autoShowSlideoutPanel();
            });
        });
    } else if ($('#view_specials_open').css('display') === 'inline') {
        autoShowSlideoutPanel()
    }
}

$(document).ready(function() {
    $('#view_specials').hide();

    $('#zip_entry .go').bind('mouseup', function() { isGoClicked = true; });
    $('#zip_code').bind('keypress', function(event) {
        var charCode = event.which ? event.which : event.keyCode;
        if (charCode === 13) {
            isGoClicked = true;
        }
    });

    $('#view_specials_open').bind('click', showSlideoutPanel);
    $('#view_price_list').bind('click', function() { parent.location = "/Home/Specials.aspx"; });
    $('#close_specials').bind('click', hideSlideoutPanel);

    specialsSubscribeToPublishers();

    if (isSpecialsPage()) {
        $('.landing_content_container').addClass('specials_content');
        $('.landing_content_container *').css('background-color', 'transparent');

        $('#specials_go').bind('click', function() {
            specialsPageSubscribeToPublishersOnGoClick();
            getSpecialsForPage()
        });

        if ($.cookie(SESSION_GUID, 'zip_code')) {
            $('#specials_zip_code').val($.cookie(SESSION_GUID, 'zip_code'));
        }

        $('#specials_zip_code').keydown(function(event) {
            var charCode = event.which ? event.which : event.keyCode;
            if (charCode === 13) {
                $('#specials_go').click();
                return false;
            }
        });
    }
});

//subscribe to certain publishers only when the specials page go button is clicked.
function specialsPageSubscribeToPublishersOnGoClick() {
    var t = AjaxManager.Territory;
    getSpecialsForTerritory.subscribe(t.onTerritoryChanged);
    showNoneAvailableMessage.subscribe(t.onNoTerritoryFound);
    buildSpecialsFranchiseListing.subscribe(t.onMultipleTerritoriesFound);

    //unsubscribe to this since we know want to react when the Quote Tool also updates.
    getSpecialsForTerritory.unsubscribe(AjaxManager.AreasAndServices.onAreasAndServicesChanged);
    specialsPageUnubscribeToPublishersAfterGoClick.subscribe(AjaxManager.AreasAndServices.onComplete);
}

//unsubscribe so we only respond when the go button on specials page is clicked.
function specialsPageUnubscribeToPublishersAfterGoClick() {
    var t = AjaxManager.Territory;
    getSpecialsForTerritory.unsubscribe(t.onTerritoryChanged);
    showNoneAvailableMessage.unsubscribe(t.onNoTerritoryFound);
    buildSpecialsFranchiseListing.unsubscribe(t.onMultipleTerritoriesFound);

    //the specials page is done responding to its go click so we can listen for the Quote Tool to update again.
    var a = AjaxManager.AreasAndServices;
    getSpecialsForTerritory.subscribe(a.onAreasAndServicesChanged);
    specialsPageUnubscribeToPublishersAfterGoClick.unsubscribe(a.onComplete);
}

//subscribe to certain publishers so the page can respond when the quote control zip is changed.
function specialsSubscribeToPublishers() {
    var territory = AjaxManager.Territory;
    showSpecialsError.subscribe(territory.onError);
    //removeSpecial.subscribe(AjaxManager.Estimate.onOrderGuaranteed);

    var inSchedule = common.inSchedule();
    if (inSchedule) {
        setCouponText.subscribe(AjaxManager.AreasAndServices.onAreasAndServicesChanged);
    } else {
        getSpecialsForTerritory.subscribe(AjaxManager.AreasAndServices.onAreasAndServicesChanged);
    }
}



