﻿/// <reference path="jquery-1.2.6-vsdoc.js" />
/// <reference path="Publisher.js" />
/// <referemce path="exentions.js" />

/* ---- CLEARSALEING CONVERSION VARIABLES ---- */
var csTrackURL = "https://dsa.csdata1.com/data/sample.jpeg?";
var csAccountID = "5170365";
var csGenShoppingCartData;
var csSalesStageCode;
var csOrderType;
var csOrderNum;
var csCustomerRating;
var csPostalCode;
var csOrderSubTotal;
var csTax;
var csOrderTotal;
var csIds;
var csCodes;
var csItems;
var csPrice;
var csQtys;
var csCity;
var csState;
/* ------------------------------------------- */

var LINE_ITEM = 'line_item';
var SUBTOTAL = 'line_item_sub_total';
var TOTAL = 'line_item_totals';
var EMPTY_OPTION = '<option value="NA">Please enter a zip code</option>';
var minimum_order_message = 0;
var mimimum_order_message_status = 'show';
var carpetMin = 0;
var carpetMax = 12;
var leatherMin = 0;
var leatherMax = 12;
var autoMin = 0;
var autoMax = 12;
var tileMin = 0;
var tileMax = 12;
var ductMin = 0;
var ductMax = 25;

$(document).ready(function() {
    quoteControlSubscribeToPublishers();
    //Hide pre-hidden elements

    //TODO: move the initial hides to style sheet, or inline styles
    //      this will prevent anything from popping in and then out
    $('#franchise_selection').hide();
    $('#disable_panel').hide();
    $('#min_price_warning').hide();
    $('#requires_portable').hide();
    $('#current_room_selection').hide();
    $('#current_furniture_selection').hide();
    $('#current_automobile_selection').hide();
    $('#current_leather_selection').hide();
    $('#current_duct_selection').hide();
    $('#current_tile_selection').hide();
    $('#duct_tab').hide();
    $('#tile_tab').hide();
    $('#call_tab').hide();
    $('#carpet_tab').show();
    $('#format_warning').hide();
    $('#zip_warning').hide();
    $('#zip_change_warning').hide();
    $('#disclaimer_detail').hide();
    $('#portable_disclaimer').hide();
    $('.portable_disclaimer_generic').show();
    $('.portable_disclaimer_minimum').hide();
    $('.portable_disclaimer_surcharge').hide();
    $('#dryer_yes').click(function() {
        updateTotal();
        return true; //allows the checkbox check to show up/hide since updateTotal() could return false
    });
    $('#HVAC_num').change(updateTotal);
    $('#view_disclaimer_container').hide();
    //$('.a_tab').after('');

    $('.slideout_panel_guarantee_disclaimer_link').click(function() {
        var disclaimer = $('.slideout_panel_guarantee_disclaimer');

        if (disclaimer.css('display') === 'none') {
            disclaimer.slideDown();
        } else {
            disclaimer.slideUp();
        }

        return false;
    });

    if ($.cookie(SESSION_GUID, 'saved_quote') === null || JSON.parse($.cookie(SESSION_GUID, 'saved_quote')).ZipCode === null) {
        $('#total_cost_items').hide();
        $('#add_services').hide();
        $('#schedule_now').css('border-top', '0px');
    }

    $("#min_price_warning").css({ border: "solid thin #FF0000",
        marginTop: "5px",
        marginBottom: "10px",
        padding: "7px",
        width: "260px",
        color: "#FF0000",
        fontWeight: "bold",
        background: "#FFFFCC",
        position: "absolute"
    });

    //determine browser and set spacing for <hr> px 5px 15px 0px
    if ($.browser.msie && $.browser.version.search(/8.*/) == -1) {
        $('#schedule_section hr').css('margin-top', '2px')
		.css('margin-bottom', '2px')
		.css('margin-left', '0px')
		.css('width', '275px');
        $('#tab_content').css('margin', '10px 5px 3px 0px');
    } else {
        $('#schedule_section hr').css('margin-top', '10px')
		.css('margin-bottom', '10px')
		.css('margin-left', '0px')
		.css('width', '275px');
        $('#tab_content').css('margin', '10px 5px 10px 0px');
    }

    //Register Event handlers
    $('#zip_code').keypress(function(event) {
        var charCode = event.which ? event.which : event.keyCode;
        if (charCode === 13) {
            $('.go').click();
            return false;
        }
    });

    $('#clear_quote').click(clearQuote);

    $('.selection_option').each(function() {
        $(this).selectbox();
    });

    $('.jquery-selectbox-list').each(function() {
        $(this).css('height', '');
    });

    //schedule now
    $('#schedule_now').click(scheduleNow);

    //input change
    $(".num").change(updateTotal);

    //hardwood estimate checkbox
    $('#HardwoodEstimate').click(function() {
        var ci = loadCleaningInfo();
        ci.HardwoodEstimate = !ci.HardwoodEstimate;
        ci.Save();
        updateTotal();
    });

    //tab click
    $('#schedule_tabs UL LI').each(function() {
        $(this).bind("click", tabControl);
    });

    //portable disclaimer show/hide
    $(".portable").click(function() {
        //if the yes button is clicked, show the disclamier.
        //if not, then hide the disclaimer
        if ($("#portableY").attr("checked") === true) {
            $('#portable_disclaimer').slideDown();
        } else {
            $('#portable_disclaimer').slideUp();
        }
        //update the total accordingly
        updateTotal();
    });

    //go button click
    $('.go').bind('click', function() {
        var zip = $('#zip_code').val();
        var old_zip_code = $.cookie(SESSION_GUID, 'zip_code');
        if ((old_zip_code === null || old_zip_code !== zip)) {
            onFoundMultipleTerritories.subscribe(AjaxManager.Territory.onMultipleTerritoriesFound);
            getZipCode();
        }
    });

    $('#add_tile_link').click(function() {
        $('.t_tab').click();
        return false;
    });

    $('#add_carpet_link').click(function() {
        $('.c_tab').click();
        return false;
    });

    //hides the zip code error warning
    $('#zip_warning_ok').click(function() {
        $('#zip_warning').fadeOut('slow');
        $('#zip_code').val('');
    });
    $('#franchise_ok').click(franchiseOkClick);

    $('#view_disclaimer').click(function(e) {
        a = $('#view_disclaimer_container').position().top + 20;
        $('#disclaimer_detail').css('top', a + 'px');
        $('#disclaimer_detail').show('slow');
    });

    $('#what_is_included_link').click(function(e) {
        offset_by = Math.ceil(Math.abs(($('#what_is_included').height() - $('#view_disclaimer_container').height()) / 2));
        a = $('#view_disclaimer_container').position().top - offset_by;
        $('#what_is_included').css({ 'top': (a + 'px') });
        $('#what_is_included').show('slow');
        return false;
    });

    $('#disclaimer_detail_close').click(function(e) {
        $('#disclaimer_detail').fadeOut('slow');
    });

    $('#what_is_included_close').click(function(e) {
        $('#what_is_included').fadeOut('slow');
    });

    var isCheckout = ($('#time_blocks').length > 0 || $('#signin_content').length > 0
        || $('#create_account_message').length > 0 || $('#address_selection_container').length > 0
        || $('#confirmation_items_table').length > 0);

    if (isCheckout === true) {
        if ($.cookie(SESSION_GUID, 'rescheduleOrderNumber') == null) {
            $('#edit_order').parent().show();
        }

        var inSchedule = common.inSchedule();
        if (inSchedule === null) {
            document.location = '/Redirect.aspx';
            return;
        }
    }

    $('.jquery-selectbox').css('width', '273px');

    // load CleaningInfo from cookies
    var cleaning_info = loadCleaningInfo();

    $('.item-0').hide();

    if (cleaning_info.ErrorMessage != null || cleaning_info.ZipCode === null) {
        $('.coupon').empty().hide();
        return; // there was an error loading, so exit
    }

    $('#zip_code').val(cleaning_info.ZipCode);

    $('#requires_portable').show();
    if (cleaning_info.isPortable) {
        $('#portableY').attr('checked', true);
        $('#portable_disclaimer').show();
    } else {
        $('#portableY').attr('checked', false);
    }

    if (cleaning_info.HardwoodEstimate) {
        $('#HardwoodEstimate').attr('checked', true);
    }

    requestZipCodeInfo($.cookie(SESSION_GUID, 'zip_code'));
    $('.trash_can').unbind().click(removeRow);
    resetDropDownDimensions();
    hideLeatherDropdown();
    hideAutoDropdown();

    if ($.cookie(SESSION_GUID, 'current_tab') != null) {
        setTab(getCurrentTab(), false, null, true);
        setActiveTab();
        resetDropDownDimensions();
    }
});


//Scans scheduling tool for current status, and uses CleaningInfo to cookie it
function saveQuoteInformation() {
    var status = new CleaningInfo(this, 'saved_quote');

    var _rooms = scanTable('current_room_selection', 'carpet');
    var _cloth = scanTable('current_furniture_selection', 'carpet');
    var _leather = scanTable('current_leather_selection', 'carpet');
    var _autos = scanTable('current_automobile_selection', 'carpet');
    var _guars = scanTable('current_guar_selection', 'guarantee');
    var _tile = scanTable('current_tile_selection', 'tile');
    var _duct = scanTable('current_duct_selection', 'duct');

    for (var i in _rooms) {
        var room = _rooms[i];
        status.Carpets.Rooms[room.Name] = room;
    }

    for (var i in _guars) {
        var room = _guars[i];
        status.Carpets.Guarantees[room.Name] = room;
    }

    for (var i in _cloth) {
        var cloth = _cloth[i];
        status.Carpets.ClothFurniture[cloth.Name] = cloth;
    }

    for (var i in _leather) {
        var leather = _leather[i];
        status.Carpets.LeatherFurniture[leather.Name] = leather;
    }

    for (var i in _autos) {
        var auto = _autos[i];
        status.Carpets.Autos[auto.Name] = auto;
    }

    for (var i in _tile) {
        var tile = _tile[i];
        status.Tile.Rooms[tile.Name] = tile;
    }

    for (var i in _duct) {
        var duct = _duct[i];
        status.Ducts.Rooms[duct.Name] = duct;
    }

    status.Ducts.HVACs = parseInt($('#HVAC_num').val(), 10);
    status.Ducts.AC = $('#AC_yes').attr('checked');
    status.Ducts.Dryer = $('#dryer_yes').attr('checked');
    status.HardwoodEstimate = $('#HardwoodEstimate').attr('checked');

    if ($('#portableY').attr('checked')) {
        status.isPortable = true;
    } else {
        status.isPortable = false;
    }

    var territory = getTerritory();
    var operation = getOperation();

    if (territory !== null && operation !== null) {
        status.City = territory.City;
        status.State = territory.State;
        status.scheduleMinimum = operation.ScheduleMinimum;
    } else {
        var t = getTerritory();
        status.City = t.City;
        status.State = t.State;
        var o = getOperation();
        status.scheduleMinimum = o.ScheduleMinimum;
    }
    status.ZipCode = $.cookie(SESSION_GUID, 'zip_code');

    var selected_special_json = $.cookie(SESSION_GUID, 'current_special');
    if (selected_special_json !== null) {
        status.SpecialID = JSON.parse(selected_special_json).OfferID;
        status.SpecialHTML = getSelectedSpecialHTML();
    }

    status.Save();
    return status;
}

function getSelectedSpecialHTML() {
    return $('.selected_special_offer_list_item').eq(0).html();
}

//returns the status of the provided table
function scanTable(tableID, type) {
    var table = $('#' + tableID);
    var rows = table.children().eq(0).children();
    var tableContents = [];

    var tds;

    for (var j = 2; j < rows.length; j++) {
        tds = rows.eq(j).children();
        var rowContents;

        switch (type) {
            case 'carpet':
                rowContents = new CarpetItem(
										tds.eq(0).children().eq(0).text(),
										tds.eq(1).children().eq(0).val(),
										tds.eq(2).children().eq(0).val(),
										tds.eq(3).children().eq(0).val(),
										false
									);
                tableContents.push(rowContents);
                break;
            case 'tile':
                rowContents = new TileItem(
										tds.eq(0).children().eq(0).text(),
										tds.eq(1).children().eq(0).val(),
										0
									);
                tableContents.push(rowContents);
                break;
            case 'duct':
                rowContents = new DuctItem(
										tds.eq(0).children().eq(0).text(),
										tds.eq(1).children().eq(0).val()
									);
                tableContents.push(rowContents);
                break;
            case 'guarantee':
                rowContents = new CarpetItem(
										tds.eq(0).children().eq(0).text(),
										tds.eq(1).children().eq(0).val(),
										tds.eq(2).children().eq(0).val(),
										tds.eq(3).children().eq(0).val(),
										true
									);
                tableContents.push(rowContents);
                break;
        }

    }

    return tableContents;
}

/*
Function called from selectors "onchange" event
     
1. Adds selected room/furniture/automobile.... to the table above
2. Updates selector by removing the previously selected item
3. Removes selector if no more items are available

SelectorID:   ID of the selection control
groupID:	  ID given to table that is to be manipulated
*/
function selectChangeControl(selectorID, groupID, type) {
    selectorID = "#" + selectorID;
    groupID = "#" + groupID;
    var item = $(selectorID).val();
    var old_item = item;

    if (item == "NA") {
        return; //just in case
    }

    item = item.replace(/_/g, ' ').replace(/-SLASH-/g, '/');

    $('.last_update').removeClass('last_update');

    switch (type) {
        case 'carpet': case 'upholstered':
            $(groupID + " tbody").append(addNewRow(type, item, [1, 0, 0], carpetMin, carpetMax));
            break;
        case 'leather':
            $(groupID + " tbody").append(addNewLeatherRow(type, item, [1, 0, 0], leatherMin, leatherMax));
            break;
        case 'auto':
            $(groupID + " tbody").append(addNewAutoRow(type, item, [1, 0, 0], autoMin, autoMax));
            break;
        case 'tile':
            $(groupID + " tbody").append(addNewRow(type, item, [1], tileMin, tileMax));
            break;
        case 'duct':
            $(groupID + " tbody").append(addNewRow(type, item, [1], ductMin, ductMax));
            break;
        case 'guarantee':
            removeSpecial(false);
            $(groupID + " tbody").append(addNewGuaranteeRow(type, item, [1, 0, 0], carpetMin, carpetMax));
            break;
    }

    if ($(groupID).css('display') === 'none') {
        $(groupID).show('blind', {}, 'slow');
    }

    resetSelector(selectorID, item, old_item);

    $(groupID).show("slow");
    updateTotal();

    //Update event handlers
    $(".num").unbind("change")
	.change(updateTotal);

    $('.trash_can').unbind()
	.click(removeRow);
}



function resetSelector(selector, item, old_item) {
    //update and reset room selector
    $(selector).children().each(function() {
        //reset the selector
        if ($(this).val() === "NA") {
            var select_box = $(selector).parent();
            var select_box_container = $(select_box).children('.jquery-selectbox-list');
            var select_box_items = $(select_box_container).children('span');
            $(this).attr("selected", "selected");
            var dd_text = $(select_box).children('.jquery-selectbox-currentItem');
            var item_0 = $(select_box_items)[0];
            dd_text.text($(item_0).text());
        }
    });

    if ($(selector).children().length == 1) {
        $(selector).parent().hide('blind', {}, 500);
    }
}

// increments the selected dropdown value for an item that has already been selected
function incrementExistingRow(rowName, max) {
    var found = false;
    if ($('#' + rowName).length == 1) {
        var qty = parseInt($('#' + rowName).val());
        if (qty < max) {
            $('#' + rowName).val(qty + 1);
            resetChildren(rowName);
        }
        found = true;
    }
    return found;
}

function addNewRow(row_type, item_name, quantities, min, max) {
    var baseItemName = row_type.replace(/[\s\/]/g, '') + '_' + item_name.replace(/[\s\/]/g, '') + '_1_' + quantities.length;
    var tr = $(row());
    var td = $(cell());

    if (!incrementExistingRow(baseItemName, max)) {
        tr.addClass('room');
        tr.addClass(row_type);
        tr.append(cell('<span style="padding-left:5px;">' + item_name + '</span>'));

        for (j = 0; j < quantities.length; j++) {
            td.addClass('room_quantity');

            if (j > 0) {
                td.append(createQuanitityDropDown_obj(row_type.replace(/[\s\/]/g, '') + '_' + item_name.replace(/[\s\/]/g, '') + '_' + (j + 1) + '_' + quantities.length, 0, quantities[0], quantities[j]));
            } else {
                td.append(createQuanitityDropDown_obj(baseItemName, min, max, quantities[j]));
            }

            tr.append(td);
            td = $(cell());
        }

        td.addClass('room_quantity');
        td.append("<img class='trash_can last_update " + row_type + "' src='/Images/trashcan.gif' alt='Remove' title='Remove' />");
        $('.trash_can').unbind().click(removeRow);

        tr.append(td);

        return tr;
    } else return '';
}

function addNewLeatherRow(row_type, item_name, quantities, min, max) {
    var baseItemName = row_type.replace(/[\s\/]/g, '') + '_' + item_name.replace(/[\s\/]/g, '') + '_1_' + quantities.length;
    var tr = $(row());
    var td = $(cell());

    if (!incrementExistingRow(baseItemName, max)) {
        tr.addClass('room');
        tr.addClass(row_type);
        tr.append(cell('<span style="padding-left:5px;">' + item_name + '</span>'));

        for (j = 0; j < quantities.length; j++) {
            td.addClass('room_quantity');

            if (j > 0) {
                if (j > 1) {
                    td.css('display', 'none');
                }
                td.append(createQuanitityDropDown_obj(row_type.replace(/[\s\/]/g, '') + '_' + item_name.replace(/[\s\/]/g, '') + '_' + (j + 1) + '_' + quantities.length, 0, quantities[0], quantities[j]));
            } else {
                td.append(createQuanitityDropDown_obj(baseItemName, min, max, quantities[j]));
            }

            tr.append(td);
            td = $(cell());
        }

        td.addClass('room_quantity');
        td.append("<img class='trash_can last_update " + row_type + "' src='/Images/trashcan.gif' alt='Remove' title='Remove' />");
        $('.trash_can').unbind().click(removeRow);

        tr.append(td);

        return tr;
    } else return '';
}

function addNewAutoRow(row_type, item_name, quantities, min, max) {
    var baseItemName = row_type.replace(/[\s\/]/g, '') + '_' + item_name.replace(/[\s\/]/g, '') + '_1_' + quantities.length;
    var tr = $(row());
    var td = $(cell());

    if (!incrementExistingRow(baseItemName, max)) {
        tr.addClass('room');
        tr.addClass(row_type);
        tr.append(cell('<span style="padding-left:5px;">' + item_name + '</span>'));

        for (j = 0; j < quantities.length; j++) {
            td.addClass('room_quantity');

            if (j > 0) {
                td.css('display', 'none');
                td.append(createQuanitityDropDown_obj(row_type.replace(/[\s\/]/g, '') + '_' + item_name.replace(/[\s\/]/g, '') + '_' + (j + 1) + '_' + quantities.length, 0, quantities[0], quantities[j]));
            } else {
                td.append(createQuanitityDropDown_obj(baseItemName, min, max, quantities[j]));
            }

            tr.append(td);
            td = $(cell());
        }

        td.addClass('room_quantity');
        td.append("<img class='trash_can last_update " + row_type + "' src='/Images/trashcan.gif' alt='Remove' title='Remove' />");
        $('.trash_can').unbind().click(removeRow);

        tr.append(td);

        return tr;
    } else return '';
}

function addNewGuaranteeRow(row_type, item_name, quantities, min, max) {
    var baseItemName = row_type.replace(/[\s\/]/g, '') + '_' + item_name.replace(/[\s\/]/g, '') + '_1_' + quantities.length;
    var tr = $(row());
    var td = $(cell());

    if (!incrementExistingRow(baseItemName, max)) {
        tr.addClass('room');
        tr.addClass(row_type);
        tr.append(cell('<span style="padding-left:5px;">' + item_name + '</span>'));

        for (j = 0; j < quantities.length; j++) {
            td.addClass('room_quantity');

            if (j > 1) {
                td.append(createQuanitityDropDown_obj(row_type.replace(/[\s\/]/g, '') + '_' + item_name.replace(/[\s\/]/g, '') + '_' + (j + 1) + '_' + quantities.length, 0, quantities[0], quantities[j]));

            } else if (j > 0) {
                td.append("FREE"
                        + createQuantityDropdown(row_type.replace(/[\s\/]/g, '', null) + '_'
                        + item_name.replace(/[\s\/]/g, '') + '_' + (j + 1) + '_'
                        + quantities.length, 0, quantities[0], quantities[j], null, true));
            } else {
                td.append(createQuanitityDropDown_obj(baseItemName, min, max, quantities[j]));
            }

            tr.append(td);
            td = $(cell());
        }

        td.addClass('room_quantity');
        td.append("<img class='trash_can last_update " + row_type + "' src='/Images/trashcan.gif' alt='Remove' title='Remove' />");
        $('.trash_can').unbind().click(removeRow);

        tr.append(td);

        return tr;
    } else return '';
}

function createQuantityDropdown(name, min, max, selected, enabled, hidden) {
    var en = !isNullOrUndefined(enabled) ? enabled : true;
    var hid = !isNullOrUndefined(hidden) ? hidden : false;
    if (!en) {
        enabled = "disabled";
    } else {
        enabled = "";
    }

    if (!hid) {
        hidden = "";
    } else {
        hidden = 'style="display:none"';
    }

    var html = "<select id='" + name + "' onChange='resetChildren(\"" + name + "\");updateTotal();' class='quantitySelect' " + enabled + " " + hidden + ">"; //


    for (var i = min; i <= max; i++) {
        if (i != selected) {
            html += "<option value='" + i + "'>" + i + "</option>";
        } else {
            html += "<option value='" + i + "' selected>" + i + "</option>";
        }
    }
    html += "</select>";

    return html;
}

function createQuanitityDropDown_obj(name, min, max, selected, enabled, hidden) {
    var en = !isNullOrUndefined(enabled) ? enabled : true;
    var hid = !isNullOrUndefined(hidden) ? hidden : false;
    if (!en) {
        enabled = "disabled";
    } else {
        enabled = "";
    }

    if (!hid) {
        hidden = "";
    } else {
        hidden = 'style="display:none"';
    }

    var html = "<select id='" + name + "' onChange='resetChildren(\"" + name + "\");updateTotal();' class='quantitySelect' " + enabled + " " + hidden + ">"; //


    for (var i = min; i <= max; i++) {
        html += "<option value='" + i + "'>" + i + "</option>";

    }
    html += "</select>";

    var domObj = $(html);
    domObj.val(selected);
    return domObj;
}

function resetChildren(name) {
    var nameComponents = name.split("_");
    var parent = $('#' + name);

    // looking for all parent items with children
    if (nameComponents[2] == 1) {
        if (parseInt(parent.val()) == 0) {
            // this is a parent and it was set to zero; delete the row
            removeRowByTarget(parent);
        }
        if (nameComponents[3] > nameComponents[2]) {
            for (i = parseInt(nameComponents[2]) + 1; i <= parseInt(nameComponents[3]); i++) {
                var child = $('#' + nameComponents[0] + '_' + nameComponents[1] + '_' + i + '_' + nameComponents[3]);
                var origChildVal = child.val();

                child.empty();
                //$('#' + name + ' option:first').text()
                for (j = 0; j <= parseInt(parent.val()); j++) {
                    child.append("<option value='" + j + "'>" + j + "</option>");
                }

                // if child has currently selected value greater than parent, lower its selected value to that of parent
                if (parseInt(origChildVal) > parseInt(parent.val())) {
                    child.val(parent.val());
                } else {
                    child.val(origChildVal);
                }
            }
        }
    }
}

//Removes <tr> when called from child of <td>/<th>
//Adds item back into the selector
//Only used when deleting is active
function removeRow() {
    var row = $(this).parent().parent();
    var table = row.parent().parent();
    var selectorID = table.next().children('select').attr('id');
    var rowContents = row.contents();
    var desc = $(rowContents[0]).children().text();

    row.remove();

    //check the tboby to see if it has any rows in it
    //if it doesn't, hide it
    if (table.children().contents().length == 2) {
        table.hide('blind', {}, 500);
    }

    updateTotal();
    saveQuoteInformation();
    return false;
}

//same as remove row
//accepts trash can icon in row to be removed
function removeRowByTarget(target) {
    var row = $(target).parent().parent();
    var table = row.parent().parent();
    var selectorID = table.next().children('select').attr('id');
    var rowContents = row.contents();
    var desc = $(rowContents[0]).children().text();

    row.remove();

    //check the tboby to see if it has any rows in it
    //if it doesn't, hide it
    if (table.children().contents().length == 2) {
        table.hide('blind', {}, 500);
    }

    saveQuoteInformation();
    return false;
}

//Handles the click events for the tabs
//accepts the event object 
function tabControl(e) {
    e.stopPropagation();

    var pt_id = $('#current').find("a").eq(0).attr('id');

    //check if the tab being clicked is active
    if ($(this).attr('id') === 'current') {
        return false;
    }

    var prev_tab = $(this);

    // pull the name of the current link that was clicked and use it 
    // to construct the name of the tab to be displayed
    var tab = $(this).contents();

    var tabName = '#' + $(tab[0]).attr('id') + '_tab';

    // clear current tab
    $('#schedule_tabs UL LI').each(function() {
        $(this).removeAttr('id');
    })
	.unbind('click');

    // set current tab to clicked tab
    $(this).attr('id', 'current');

    return setTab(tabName, false, pt_id, false);
}

function emptyTable(selector) {
    var rows = $(selector + " tr");

    for (var j = 2; j < rows.length; j++) {
        rows.eq(j).remove();
    }
}

function setTab(tabName, clearEstimate, previousTab, bypass) {
    if (clearEstimate === true) {
        $.cookie(SESSION_GUID, 'saved_quote', null, { path: '/' });
    }

    if (tabName === '#undefined_tab' && $.browser.safari) {
        tabName = '#call_tab';
    }

    // hide all tab content
    $('#estimation_section').children().each(function() {
        $(this).css('display', 'none');
    });



    // show current tab content
    $(tabName).show();
    if (tabName == '#guar_tab') {
        $('#carpet_tab').show();
        var account = AjaxManager.Customer.getAccount();
        if (account == null) {
            $('#accountSignInLink').attr("href", "/Home/SignIn.aspx")
        }
        else {
            $('#accountSignInLink').attr("href", "/Home/MyAccount.aspx")
        }
    }

    if ($('#edit_order').parent().css('display') == 'none') {
        if (tabName == '#tile_tab') {
            $('#what_is_included_link').parent().show();
            if ($('.c_tab').css('display') !== 'none') {
                $('#add_carpet_link').parent().show();
            }
            $('#add_tile_link').parent().hide();
        } else {
            $('#what_is_included_link').parent().hide();
        }

        if (tabName == '#carpet_tab') {
            $('#add_carpet_link').parent().hide();
            if ($('.t_tab').css('display') !== 'none') {
                $('#add_tile_link').parent().show();
            }
        }

        if (tabName == '#duct_tab') {
            $('#add_carpet_link').parent().hide();
            $('#add_tile_link').parent().hide();
        }
    }

    $(tabName).children().each(function() {
        $(this).css('display', '');
    });

    if (!common.inSchedule()) {
        setTimeout('$("#schedule_tabs UL LI").click(tabControl);', 500);
    }

    $('.jquery-selectbox').each(function() {
        $(this).width('273');
    });

    if (bypass) {
        return false
    }

    $('.tab_warning').hide();

    resetDropDownDimensions();
    var ci = loadCleaningInfo();

    var dom = document.getElementById('schedule_tabs'); 	//the scheduling tab
    var top = dom.offsetTop; 							//top position of the scheduling tab
    dom = document.getElementById('schedule_section'); 	//the scheduling section 
    left = dom.offsetLeft; 								//left position of the scheduling section
    var length = window.screen.height; 					//length of the screen

    var operation = cache.getItem("Operation");
    var doesAirDucts = true;
    if (operation != null) {
        doesAirDucts = operation.DoesAirDuctCleaningOnline && operation.DoesAirDuctCleaning;
    }

    if (tabName === '#guar_tab' && previousTab === 'carpet') {
        var aas = AjaxManager.AreasAndServices.getAreasAndServices();
        if (aas !== null && aas !== undefined) {

            ci.switchToGuarantee();
            ci.Save();

            $('#current_guar_selection').hide();
            $('#current_room_selection').hide();
            emptyTable('#current_guar_selection');
            emptyTable('#current_room_selection');

            $.cookie(SESSION_GUID, 'saved_carpet_special', $.cookie(SESSION_GUID, 'current_special'));

            AddGuaranteedRooms(aas.CarpetCollection.Areas, ci);
            resetDropDownDimensions();

            $('.trash_can').unbind()
	    .click(removeRow);
        }
    }
    if (tabName === '#carpet_tab') {
        var aas = AjaxManager.AreasAndServices.getAreasAndServices();
        if (aas !== null && aas !== undefined) {
            ci.switchToCarpet();
            ci.Save();

            $('#current_guar_selection').hide();
            $('#current_room_selection').hide();
            emptyTable('#current_guar_selection');
            emptyTable('#current_room_selection');

            AddCarpetRooms(aas.CarpetCollection.Areas, ci);
            resetDropDownDimensions();

            if (($.cookie(SESSION_GUID, 'current_special') == null) && ($.cookie(SESSION_GUID, 'saved_carpet_special') != null)) {
                var selected_special_json = $.cookie(SESSION_GUID, 'saved_carpet_special');
                $('a[id*="special_' + JSON.parse(selected_special_json).OfferID + '"]').eq(0).click();
            }

            $('.trash_can').unbind()
	    .click(removeRow);
        }
    }


    if (tabName == '#duct_tab' && doesAirDucts) {
        if (ci.ZipCode !== null && previousTab.indexOf('call') < 0) {
            // Display the disable panel
            $('#disable_panel').css('top', top).css('left', left).css('height', length + "px").show();
            $('#disable_panel').after($('#duct_tab_switch_warning'));

            // Display the warning message
            $('#duct_tab_switch_warning').show();

            $('#duct_tab_switch_warning_ok a').unbind().click(function(tab) {
                $('#duct_tab_switch_warning').hide();
                $('#disable_panel').hide();

                var cookies = {};
                cookies['saved_quote'] = null;
                cookies['current_tab'] = tabName.split('_')[0].replace(/#/, '');
                $.setCookieInBulk(SESSION_GUID, cookies, true);

                if ($.cookie(SESSION_GUID, 'zip_code') !== null) { updateTotal(true); }
            });
            $('#duct_tab_switch_warning_cancel a').unbind().click(function() {
                $('#duct_tab_switch_warning').hide();
                $('#disable_panel').hide();
                setTab(getCurrentTab(), false, null, true);
                setActiveTab();
                resizeSidebar();
                return false;
            });
        } else {
            $.cookie(SESSION_GUID, 'current_tab', tabName.split('_')[0].replace(/#/, ''), { path: '/' });
            if ($.cookie(SESSION_GUID, 'zip_code') !== null) { updateTotal(true); }
            resizeSidebar();
        }
    } else if (previousTab.indexOf('duct') >= 0 && !(doesAirDucts)) {
        $.cookie(SESSION_GUID, 'current_tab', tabName.split('_')[0].replace(/#/, ''), { path: '/' });
        resizeSidebar();
    } else {
        if (ci.ZipCode !== null
        && previousTab.indexOf('carpet') < 0
        && previousTab.indexOf('tile') < 0
        && previousTab.indexOf('guar') < 0
        && previousTab.indexOf('call') < 0) {
            // Display the disable panel
            $('#disable_panel').css('top', top).css('left', left).css('height', length + "px").show();
            $('#disable_panel').after($('#carpet_tile_tab_switch_warning'));

            // Display the warning message
            $('#carpet_tile_tab_switch_warning').show();

            $('#carpet_tile_tab_switch_warning_ok a').unbind().click(function(tab) {
                $('#carpet_tile_tab_switch_warning').hide();
                $('#disable_panel').hide();

                var cookies = {};
                cookies['saved_quote'] = null;
                cookies['current_tab'] = tabName.split('_')[0].replace(/#/, '');
                $.setCookieInBulk(SESSION_GUID, cookies, true);

                if ($.cookie(SESSION_GUID, 'zip_code') !== null) { updateTotal(true); }
            });
            $('#carpet_tile_tab_switch_warning_cancel a').unbind().click(function() {
                $('#carpet_tile_tab_switch_warning').hide();
                $('#disable_panel').hide();
                setTab(getCurrentTab(), false, null, true);
                setActiveTab();
                resizeSidebar();
                return false;
            })
        } else {
            $.cookie(SESSION_GUID, 'current_tab', tabName.split('_')[0].replace(/#/, ''), { path: '/' });
            if ($.cookie(SESSION_GUID, 'zip_code') !== null) { updateTotal(true); }
            resizeSidebar();
        }
    }

    SetDisclaimers();

    return false;
}



//checks if key pressed is a numeric key
function isNumberKey(evt) {
    var charCode = evt.which ? evt.which : event.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }
    if (charCode === 13) {
        return false;
    }
    return true;
}

function showUpdateTotalWaitSpinner() {
    //format and show the wait spinner
    if (!($.browser.msie && parseFloat($.browser.version) < 7)) {
        var div_height = $('#quote_body').height();
        var width = $('#quote_body').width();

        //if the quote box is too small, add a div to space it out
        if (div_height < 21) {
            $('#quote_body').append('<div style="height:15px"></div>');
            div_height = $('#quote_body').height();
        }

        //create a transparent div with the spinner
        $('#quote_body').before('<div class="quote_wait_div"><img class="quote_wait" style="max-height: '
			+ div_height + 'px;" alt="Please wait..." src="/Images/wait.gif" /><div class="quote_wait_inner" style="height: ' + (div_height - 1) + 'px;">'
			+ '</div></div>');
        $('.quote_wait').css('left', '111px');

        //if the quote is big enough, place spinner in the vertical center of the box
        if (div_height > 42) {
            $('.quote_wait').css('margin-top', (div_height / 2 - 21) + 'px');
        }

        $('.quote_wait_div').fadeIn();
    }
}


function populateAirDuctOrderAmounts(amounts, itemIDs, order, cleaning_info) {
    cleanID = AjaxManager.AreasAndServices.Services.AirDuct.Clean.serviceId;
    areas = AjaxManager.AreasAndServices.Areas.AirDuct;

    amounts.AirDuct = {
        Clean: 0
    };

    $(".duct:not(.trash_can)").each(function() {
        var row = $(this).contents();
        var desc = $(row[0]).text();
        var clean = parseFloat($(row[1]).contents().filter(":input").val());
        var areaID = areas[desc];

        amounts.AirDuct.Clean += clean;

        //assemble pricing request objects
        order.push({ LineID: order.length + 1, Quantity: clean, AreaID: areaID, ServiceID: cleanID });

        var duct_item = new DuctItem(desc, clean);
        cleaning_info.Ducts.Rooms[desc] = duct_item;
    });

    //get additional air duct information
    var ductExtra = cache.getItem('airDuctExtra');
    if (ductExtra === null) {
        hideLeatherDropdown();
        hideAutoDropdown();
        return false;
    }

    //Add line item for the number of furnaces / HVACs
    cleaning_info.Ducts.HVACs = parseInt($('#HVAC_num').val(), 10);
    if (cleaning_info.Ducts.HVACs > 0) {
        order.push({
            LineID: order.length + 1,
            Quantity: parseInt($('#HVAC_num').val(), 10),
            AreaID: ductExtra.HVAC.AreaID,
            ServiceID: cleanID
        });
    }

    //Add line item if dryer is checked
    if ($('#dryer_yes').attr('checked')) {
        cleaning_info.Ducts.Dryer = true;
        order.push({
            LineID: order.length + 1,
            Quantity: 1,
            AreaID: ductExtra.Dryer.AreaID,
            ServiceID: cleanID
        });
    }


    if ($('#AC_yes').attr('checked')) {
        cleaning_info.Ducts.AC = true;
    }

    //remove items from other tags
    $('.trash_can').each(function() {
        if (!$(this).hasClass('duct')) {
            removeRowByTarget(this);
        }
    });

    return true;
}

function populateCarpetOrderAmounts(amounts, itemIDs, order, cleaning_info) {
    try {
        var carpetAmountsArea = createAmountsArea(amounts, "Carpet");
        createCarpetOrderLineItems('.carpet', order, carpetAmountsArea, itemIDs.CarpetIDs, itemIDs.CarpetServices, cleaning_info.Carpets.Rooms);
    } catch (e) { }

    try {
        var upholsteredAmountsArea = createAmountsArea(amounts, "Upholstered")
        createCarpetOrderLineItems('.upholstered', order, upholsteredAmountsArea, itemIDs.UpholsteredIDs, itemIDs.UpholsteredServices, cleaning_info.Carpets.ClothFurniture);
    } catch (e) { }

    try {
        var leatherAmountsArea = createAmountsArea(amounts, "Leather")
        createCarpetOrderLineItems('.leather', order, leatherAmountsArea, itemIDs.LeatherIDs, itemIDs.LeatherServices, cleaning_info.Carpets.LeatherFurniture);
    } catch (e) { }

    try {
        var autoAmountsArea = createAmountsArea(amounts, "Auto")
        createCarpetOrderLineItems('.auto', order, autoAmountsArea, itemIDs.AutoIDs, itemIDs.AutoServices, cleaning_info.Carpets.Autos);
    } catch (e) { }
}

function createAmountsArea(amounts, amountsAreaName) {
    return amounts[amountsAreaName] = {
        Clean: 0, Protect: 0, Deodorize: 0
    };
}

function createCarpetOrderLineItems(targetID, order, amountsArea, itemsIDsArea, itemIDsAreaServices, cleaningInfoArea) {
    var cleanId = AjaxManager.AreasAndServices.Services.Carpet.Clean.serviceId;
    var protectId = AjaxManager.AreasAndServices.Services.Carpet.Protect.serviceId;
    var deodorizeId = AjaxManager.AreasAndServices.Services.Carpet.Deodorize.serviceId;
    var areas = AjaxManager.AreasAndServices.Areas.Carpet;

    switch (targetID) {
        case '.carpet':
            break;
        case '.upholstered':
            cleanId = AjaxManager.AreasAndServices.Services.Carpet.Clean.serviceId;
            protectId = AjaxManager.AreasAndServices.Services.Carpet.Protect.serviceId;
            deodorizeId = AjaxManager.AreasAndServices.Services.Carpet.Deodorize.serviceId;
            areas = AjaxManager.AreasAndServices.Areas.Upholstered;
            break;
        case '.leather':
            cleanId = AjaxManager.AreasAndServices.Services.Leather.Clean.serviceId;
            protectId = AjaxManager.AreasAndServices.Services.Leather.Protect.serviceId;
            areas = AjaxManager.AreasAndServices.Areas.Leather;
            break;
        case '.auto':
            cleanId = AjaxManager.AreasAndServices.Services.Auto.Clean.serviceId;
            areas = AjaxManager.AreasAndServices.Areas.Auto;
            break;
    }



    $(targetID + ":not(.trash_can)").each(function() {

        var row = $(this).contents();
        var desc = $(row[0]).text();
        var clean = parseInt($(row[1]).contents().filter(":input").val(), 10);
        var protect = parseInt($(row[2]).contents().filter(":input").val(), 10);
        var deodorize = parseInt($(row[3]).contents().filter(":input").val(), 10);
        var areaID = areas[desc];

        amountsArea.Clean += clean;
        amountsArea.Protect += protect;
        amountsArea.Deodorize += deodorize;

        //assemble pricing request objects
        order.push({ LineID: order.length + 1, Quantity: clean, AreaID: areaID, ServiceID: cleanId });
        if (protect > 0) {
            order.push({ LineID: order.length + 1, Quantity: protect, AreaID: areaID, ServiceID: protectId });
        }

        if (deodorize > 0) {
            order.push({ LineID: order.length + 1, Quantity: deodorize, AreaID: areaID, ServiceID: deodorizeId });
        }

        var carpet_item = new CarpetItem(desc, clean, protect, deodorize, false);

        cleaningInfoArea[desc] = carpet_item;
    });
}

function populateTileOrderAmounts(amounts, itemIDs, order, cleaning_info) {
    cleanid = AjaxManager.AreasAndServices.Services.TileGrout.Clean.serviceId;
    areas = AjaxManager.AreasAndServices.Areas.TileGrout;

    //Tile & Grout items will be calculated when pricing moves to a  per room basis
    amounts.Tile = {
        Clean: 0
    };

    $(".tile:not(.trash_can)").each(function() {
        var row = $(this).contents();
        var desc = $(row[0]).text();
        var clean = parseInt($(row[1]).contents().filter(":input").val(), 10);
        var areaID = areas[desc];

        amounts.Tile.Clean += clean;


        //assemble pricing request objects
        order.push({ LineID: order.length + 1, Quantity: clean, AreaID: areaID, ServiceID: cleanid });

        var tile_item = new TileItem(desc, clean, 0);
        cleaning_info.Tile.Rooms[desc] = tile_item;

    });

}

function populateGuaranteeOrderAmounts(amounts, itemIDs, order, cleaning_info) {
    guaranteeId = AjaxManager.AreasAndServices.Services.Guarantee.Guarantee.serviceId;
    cleanId = AjaxManager.AreasAndServices.Services.Carpet.Clean.serviceId;
    deodorizeId = AjaxManager.AreasAndServices.Services.Carpet.Deodorize.serviceId;
    areas = AjaxManager.AreasAndServices.Areas.Carpet;

    amounts.Guarantee = {
        Clean: 0,
        Deodorize: 0
    }

    $(".guarantee:not(.trash_can)").each(function() {
        var row = $(this).contents();
        var desc = $(row[0]).text();
        var clean = parseInt($(row[1]).contents().filter(":input").val(), 10);
        var protect = parseInt($(row[2]).contents().filter(":input").val(), 10);
        var deodorize = parseInt($(row[3]).contents().filter(":input").val(), 10);
        var areaID = areas[desc];

        amounts.Guarantee.Clean += clean;
        amounts.Carpet.Deodorize += deodorize;

        order.push({ LineID: order.length + 1, Quantity: clean, AreaID: areaID, ServiceID: guaranteeId });
        order.push({ LineID: order.length + 1, Quantity: clean, AreaID: areaID, ServiceID: cleanId });

        if (deodorize > 0) {
            order.push({ LineID: order.length + 1, Quantity: deodorize, AreaID: areaID, ServiceID: deodorizeId });
        }

        var carpet_item = new CarpetItem(desc, clean, protect, deodorize, true);
        cleaning_info.Carpets.Guarantees[desc] = carpet_item;
    });
}

function populateGscAmounts(amounts, itemIDs, order, cleaning_info) {
    var serviceId = AjaxManager.AreasAndServices.Services.Guarantee.GSC.serviceId;
    var protectServiceID = AjaxManager.AreasAndServices.Services.Carpet.Protect.serviceId;
    var deodorizeServiceID = AjaxManager.AreasAndServices.Services.Carpet.Deodorize.serviceId;

    amounts.Gsc = {
        Clean: 0,
        Protect: 0,
        Deodorize: 0
    }

    $(".gsc:not(.gtrash_can)").each(function() {

        var areaID;
        var row = $(this).contents();
        var desc = $(row[0]).text();
        var clean = parseInt($(row[1]).contents().filter(":input").val(), 10);
        var protect = parseInt($(row[2]).contents().filter(":input").val(), 10);
        var deodorize = parseInt($(row[3]).contents().filter(":input").val(), 10);
        var container = $(this).parent().parent().parent();
        var guarID = container.attr('id').split('_')[2];
        
        if (AjaxManager.Guarantee.active[guarID] == null || AjaxManager.Guarantee.active[guarID] == 'undefined') return;
        
        var orderNum = AjaxManager.Guarantee.active[guarID].OriginalOrderNumber;

        amounts.Gsc.Clean += clean;
        amounts.Carpet.Protect += protect;
        amounts.Carpet.Deodorize += deodorize;

        for (var k in AjaxManager.AreasAndServices.Areas) {
            areaID = AjaxManager.AreasAndServices.Areas[k][desc];
            if (areaID !== undefined) {
                break;
            }
        }

        //TODO: Add correct service id
        order.push({ LineID: order.length + 1, Quantity: clean, AreaID: areaID, ServiceID: serviceId, OriginalOrderNumber: orderNum });

        if (protect > 0) {
            order.push({ LineID: order.length + 1, Quantity: protect, AreaID: areaID, ServiceID: protectServiceID });
        }

        if (deodorize > 0) {
            order.push({ LineID: order.length + 1, Quantity: deodorize, AreaID: areaID, ServiceID: deodorizeServiceID });
        }
    });
}

function populateRenewals(order) {
    $('.renewal').each(function() {
        var id = $(this).attr('id').split('_')[2];
        var guar = AjaxManager.Guarantee.active[id];

        if ($(this).attr('checked')) {
            var lineItems = guar.RenewalLineItems;
            guar.isRenewed = true;
            AjaxManager.Guarantee.save();

            for (var i in lineItems) {
                order.push(lineItems[i]);
            }
        } else {
            guar.isRenewed = false;
            AjaxManager.Guarantee.save();
        }
    });
}

function checkHardwoodEstimate(order) {
    if ($('#HardwoodEstimate').attr('checked')) {
        var lineID = 0;
        var estimate = common.createHardwoodEstimateLineItem();

        if (order !== null && order !== undefined && order.length !== 0) {
            var lineID = order[order.length - 1].LineID + 1;
        }

        estimate.LineID = lineID;
        order.push(estimate);
    }
}

function handleEmptyOrder() {
    //if there are no items, clear quote and update totals to 0
    if ($.cookie(SESSION_GUID, 'zip_code') !== null) {
        $.cookie(SESSION_GUID, 'prices', null, { path: '/' });
        $("#quote_body").empty().append('Select areas to be cleaned above.');
        $("#total_costs_table").empty();
        $('#add_services').show();
        $('#total_cost_items').show();
        $('#total_costs_table').append(createCostRow(SUBTOTAL, 'Subtotal', 0));
        $('#total_costs_table').append(createCostRow(SUBTOTAL, 'Tax', 0));
        $('#total_costs_table').append(createCostRow(TOTAL, 'Total', 0)).show();
    }

    $('.quote_wait_div').fadeOut().remove();
}

function updateGuaranteedStatus() {
    var ci = loadCleaningInfo();
    var isGuaranteed = false;

    if (!isNullOrUndefined(ci.Carpets.Guarantees)) {
        for (var i in ci.Carpets.Guarantees) {
            isGuaranteed = true;
        }
    }

    isGuaranteed = isGuaranteed || AjaxManager.Guarantee.hasActive();

    if (isGuaranteed) {
        AjaxManager.Estimate.publishOrderGuaranteed();
    } else {
        AjaxManager.Estimate.publishOrderNotGuaranteed();
    }
}

//Updates the quote total
function updateTotal(reset) {
    if ($.cookie(SESSION_GUID, 'current_tab') === 'call') return false;
    if ($.cookie(SESSION_GUID, 'zip_code') == null) return false;

    var val = $(this).val();
    if ($(this).hasClass('num')) {
        if (parseInt(val, 10) < 0) {
            val = Math.abs(val);
            $(this).val(val);
        }
    }

    if ($(this).hasClass('num')) {
        $('.last_update').removeClass('last_update');
        $(this).parent().parent().find('.trash_can').addClass('last_update');
    }

    if (reset !== 'return') {
        showUpdateTotalWaitSpinner();
    }

    var type = 1; 									    //the type of service 1 - carpet/tile  2 - air duct
    var territory = getTerritory(); 					//selected territory
    var operation = getOperation(); 				    //operation for that territory
    var itemIDs = buildIDList(getAreasAndServices());   //Simplified areasandservices list
    var notes = 'Central Air: NO';
    var order = []; 									//list of line items for AJAX call
    var cleaning_info = loadCleaningInfo();
    var amounts = { Carpet: null, Upholstered: null, Leather: null, Auto: null, Tile: null, AirDuct: null, Guarantee: null };

    setTimeout(updateGuaranteedStatus, 200);

    if ($('#current').hasClass('a_tab')) {        
        type = 2; //set type for GetPricing.  Type 2 = ServiceType.AirDuct
        var result = populateAirDuctOrderAmounts(amounts, itemIDs, order, cleaning_info)
        if (!result) {
            return;
        }
    } else {
        populateCarpetOrderAmounts(amounts, itemIDs, order, cleaning_info);
        populateTileOrderAmounts(amounts, itemIDs, order, cleaning_info);
        populateGuaranteeOrderAmounts(amounts, itemIDs, order, cleaning_info);
        populateGscAmounts(amounts, itemIDs, order, cleaning_info);
        populateRenewals(order);
        checkHardwoodEstimate(order);

        //remove items in other two tabs
        $('#duct_tab .trash_can').each(function() {
            if ($(this).hasClass('duct')) {
                removeRowByTarget(this);
            }
        });
    }

    

    if (order.length === 0) {
        handleEmptyOrder();
        return;
    }

    //check to see if the job requires a portable unit	
    var isPortableJob = false;
    if ($('#portableY').attr('checked') === true) {
        isPortableJob = true;
    }

    var offer;
    offer = AjaxManager.Discount.getActiveDiscount();

    try {
        offer.EndDate = new Date(parseInt(offer.EndDate.replace(/\D/g, ''), 10));
        offer.StartDate = new Date(parseInt(offer.StartDate.replace(/\D/g, ''), 10));
    } catch (ex) { }

    //build the request object
    var pricing_request = {
        operation: operation,
        territory: territory,
        items: order,
        isPortableJob: isPortableJob,
        type: type,
        Offer: offer,
        customer: null
    };

    //remove items in duct tab
    if (reset == 'return') {
        return pricing_request;
    }

    var account = AjaxManager.Customer.getAccount();
    if (account !== null && account !== undefined && $('#TotalsSection').length > 0) {
        if (account.getSelectedAddress() !== null && account.getSelectedAddress() !== undefined) {
            pricing_request.customer = AjaxManager.Customer.getAccount().getSelectedAddress().CustomerRecord;
        }
    }

    var cookies = {};
    
    cookies['order_details'] = JSON.stringify(order);    
    cookies['quantities'] = JSON.stringify(amounts);

    $.setCookieInBulk(SESSION_GUID, cookies, true);

    $.ajax({
        url: '/Service.asmx/GetPricing',
        type: 'POST',
        datatype: 'json',
        //timeout: 10000,
        data: JSON.stringify(pricing_request),
        contentType: 'application/json; charset=utf-8',
        success: function(res) {
            var line_items = JSON.parse(res);
            if (line_items.IsError) {

                error_response(line_items.ErrorDescription, true);
                return false;
            }
                     
            $.cookie(SESSION_GUID, 'prices', res, { path: '/' });
            AjaxManager.Estimate.publishTotal(line_items);
            buildRealTimeQuote(operation);
        },
        error: function(err) { error_response(err, true); }
    });

    // attempt to resize the sidebar
    try {
        resizeSidebar();
    } catch (err) {
        // do nothing!
    }


    hideLeatherDropdown();
    hideAutoDropdown();
    
    cleaning_info.Save();
    
   
}

function buildRealTimeQuote(operation) {
    $('.quote_wait_div').eq(0).fadeOut().remove();
    if ($.cookie(SESSION_GUID, 'prices') == null
        || $.cookie(SESSION_GUID, 'quantities') == null) {
        return;
    }
    var line_items = JSON.parse($.cookie(SESSION_GUID, 'prices'));
    var amounts = JSON.parse($.cookie(SESSION_GUID, 'quantities'));

    //show disclaimer if it exists otherwise hide it
    if (line_items.Disclaimer !== null && line_items.Disclaimer !== '') {
        $('#order_dsiclaimer_text').empty();
        $('#order_dsiclaimer_text').append(line_items.Disclaimer);
        $('#order_disclaimer_detail').show('slow');
    } else {
        $('#order_disclaimer_detail').hide();
    }

    $("#quote_body").empty();
    $("#total_costs_table").empty();
    $("#quote_init").hide();
    $('#schedule_now').css('border-top', 'solid 1px #000000');

    var tax = 0;

    var line_item_groups = {
        Carpet: [],
        Upholstered: [],
        Leather: [],
        Auto: [],
        Tile: [],
        Duct: [],
        Other: [],
        Savings: [],
        Guarantee: [],
        Hardwood: [],
        Tax: null,
        Subtotal: 0
    };

    var isMinPriceMet = true;
    clearInvalidOfferMessage();

    for (var i = 0; i < line_items.SummaryInfoDetails.length; i++) {
        var serviceTypeID = line_items.SummaryInfoDetails[i].ServiceTypeID;
        var amount = line_items.SummaryInfoDetails[i].Amount;
        var description = line_items.SummaryInfoDetails[i].Description;
        var isOfferValid = line_items.SummaryInfoDetails[i].IsOfferValid;
        var offerMessage = line_items.SummaryInfoDetails[i].OfferMessage;
        var offerApplyMessage = line_items.SummaryInfoDetails[i].OfferApplyMessage;
        var line_item = { Amount: amount, Description: description, IsOfferValid: isOfferValid, OfferMessage: offerMessage, OfferApplyMessage: offerApplyMessage };

        switch (serviceTypeID) {
            case 1:
                line_item_groups.Carpet.push(line_item);
                break;
            case 2:
                line_item_groups.Upholstered.push(line_item);
                break;
            case 3:
                line_item_groups.Tile.push(line_item);
                break;
            case 9:
                line_item_groups.Leather.push(line_item);
                break;
            case 7:
                line_item_groups.Auto.push(line_item);
                break;
            case 4:
                line_item_groups.Duct.push(line_item);
                break;
            case -3: // -3 = Portable Surcharge
                line_item_groups.Other.push(line_item);
                break;
            case -2: case -4: case -5: // -2 = Portable Minimum; -4 = Cleaning Minimum; -5 = Scheduling Minimum
                if (mimimum_order_message_status !== 'closed') {
                    minimum_order_message = line_item.Amount;
                    isMinPriceMet = false;
                    mimimum_order_message_status = 'show';
                }
                line_item_groups.Other.push(line_item);
                break;
            case -6:
                line_item_groups.Savings.push(line_item);
                setInvalidOfferMessage(line_item);
                break;
            case -1:
                line_item_groups.Tax = line_item;
                break;
            case -12:
                line_item_groups.Guarantee.push(line_item);
                break;
            case -14:
                line_item_groups.Hardwood.push(line_item);
                break;
        }

        if (serviceTypeID != -1) {
            line_item_groups.Subtotal += line_item.Amount;
        }

        /*
        -2 = Portable Minimum
        -3 = Portable Surcharge
        -4 = Cleaning Minimum
        -5 = Scheduling Minimum
        */
    }

    if (isMinPriceMet && mimimum_order_message_status !== 'closed') {
        mimimum_order_message_status = 'hide';
    }

    var firstTable = true;

    if (line_item_groups.Guarantee.length > 0) {
        $('#quote_body').append(createCostTable('Guarantee', line_item_groups.Guarantee, amounts.Guarantee));
        firstTable = false;
    }

    if (line_item_groups.Carpet.length > 0) {
        if (!firstTable) {
            $('#quote_body').append('<hr class="quote_hr" />');
        }

        $('#quote_body').append(createCostTable('Carpet', line_item_groups.Carpet, amounts.Carpet));
        firstTable = false;
    }

    if (line_item_groups.Upholstered.length > 0) {
        if (!firstTable) {
            $('#quote_body').append('<hr class="quote_hr" />');
        }

        $('#quote_body').append(createCostTable('Upholstered Furniture', line_item_groups.Upholstered, amounts.Upholstered));
        firstTable = false;
    }

    if (line_item_groups.Leather.length > 0) {
        if (!firstTable) {
            $('#quote_body').append('<hr class="quote_hr" />');
        }

        $('#quote_body').append(createCostTable('Leather Furniture', line_item_groups.Leather, amounts.Leather));
        firstTable = false;
    }

    if (line_item_groups.Auto.length > 0) {
        if (!firstTable) {
            $('#quote_body').append('<hr class="quote_hr" />');
        }

        $('#quote_body').append(createCostTable('Automobile', line_item_groups.Auto, amounts.Auto));
        firstTable = false;
    }

    if (line_item_groups.Tile.length > 0) {
        if (!firstTable) {
            $('#quote_body').append('<hr class="quote_hr" />');
        }

        $('#quote_body').append(createCostTable('Tile & Grout', line_item_groups.Tile, amounts.Tile));
        firstTable = false;
    }

    if (line_item_groups.Duct.length > 0) {
        if (!firstTable) {
            $('#quote_body').append('<hr class="quote_hr" />');
        }

        $('#quote_body').append(createCostTable('Air Duct', line_item_groups.Duct, amounts.AirDuct));
        firstTable = false;
    }

    if (line_item_groups.Savings.length > 0) {
        if (!firstTable) {
            $('#quote_body').append('<hr class="quote_hr" />');
        }

        $('#quote_body').append(createCostTable('Savings', line_item_groups.Savings));
        firstTable = false;
    }

    if (line_item_groups.Hardwood.length > 0) {
        if (!firstTable) {
            $('#quote_body').append('<hr class="quote_hr" />');
        }

        $('#quote_body').append(createCostTable('Hardwood', line_item_groups.Hardwood));
        firstTable = false;
    }

    if (line_item_groups.Other.length > 0) {
        if (!firstTable) {
            $('#quote_body').append('<hr class="quote_hr" />');
        }

        $('#quote_body').append(createCostTable('Other', line_item_groups.Other));
        firstTable = false;
    }

    if ($("#total_costs").css('display') === 'none') {
        if ($.browser.safari === true) {
            $("#total_costs").show();

        } else {
            $("#total_costs").show('blind', {}, 500);
        }
    }
    if ($.browser.safari === true) {
        var height = $('.tab-bg').height();
        $('.tab-bg').css('height', (height + 1) + 'px');
        $('.tab-bg').css('height', height + 'px');
        //If the quote is editable, need to do this so the scroll bar will expand if items are added
        if ($('#schedule_now').is(':visible')) {
            $('.tab-bg').css('height', '');
        }
    }
    subtotal = line_item_groups.Subtotal;
    tax = line_item_groups.Tax.Amount;
    var total = subtotal + tax;

    $('#add_services').show();
    $('#total_cost_items').show();
    $('#total_costs_table').append(createCostRow(SUBTOTAL, 'Subtotal', subtotal));
    $('#total_costs_table').append(createCostRow(SUBTOTAL, 'Tax', tax));
    $('#total_costs_table').append(createCostRow(TOTAL, 'Total', total)).show();

    ClearSaleing_PriceUpdate(line_item_groups, subtotal, tax, total, operation.OperationID);

    if (minimum_order_message) {
        scheduleMinimumMessage(operation, subtotal);
    }

    if (!(common.inSchedule())) {
        saveQuoteInformation();
    }
}

function formatDisclaimerMessage(operation) {
    if (operation == null) { return false; }
    var currentTab = $('#current a').attr('id');

    $('.standard_room_size').empty().append(operation.StandardRoomSize);
    if ($('#portableY').attr('checked')) {
        if (operation.PortableMinimum > 0) {
            $('.disclaimer_amount').empty().append(operation.PortableMinimum.toFixed(2));
            $('.minimum_type').empty().append('portable');
            $('.surcharge_disclaimer').hide();

            $('.portable_disclaimer_generic').hide();
            $('.portable_disclaimer_surcharge').hide();
            $('.portable_disclaimer_minimum').show();
            $('.portable_disclaimer_minimum_amount').show();
            $('.portable_disclaimer_minimum_amount').empty().append(operation.PortableMinimum.toFixed(2));
        } else {
            $('.portable_disclaimer_minimum').hide();
            if (operation.PortableSurcharge > 0) {
                $('.surcharge_disclaimer').show();
                $('.portable_disclaimer_surcharge_amount').show();
                $('.portable_disclaimer_surcharge_amount').empty().append(operation.PortableSurcharge.toFixed(2));

                $('.portable_disclaimer_generic').hide();
                $('.portable_disclaimer_surcharge').show();
                $('.portable_disclaimer_minimum').hide();
            } else {
                $('.surcharge_disclaimer').hide();
                $('.portable_disclaimer_surcharge').hide();
            }

            if (operation.ScheduleMinimum > 0) {
                $('.minimum_type').empty().append('job');
                $('.disclaimer_amount').empty().append(operation.ScheduleMinimum.toFixed(2));
            } else if (operation.CleaningMinimum > 0) {
                $('.minimum_type').empty().append('cleaning');
                $('.disclaimer_amount').empty().append(operation.CleaningMinimum.toFixed(2));
            }
        }
    } else {
        $('.portable_disclaimer_generic').show();
        $('.portable_disclaimer_surcharge').hide();
        $('.portable_disclaimer_minimum').hide();
        $('.portable_disclaimer_minimum_amount').hide();
        $('.portable_disclaimer_surcharge_amount').hide();
        $('.surcharge_disclaimer').hide();
        if (operation.ScheduleMinimum > 0) {
            $('.minimum_type').empty().append('job');
            $('.disclaimer_amount').empty().append(operation.ScheduleMinimum.toFixed(2));
        } else if (operation.CleaningMinimum > 0) {
            $('.minimum_type').empty().append('cleaning');
            $('.disclaimer_amount').empty().append(operation.CleaningMinimum.toFixed(2));
        }
    }

   
    if (currentTab == 'duct') {
        $('#portableY').attr('checked', false);
        $('#requires_portable').hide();
        $('.carpet_general_disclaimer').hide();
        $('.carpet_tc').hide();
        $('.tile_grout_square_foot_general_disclaimer').hide();
        $('.tile_grout_square_foot_tc').hide();
        $('.tile_grout_room_general_disclaimer').hide();
        $('.tile_grout_room_tc').hide();
        if (operation.IsAirductPerRoom) {
            $('.air_duct_room_general_disclaimer').show();
            $('.air_duct_room_tc').show();
            $('.air_duct_vent_general_disclaimer').hide();
            $('.air_duct_vent_tc').hide();
        } else {
            $('.air_duct_vent_general_disclaimer').show();
            $('.air_duct_vent_tc').show();
            $('.air_duct_room_general_disclaimer').hide();
            $('.air_duct_room_tc').hide();
        }
    } else if (currentTab == 'tile') {
        $('.carpet_general_disclaimer').hide();
        $('.carpet_tc').hide();
        $('.air_duct_vent_general_disclaimer').hide();
        $('.air_duct_vent_tc').hide();
        $('.air_duct_room_general_disclaimer').hide();
        $('.air_duct_room_tc').hide();
        if (operation.IsTilePerRoom) {
            $('.tile_grout_room_general_disclaimer').show();
            $('.tile_grout_room_tc').show();
            $('.tile_grout_square_foot_general_disclaimer').hide();
            $('.tile_grout_square_foot_tc').hide();
        } else {
            $('.tile_grout_square_foot_general_disclaimer').show();
            $('.tile_grout_square_foot_tc').show();
            $('.tile_grout_room_general_disclaimer').hide();
            $('.tile_grout_room_tc').hide();
        }
    } else { //carpet
        $('.carpet_general_disclaimer').show();
        $('.carpet_tc').show();
        $('.tile_grout_square_foot_general_disclaimer').hide();
        $('.tile_grout_square_foot_tc').hide();
        $('.tile_grout_room_general_disclaimer').hide();
        $('.tile_grout_room_tc').hide();
        $('.air_duct_vent_general_disclaimer').hide();
        $('.air_duct_vent_tc').hide();
        $('.air_duct_room_general_disclaimer').hide();
        $('.air_duct_room_tc').hide();
    }
}

function SetDisclaimers()
{
    var currentTab = $('#current a').attr('id');
    var operation = getOperation();
    
    if (operation == null) return;
      
    if (currentTab == 'duct') {
        $('#portableY').attr('checked', false);
        $('#requires_portable').hide();
        $('.carpet_general_disclaimer').hide();
        $('.carpet_tc').hide();
        $('.tile_grout_square_foot_general_disclaimer').hide();
        $('.tile_grout_square_foot_tc').hide();
        $('.tile_grout_room_general_disclaimer').hide();
        $('.tile_grout_room_tc').hide();
        if (operation.IsAirductPerRoom) {
            $('.air_duct_room_general_disclaimer').show();
            $('.air_duct_room_tc').show();
            $('.air_duct_vent_general_disclaimer').hide();
            $('.air_duct_vent_tc').hide();
        } else {
            $('.air_duct_vent_general_disclaimer').show();
            $('.air_duct_vent_tc').show();
            $('.air_duct_room_general_disclaimer').hide();
            $('.air_duct_room_tc').hide();
        }
    } else if (currentTab == 'tile') {
        $('.carpet_general_disclaimer').hide();
        $('.carpet_tc').hide();
        $('.air_duct_vent_general_disclaimer').hide();
        $('.air_duct_vent_tc').hide();
        $('.air_duct_room_general_disclaimer').hide();
        $('.air_duct_room_tc').hide();
        if (operation.IsTilePerRoom != null && operation.IsTilePerRoom) {
            $('.tile_grout_room_general_disclaimer').show();
            $('.tile_grout_room_tc').show();
            $('.tile_grout_square_foot_general_disclaimer').hide();
            $('.tile_grout_square_foot_tc').hide();
        } else {
            $('.tile_grout_square_foot_general_disclaimer').show();
            $('.tile_grout_square_foot_tc').show();
            $('.tile_grout_room_general_disclaimer').hide();
            $('.tile_grout_room_tc').hide();
        }
    } else { //carpet
        $('.carpet_general_disclaimer').show();
        $('.carpet_tc').show();
        $('.tile_grout_square_foot_general_disclaimer').hide();
        $('.tile_grout_square_foot_tc').hide();
        $('.tile_grout_room_general_disclaimer').hide();
        $('.tile_grout_room_tc').hide();
        $('.air_duct_vent_general_disclaimer').hide();
        $('.air_duct_vent_tc').hide();
        $('.air_duct_room_general_disclaimer').hide();
        $('.air_duct_room_tc').hide();
    }
}


//formats and shows the order minimum message box
function scheduleMinimumMessage(operation, subtotal) {
    if ($('#schedule_now').css('display') === 'none') { return false; }
    if (mimimum_order_message_status === 'closed' || mimimum_order_message_status === 'hide') { return false; }


    var top = $('#quote_body').position().top;
    var left = $('#quote_body').position().left;
    var min;

    //select the apppropriate minimum amount
    if (operation.PortableMinimum > 0 && $('#portableY').attr('checked')) {
        min = operation.PortableMinimum;
        message = '<div class="schedule_min_message" style="display:none;">'
		+ '<p>Your order total of $' + (min - minimum_order_message).toFixed(2) + ' does not meet our required $'
	    + min.toFixed(2) + ' portable minimum.  You may add items to the order, or continue and be charged the minimum portable amount.</p>'
	    + '<div style="font-weight: bold; float:right"><a href="#">OK</a></div></div>';
    } else if (operation.ScheduleMinimum > 0) {
        min = operation.ScheduleMinimum;
        message = '<div class="schedule_min_message" style="display:none;">'
		+ '<p>Your order total of $' + (min - minimum_order_message).toFixed(2) + ' does not meet our required $'
	    + min.toFixed(2) + ' job minimum.  You may add items to the order, or continue and be charged the minimum job amount.</p>'
	    + '<div style="font-weight: bold; float:right"><a href="#">OK</a></div></div>';
    } else {
        min = operation.CleaningMinimum;
        message = '<div class="schedule_min_message" style="display:none;">'
	    + '<p>Your cleaning total of $' + (min - minimum_order_message).toFixed(2) + ' does not meet our required $'
	    + min.toFixed(2) + ' cleaning minimum.  You may add additional cleaning items to the order, or continue and be charged the minimum cleaning amount.'
	    + '</p><div style="font-weight: bold; float:right"><a href="#">OK</a></div></div>';
    }

    //position and show the message
    $('#quote_body').append(message);
    $('.schedule_min_message').css('top', '-1px').css('left', '-1px');
    $('.schedule_min_message').fadeIn();

    //register click event for the message box	
    $('.schedule_min_message a').click(function() {
        $('.schedule_min_message').fadeOut();
        minimum_order_message = false;
        setTimeout(function() { $('.schedule_min_message').remove(); }, 1000);
        mimimum_order_message_status = 'closed';
        return false;
    });
}

function clearInvalidOfferMessage() {
    $('.invalid_offer_message').remove();
}

function setInvalidOfferMessage(offer_line_item) {
    if (offer_line_item.IsOfferValid) {
        clearInvalidOfferMessage();
        return false;
    }

    var top = $('#quote_body').position().top;
    var left = $('#quote_body').position().left;

    message = '<div class="invalid_offer_message" style="display:none;">'
		+ '<p>'
		+ offer_line_item.OfferMessage
		+ '</p>'
	    + '<div><div style="float:left"><a>Revise Order</a></div><div style="font-weight: bold; float:right"><a>Continue Without Special</a></div></div>';

    //position and show the message
    $('#quote_body').append(message);
    $('.invalid_offer_message').css('top', '-1px').css('left', '-1px');

    //register click event for the message box	
    $('.invalid_offer_message a').eq(0).bind('click', function() {
        $('.invalid_offer_message').fadeOut();
        return false;
    });

    $('.invalid_offer_message a').eq(1).bind('click', function() {
        clearInvalidOfferMessage();
        removeSpecial();
        $('#schedule_now').click();
    });
}

function hideLeatherDropdown() {
    // magic sauce
    try {
        var areas_and_services = cache.getItem("AreasAndServices");

        var aas_count = 0;

        for (var aas_item in areas_and_services.LeatherCollection.Areas) {
            aas_count++;
        }

        if (aas_count === 0) {
            $('#leather_selector').hide();
            $('#leather_selection').hide();
            $('#leather_selection + hr').hide();
            $('#current_leather_selection').hide();
        }
    }
    catch (ex) { }

    return false;
}

function hideAutoDropdown() {
    try {
        var areas_and_services = cache.getItem("AreasAndServices");

        var aas_count = 0;

        for (var aas_item in areas_and_services.AutomobileCollection.Areas) {
            aas_count++;
        }

        if (aas_count === 0) {
            $('#automobile_selection').empty();

            if ($('#leather_selection HR').css('display') != 'none') {
                $('#leather_selection HR').css('display', 'none');
            } else {
                if ($('leather_selection').css('display') == 'none') {
                    $('#furniture_selection + HR').css('display', 'none');
                }
            }
        }
    } catch (ex) { }

    return false;
}

//creates a table for a pricing section
function createCostTable(table_type, line_items, amounts) {
    var str = '<div class="quote_div"><table class="quote_table"><colgroup><col width="70%"/><col width="*"/></colgroup>';
    str += '<tr class="line_item"><td colspan="2"><span class="bold">' + table_type + '</span></td></tr>';
    var qty = '';

    for (var i in line_items) {
        if (amounts !== null && amounts !== undefined) {
            if (line_items[i].Description.indexOf('Clean') >= 0) {
                if (table_type === "Tile & Grout" && line_items[i].Amount === 0) {
                    line_items[i].Description = 'In-home Estimate';
                } else {
                    qty = ' - ' + amounts.Clean;
                }
            } else if (line_items[i].Description.indexOf('Protect') >= 0) {
                qty = ' - ' + amounts.Protect;
            } else if (line_items[i].Description.indexOf('Deodorize') >= 0) {
                qty = ' - ' + amounts.Deodorize;
            }
        }
        text = line_items[i].Description + qty
        if (line_items[i].OfferApplyMessage != null && line_items[i].OfferApplyMessage.length > 0) {
            text = line_items[i].Description + qty + '<br/>(' + line_items[i].OfferApplyMessage + ')'
        }
        str += createCostRow(LINE_ITEM, text, line_items[i].Amount);

        qty = "";
    }
    str += '</table></div>';
    return str;
}

//Creates a row in the quote cost section
function createCostRow(row_type, text, value, isSavings) {
    if (value === 0 && row_type === LINE_ITEM) {
        return "<tr class='" + row_type + "'><td class='" + row_type + "_desc'>" + text + "</td><td class='" + row_type + "_value'></td></tr>";
    }
    else if (isSavings) {
        //make the nubmer negative and stuff
    }
    else {
        return "<tr class='" + row_type + "'><td class='" + row_type + "_desc'>" + text + "</td><td class='" + row_type + "_value'>$" + value.toFixed(2) + "</td></tr>";
    }
}

// sets the zip_go button src to the go_button
function resetGoImage() {
    $('#zip_go').attr('src', '/Images/go_button.gif');
}

//Gets the info on the zip code and populates the control
function getZipCode(e) {
    zip = $('#zip_code').val();
    // set go image to wait spinner
    $('#zip_go').attr('src', '/Images/wait.gif');
    $('#add_services').hide();
    $('#total_cost_items').hide();
    $('#requires_portable').hide();
    $('#order_disclaimer_detail').hide();
    $("#quote_body").empty()
	.append('<span id="quote_init">Select areas to be cleaned above or <a href="/">view saved quote</a></span>');
    $('#schedule_now').css('border-top', '0px');

    //check if zip is a valid zip
    //show warning if not
    if (zip.search(/^(\d{5}-\d{4})|(\d{5})$/) == -1) {
        $('#zip_warning_text').empty()
		.append('This zip code is not valid');
        $('#zip_warning').fadeIn('slow');
        resetGoImage();

        return false;
    }

    var old_zip_code = $.cookie(SESSION_GUID, 'zip_code');

    var cookies = {}
    cookies['saved_quote'] = null;
    cookies['timeSlot'] = null;
    cookies['territoryID'] = null;
    cookies['operationID'] = null;
    cookies['confirmationNo'] = null;
    cookies['prices'] = null;
    cookies['current_special'] = null;
    $.setCookieInBulk(SESSION_GUID, cookies, true);

    $('.coupon').empty().hide();

    if ((old_zip_code !== null && old_zip_code !== zip)) {

        if ($('.slideout_panel').css('display') === 'block') {
            hideSlideoutPanel();
        }

        // make warning window visible
        $('#zip_change_warning').show();
        if ($.browser.msie && parseFloat($.browser.version) < 7) {
            $('#zip_change_warning').css({ position: 'absolute', top: '-10px', left: '10px' });
        } else {
            $('#zip_change_warning').css({ position: 'absolute', top: '0px', left: '10px' });
        }

        // activate warning window events
        $('#zip_change_warning .cancel').click(function() {
            $('#zip_change_warning').hide();
            resetGoImage();
            $('#zip_code').val(old_zip_code);
            $.cookie(SESSION_GUID, 'zip_code', $('#zip_code').val(), { path: '/' });
            return false;
        });

        $('#zip_change_warning .ok').unbind().click(function() {

            var cookies = {};
            cookies['saved_quote'] = null;
            cookies['zip_code'] = zip;
            $.setCookieInBulk(SESSION_GUID, cookies, true);

            $('#zip_change_warning').hide();

            // clear out zip code text box
            $('#zip_code').val(zip);

            requestZipCodeInfo(zip);
        });
    } else {
        $.cookie(SESSION_GUID, 'zip_code', zip, { path: '/' });
        requestZipCodeInfo(zip);
    }

    resetGoImage();
    $('.item-0').hide();
}

// this is nuking the order on page reload!
function requestZipCodeInfo(zip_code) {
    var ci = loadCleaningInfo();
    ci.ZipCode = zip_code;
    ci.Save();
    //AjaxManager.Discount.clearActiveDiscount();
    var territoryInfo = AjaxManager.Territory || {};
    territoryInfo.changeZipCode(zip_code);
}

function onGetTerritoryByZipSuccesss() {
    // hide the live chat button by default
    // also, show 'schedule now' if it happens to be hidden (user is on sign in page, for example)
    $('#zip_entry_chat').hide();
    $('#live_chat').hide();
    $('#schedule_now').show();
}

function onNoTerritoryFound(invalidZip) {
    var message = '';
    if (invalidZip) {
        message = 'The zip code you have provided is invalid.';
    } else {
        message = "We're sorry, Stanley Steemer does not provide service in this area.";
    }

    $('#zip_warning_text').empty().append(message);
    $('#zip_warning').fadeIn();
}

function onFoundMultipleTerritories(response) {
    //multiple territories, bring up selection
    $('#franchise_list').empty();
    var franchiseFound = false;
    //Add all available franchise locations to the list
    for (var i = 0; i < response.length; i++) {
        /*
        PARSE FORMAT
        City_County_OperationID_State_TerritoryDescription_TerritoryID_Zip_ZoneCode___type
        spaces in names will be replaced with '-'
        */
        var id = response[i].City + "_" + response[i].County + "_" + response[i].OperationID + "_" + response[i].State + "_" + response[i].TerritoryDescription + "_" + response[i].TerritoryID + "_" + response[i].Zip + "_" + response[i].ZoneCode + "_" + response[i].__type;

        id = id.replace(/ /g, "-");

        $('#franchise_list').append('<div class="franchise">' + '<input type="radio" class="franchise_select" name="franchise" id="' + id + '"/>' + '<span>' + response[i].TerritoryDescription + '</span>' + '</div>');
    }

    if (franchiseFound === false) {
        $('#franchise_selection').bgiframe();
        $('#franchise_selection').fadeIn('slow');
    }
}

//handles succes of zip code request
function onTerritorySuccessResponse(json) {
    //try {
    //	$('#red_X').click();
    //	$('#ffbz_zip_code').val(zip_code);
    //	$('#ffbz_go').click();
    //} catch (ex) {}
    if (response !== undefined) {
    }
    else {

    }
}

function onOperationChanged(operation) {
    // Show the Live Chat button if available for the Operation
    if (operation.IsOnlineChatAvailable) {
        showAndpositionLiveChatButton(operation.OnlineChatURL);
    }

    $('.franchise_address').empty();
    $('.franchise_address').append(common.formatAddress(operation));

    //show disclaimer
    $('#view_disclaimer_container').show();
}

function onAreasAndServicesChanged(serviceList) {
    //throw error if a service is null					
    if (nullOrUndef(serviceList) || nullOrUndef(serviceList.CarpetCollection.Areas) || nullOrUndef(serviceList.UpholsteredCollection.Areas) ||
		nullOrUndef(serviceList.LeatherCollection.Areas) || nullOrUndef(serviceList.AutomobileCollection.Areas) ||
		nullOrUndef(serviceList.TileCollection.Areas) || nullOrUndef(serviceList.AirDuctCollection.Areas)) {
        error_response('1234');
        return;
    }

    //set drop down lists
    var ci = loadCleaningInfo();
    AddCarpetRooms(serviceList.CarpetCollection.Areas, ci);
    AddUpholsteredFurniture(serviceList.UpholsteredCollection.Areas, ci);
    AddLeatherFurniture(serviceList.LeatherCollection.Areas, ci);
    AddAutomobiles(serviceList.AutomobileCollection.Areas, ci);
    AddTile(serviceList.TileCollection.Areas, ci);
    AddAirDuct(serviceList.AirDuctCollection.Areas, ci);
    AddGuaranteedRooms(serviceList.CarpetCollection.Areas, ci);
    AddGSCs();
    resetDropDownDimensions();

    var operation = getOperation();
    var doesAirDuct = operation.DoesAirDuctCleaningOnline && operation.DoesAirDuctCleaning;

    if (ci.isPortable === null) {
        ci.isPortable = getTerritory().IsHighPortableArea;
        ci.Save();
        $('#portableY').attr('checked', ci.isPortable);
    }

    $('.trash_can').unbind().click(removeRow);

    var inSchedule = common.inSchedule();
    //set the current tab
    var current = $('#current');
    if ($(current).attr('class') == 'a_tab') {       
        $('#carpet_tab').hide();
        $('#tile_tab').hide();
        if (doesAirDuct) {
            if (!inSchedule) {
                updateTotal();
            }
        }
    } else {
        //update scheduling tool to reflect progress					
        if (!inSchedule) {
            updateTotal();
        }
    }

    //bind change event for items that may have been cookied
    $(".num").unbind("change")
	.change(updateTotal);

    //Send ClearSaleing information
    ClearSaleing_ZipEntry(operation.OperationID);
}

function showAndpositionLiveChatButton(url) {
    $('#zip_entry_chat').css('height', '0');
    $('#zip_entry_chat').show();
    var left_original = $('#zip_entry_chat').position().left; ;

    //need to show the button to be able to determine image width;
    $('#zip_entry_chat').css('left', '-9999px');
    $('#live_chat').css('left', '-9999px');
    $('#live_chat').show();

    w = $('#create_quote').width();
    t2 = $('#zip_entry').position().top;
    w2 = $('#live_chat').width();

    $('#zip_entry_chat').hide();
    $('#live_chat').hide();

    $('#live_chat').bind('click', function() {
        eval(url.toString());
    });

    $('#live_chat').css({
        'position': 'absolute',
        'left': ((w - w2 - 20) + 'px'),
        'top': ((t2 - 5) + 'px'),
        'z-index': '2050'
    });

    $('#zip_entry_chat').css({
        'height': '8px'
    });
    $('#zip_entry_chat').show();
    $('#live_chat').show();
}

//gets associations for an operations and adds them to the scheduling tool
function displayAssociations(associations) {
    var operation = AjaxManager.Operation.getOperation();

    /*
    ID to association mapping
    1 -	IICRC Association
    2 -	AAA  Association
    3 -	BBB  Association
    5 -	NOFMA  Association
    6 -	NADCA  Association
    7 -	NWFA  Association
    8 - 24Hr Emeregency Water Damage Restoration
    */
    $('#logos').empty().append('<img style="height: 50px;" class="logo" alt="Society of Cleaning and Restoration Technicians" title="Society of Cleaning and Restoration Technicians" src="/Images/logos/g13.gif" />' +
				'<img class="logo" style="height: 50px;" alt="Space Certified Technology" title="Space Certified Technology" src="/Images/logos/Space_Technology.gif" />' +
				'<img class="logo" style="height: 50px;" alt="The Carpet and Rug Institute" title="The Carpet and Rug Institute" src="/Images/logos/cri.gif" />');

    if (associations === null) { return; }

    for (var index = 0; index < associations.length; index++) {
        $('#logos').append('<img style="height: 50px;" class="logo" title="' + associations[index].Description + '" alt="' + associations[index].Description + '" src="/Images/logos/' + associations[index].AssociationID + '.GIF" />');
    }
}

//sets up tabs and services based on the operation
function setServices(operation) {
    var doesCarpet = operation.DoesCarpetCleaningOnline && operation.DoesCarpetCleaning;
    var doesTile = operation.DoesTileCleaningOnline && operation.DoesTileCleaning;
    var doesAirDuct = operation.DoesAirDuctCleaningOnline && operation.DoesAirDuctCleaning;
    var doesGuarantee = operation.DoesGuaranteeOnline;
    var isCheckout = $('#time_blocks').length > 0 || $('#login_table').length > 0
		|| $('#confirmation_items_table').length > 0;
    var isUnassigned = operation.Zip === '99999';
    var currentTab = $.cookie(SESSION_GUID, 'current_tab');

    //Show or hide air duct tab if available			
    if (!doesAirDuct) {
        $('.a_tab').hide();
    } else {
        $('.x_tab').hide();
        $('.a_tab').show();
    }

    //show or hide tile & grout if available
    if (!doesTile) {
        $('#add_tile_link').parent().hide();
        $('.t_tab').hide();
    } else {
        $('.x_tab').hide();
        $('.t_tab').show();
    }

    //show or hide carpet if available
    if (!doesCarpet) {
        $('#add_carpet_link').parent().hide();
        $('.c_tab').hide();
    } else {
        $('.x_tab').hide();
        $('.c_tab').show();
    }

    if (doesGuarantee) {
        var link = $('#CleanGuaranteeLearnMore');
        var url = link.attr('href');
        url += '?zip=' + operation.Zip + '&oid=' + operation.OperationID;
        link.attr('href', url);
        $('.g_tab').show();
        $('.x_tab').hide();
    } else {
        $('.g_tab').hide();

    }

    //check to see if the current tab is sill showing
    if (isUnassigned) { currentTab = 'none'; }
    else if (currentTab === 'carpet' && !doesCarpet) { currentTab = 'none'; }
    else if (currentTab === 'tile' && !doesTile) { currentTab = 'none'; }
    else if (currentTab === 'duct' && !doesAirDuct) { currentTab = 'none'; }
    else if (currentTab === 'guar' && !doesGuarantee) { currentTab = 'none'; }
    else if (currentTab === 'call') { currentTab = 'none'; }
    else if (currentTab === null) { currentTab = 'none'; }

    //show the first available tab
    //if no tab is available
    //if scheduling tool is in the checkout phase, don't continue
    //if zip code is unassigned or no services are available show the call tab
    if (isCheckout && !isUnassigned) {
        return false;
    } else if (currentTab !== 'none') {
        switch (currentTab) {
            case 'carpet': setTimeout('$(".c_tab").click();', 5); break;
            case 'tile': setTimeout('$(".t_tab").click();', 5); break;
            case 'duct': setTimeout('$(".a_tab").click();', 5); break;
        }
    } else if (doesCarpet && !isUnassigned) {
        hideCallTab();
        setTimeout('$(".c_tab").click();', 5);
    } else if (doesTile && !isUnassigned) {
        hideCallTab();
        setTimeout('$(".t_tab").click();', 5);
    } else if (doesAirDuct && !isUnassigned) {
        hideCallTab();
        setTimeout('$(".a_tab").click();', 5);
    } else if (doesGuarantee && !isUnassigned) {
        hideCallTab();
        setTimeout('$(".g_tab").click();', 5);
    }
    else {
        showCallTab();
    }
}

function showCallTab() {
    $('.c_tab').hide();
    $('.t_tab').hide();
    $('.g_tab').hide();
    $('.a_tab').hide();
    $('.x_tab').show();
    setTimeout(function() { $(".x_tab").click(); }, 100);
    $('#quote_section').hide();
    $('#view_disclaimer_container').hide();
    $('#requires_portable').hide();
}

function hideCallTab() {
    $('#quote_section').show();
    $('#view_disclaimer_container').show();
}

//builds list of service/area ids for pricing use
//stors in cookie
function buildIDList(serviceList) {
    if (serviceList === null) {
        return false;
    }

    var carpetIDs = [];
    var upholsteredIDs = [];
    var leatherIDs = [];
    var autoIDs = [];
    var tileIDs = [];
    var ductIDs = [];
    var serviceIDs = [];
    var carpetServices = [];
    var upholsteredServices = [];
    var leatherServices = [];
    var autoServices = [];
    var tileServices = [];
    var ductServices = [];

    //carpet
    for (var i = 0; i < serviceList.CarpetCollection.Areas.length; i++) {
        carpetIDs[i] = {
            AreaID: serviceList.CarpetCollection.Areas[i].AreaID,
            Description: serviceList.CarpetCollection.Areas[i].Description
        };
    }

    for (var i = 0; i < serviceList.CarpetCollection.Services.length; i++) {
        carpetServices[i] = {
            ServiceID: serviceList.CarpetCollection.Services[i].ServiceID,
            Description: serviceList.CarpetCollection.Services[i].Description
        };
    }

    //upholstered
    for (var i = 0; i < serviceList.UpholsteredCollection.Areas.length; i++) {
        upholsteredIDs[i] = {
            AreaID: serviceList.UpholsteredCollection.Areas[i].AreaID,
            Description: serviceList.UpholsteredCollection.Areas[i].Description
        };
    }

    for (var i = 0; i < serviceList.UpholsteredCollection.Services.length; i++) {
        upholsteredServices[i] = {
            ServiceID: serviceList.UpholsteredCollection.Services[i].ServiceID,
            Description: serviceList.UpholsteredCollection.Services[i].Description
        };
    }

    //leather
    for (var i = 0; i < serviceList.LeatherCollection.Areas.length; i++) {
        leatherIDs[i] = {
            AreaID: serviceList.LeatherCollection.Areas[i].AreaID,
            Description: serviceList.LeatherCollection.Areas[i].Description
        };
    }

    for (var i = 0; i < serviceList.LeatherCollection.Services.length; i++) {
        leatherServices[i] = {
            ServiceID: serviceList.LeatherCollection.Services[i].ServiceID,
            Description: serviceList.LeatherCollection.Services[i].Description
        };
    }

    //auto
    for (var i = 0; i < serviceList.AutomobileCollection.Areas.length; i++) {
        autoIDs[i] = {
            AreaID: serviceList.AutomobileCollection.Areas[i].AreaID,
            Description: serviceList.AutomobileCollection.Areas[i].Description
        };
    }
    for (var i = 0; i < serviceList.AutomobileCollection.Services.length; i++) {
        autoServices[i] = {
            ServiceID: serviceList.AutomobileCollection.Services[i].ServiceID,
            Description: serviceList.AutomobileCollection.Services[i].Description
        };
    }

    //tile & grout
    for (var i = 0; i < serviceList.TileCollection.Areas.length; i++) {
        tileIDs[i] = {
            AreaID: serviceList.TileCollection.Areas[i].AreaID,
            Description: serviceList.TileCollection.Areas[i].Description
        };
    }

    for (var i = 0; i < serviceList.TileCollection.Services.length; i++) {
        tileServices[i] = {
            ServiceID: serviceList.TileCollection.Services[i].ServiceID,
            Description: serviceList.TileCollection.Services[i].Description
        };
    }

    //air duct
    for (var i = 0; i < serviceList.AirDuctCollection.Areas.length; i++) {
        ductIDs[i] = {
            AreaID: serviceList.AirDuctCollection.Areas[i].AreaID,
            Description: serviceList.AirDuctCollection.Areas[i].Description
        };
    }

    for (var i = 0; i < serviceList.AirDuctCollection.Services.length; i++) {
        ductServices[i] = {
            ServiceID: serviceList.AirDuctCollection.Services[i].ServiceID,
            Description: serviceList.AirDuctCollection.Services[i].Description
        };
    }

    //assemble final object
    var IDs = {
        CarpetIDs: carpetIDs,
        CarpetServices: carpetServices,
        UpholsteredIDs: upholsteredIDs,
        UpholsteredServices: upholsteredServices,
        LeatherIDs: leatherIDs,
        LeatherServices: leatherServices,
        AutoIDs: autoIDs,
        AutoServices: autoServices,
        TileIDs: tileIDs,
        TileServices: tileServices,
        DuctIDs: ductIDs,
        DuctServices: ductServices
    };

    var s = JSON.stringify(IDs);
    return IDs;
}

function showQuoteLoadGraphic() {
    $('#estimation_section').children().each(function() {
        $(this).children().each(function() {
            $(this).hide();
        });
    });

    $('#estimation_section').prepend('<div id="load_quote" style="margin-left: auto; margin-right: auto;"><img src="Images/wait.gif" /><br />Loading quote info...</div>');
}

function removeQuoteLoadGraphic(XMLHttpRequest, textStatus) {
    $('#estimation_section').children().each(function() {
        $(this).children().each(function() {
            $(this).show();
        });
    });

    $('#load_quote').remove();
    hideLeatherDropdown();
    hideAutoDropdown();
}

//adds list of carpet rooms to the selector
function AddCarpetRooms(rooms, ci) {
    var count = 0;

    for (var i in ci.Carpets.Rooms) {
        if (!ci.Carpets.Rooms[i].isGuaranteed) {
            count++;
        }
    }

    $('#carpet_selection').empty()
	.append('<table id="current_room_selection" class="current_selection">' +
		'<tr><td class="empty_header"></td><td colspan="4" class="header">Enter Quantities' +
		'</td></tr><tr><td class="room_header"><br />Area</td><td class="room_activity">' +
		'<a href="/Home/ResidentialServices/CarpetCleaning.aspx"><img alt="Learn more about this service." title="Learn more about this service." src="/Images/play.gif" style="cursor: pointer;vertical-align:text-bottom;" /></a>' +
		'<br />Clean</td><td class="room_activity">' +
		'<a href="/Home/ResidentialServices/CarpetCleaning/CarpetProtection.aspx"><img alt="Learn more about this service." title="Learn more about this service." src="/Images/play.gif" style="cursor: pointer;vertical-align:text-bottom;" /></a>' +
		'<br />Protect</td><td class="room_activity">' +
		'<a href="/Home/ResidentialServices/CarpetCleaning/CarpetDeodorizer.aspx"><img alt="Learn more about this service." title="Learn more about this service." src="/Images/play.gif" style="cursor: pointer;vertical-align:text-bottom;" /></a>' +
		'<br />Deodorize</td><td class="room_activity"></td></tr></table>' +
		'<select id="carpet_selector" class="selection_option">' +
		'<option value="NA">Select room/area to be cleaned</option></select>');

    if (rooms.length > 0) {
        for (var i = 0; i < rooms.length; i++) {
            $("#carpet_selector").append('<option class="show areaid_3" value="' +
				rooms[i].Description.replace(/ /g, '_').replace(/\//g, '-SLASH-') + '">' +
				rooms[i].Description + '</option>');
        }
    } else {
        $("#carpet_selector").append(EMPTY_OPTION);
    }

    $('#carpet_selector').selectbox();

    $("#carpet_selector").change(function() {
        selectChangeControl("carpet_selector", "current_room_selection", 'carpet');
        $("#requires_portable").slideDown("slow");
    });

    if (count > 0) {
        $('#current_room_selection').show();
        for (var i in ci.Carpets.Rooms) {
            if (!ci.Carpets.Rooms[i].isGuaranteed) {
                var room = ci.Carpets.Rooms[i];
                var quantity = [room.CleanQuantity, room.ProtectQuantity, room.DeodorizeQuantity];
                $('#current_room_selection tbody').append(addNewRow('carpet', room.Name, quantity, carpetMin, carpetMax));
                resetSelector('#carpet_selector', room.Name, room.Name.replace(/ /, '_').replace(/\//g, '-SLASH-'));
            }
        }
    } else {
        $('#current_room_selection').hide();
    }
}

//add the list of upholstred rooms to the selector
function AddUpholsteredFurniture(area, ci) {
    var count = 0;
    for (var i in ci.Carpets.ClothFurniture) {
        count++;
    }

    $('#furniture_selection').empty()
	.append('<table id="current_furniture_selection" class="current_selection">' +
		'<tr><td class="empty_header"></td><td colspan="4" class="header">Enter Quantities</td></tr><tr><td class="room_header">' +
		'<br />Furniture</td><td class="room_activity">' +
		'<a href="/Home/ResidentialServices/FurnitureLanding.aspx"><img alt="Learn more about this service." title="Learn more about this service." src="/Images/play.gif" style="cursor: pointer;vertical-align:text-bottom;" /></a>' +
		'<br />Clean</td><td class="room_activity"><br />Protect</td><td class="room_activity"><br />Deodorize' +
		'</td><td class="room_activity"></td></tr></table><select id="furniture_selector" class="selection_option">' +
		'<option value="NA">Select upholstered furniture to be cleaned</option></select>');

    if (area.length > 0) {
        for (var i = 0; i < area.length; i++) {
            $("#furniture_selector").append('<option class="show areaid_3" value="' +
				area[i].Description.replace(/ /g, '_').replace(/\//g, '-SLASH-') + '">' +
				area[i].Description + '</option>');
        }
    } else {
        $("#furniture_selector").append(EMPTY_OPTION);
    }

    $('#furniture_selector').selectbox();

    $("#furniture_selector").change(function() {
        selectChangeControl("furniture_selector", "current_furniture_selection", 'upholstered');
        $("#requires_portable").slideDown("slow");
    });

    if (count > 0) {
        $('#current_furniture_selection').show();
        for (var i in ci.Carpets.ClothFurniture) {
            var room = ci.Carpets.ClothFurniture[i];
            var quantity = [room.CleanQuantity, room.ProtectQuantity, room.DeodorizeQuantity];
            $('#current_furniture_selection tbody').append(addNewRow('upholstered', room.Name, quantity, carpetMin, carpetMax));

            resetSelector('#furniture_selector', room.Name, room.Name.replace(/ /, '_').replace(/\//g, '-SLASH-'));
        }
    } else {
        $('#current_furniture_selection').hide();
    }
}

//adds list of furniture to the leather selector
function AddLeatherFurniture(area, ci) {
    var count = 0;
    for (var i in ci.Carpets.LeatherFurniture) {
        count++;
    }

    $('#leather_selection').empty().append('<table id="current_leather_selection" class="current_selection">' +
		'<tr><td class="empty_header"></td><td colspan="4" class="header">Enter Quantities</td></tr><tr><td class="room_header">' +
		'<br />Furniture</td><td class="room_activity">' +
		'<a href="/Home/ResidentialServices/LeatherLanding.aspx"><img alt="Learn more about this service." title="Learn more about this service." src="/Images/play.gif" style="cursor: pointer;vertical-align:text-bottom;" /></a>' +
		'<br />Clean</td><td class="room_activity"><br />Protect</td><td style="display: none;" class="room_activity"><br />Moisturize' +
		'</td><td style="width: 6%" class="room_activity"></td></tr></table><select id="leather_selector" class="selection_option">' +
		'<option value="NA">Select leather furniture to be cleaned</option></select><hr />');

    if ($.browser.msie && $.browser.version.search(/8.*/) == -1) {
        $('#schedule_section hr').css('margin-top', '2px')
		.css('margin-bottom', '2px')
		.css('margin-left', '0px')
		.css('width', '275px');
        $('#tab_content').css('margin', '10px 5px 3px 0px');
    } else {
        $('#schedule_section hr').css('margin-top', '10px')
		.css('margin-bottom', '10px')
		.css('margin-left', '0px')
		.css('width', '275px');
        $('#tab_content').css('margin', '10px 5px 10px 0px');
    }

    if (area.length === 0) {
        hideLeatherDropdown();
        return;
    }

    $('#leather_selection').show();
    $('#leather_selection + hr').show();

    for (var i = 0; i < area.length; i++) {
        $("#leather_selector").append('<option class="show" value="' +
			area[i].Description.replace(/ /g, '_').replace(/\//g, '-SLASH-') + '">' +
			area[i].Description + '</option>');
    }

    $('#leather_selector').selectbox();

    $("#leather_selector").change(function() {
        selectChangeControl("leather_selector", "current_leather_selection", 'leather');
        $("#requires_portable").slideDown("slow");
    });

    if (count > 0) {
        $('#current_leather_selection').show();
        for (var i in ci.Carpets.LeatherFurniture) {
            var room = ci.Carpets.LeatherFurniture[i];
            var quantity = [room.CleanQuantity, room.ProtectQuantity, room.DeodorizeQuantity];
            $('#current_leather_selection tbody').append(addNewLeatherRow('leather', room.Name, quantity, leatherMin, leatherMax));

            resetSelector('#leather_selector', room.Name, room.Name.replace(/ /, '_').replace(/\//g, '-SLASH-'));
        }
    } else {
        $('#current_leather_selection').hide();
    }
}

function AddAutomobiles(area, ci) {
    var count = 0;
    for (var i in ci.Carpets.Autos) {
        count++;
    }

    if (area.length === 0) {
        $("#automobile_selector").append(EMPTY_OPTION);
        hideAutoDropdown();
        return;
    }

    $('#automobile_selection').empty()
	.append('<table id="current_automobile_selection" class="current_selection">' +
		'<tr><td style="width: 50%" class="empty_header"></td><td colspan="4" class="header">Enter Quantities</td></tr><tr><td class="room_header">' +
		'<br />Automobile</td><td style="width: 48%" class="room_activity">' +
		'<br />Clean</td><td style="display: none;" class="room_activity"><br />Protect</td><td  style="display: none;" class="room_activity"><br />Deodorize' +
		'</td><td style="width: 6%" class="room_activity"></td></tr></table><select id="automobile_selector" class="selection_option">' +
		'<option value="NA">Select auto interiors to be cleaned</option></select>');

    if (area.length > 0) {
        for (var i = 0; i < area.length; i++) {
            $("#automobile_selector").append('<option class="show areaid_3" value="' +
				area[i].Description.replace(/ /g, '_').replace(/\//g, '-SLASH-') + '">' +
				area[i].Description + '</option>');
        }
    } else {
        // shove it!
    }

    $('#automobile_selector').selectbox();

    $("#automobile_selector").change(function() {
        selectChangeControl("automobile_selector", "current_automobile_selection", 'auto');
        $("#requires_portable").slideDown("slow");
    });

    if (count > 0) {
        for (var i in ci.Carpets.Autos) {
            var room = ci.Carpets.Autos[i];
            var quantity = [room.CleanQuantity, room.ProtectQuantity, room.DeodorizeQuantity];
            $('#current_automobile_selection tbody').append(addNewAutoRow('auto', room.Name, quantity, autoMin, autoMax));

            resetSelector('#automobile_selector', room.Name, room.Name.replace(/ /, '_').replace(/\//g, '-SLASH-'));
        }
    } else {
        $('#current_automobile_selection').hide();
    }
}

function AddTile(area, ci) {
    var count = 0;
    for (var i in ci.Tile.Rooms) {
        count++;
    }
    var Operation = getOperation();
    var byRoom = Operation.IsTilePerRoom;

    if (!byRoom && Operation.TilePrice > 0) {
        $('#tile_description').empty().append('<span class="bold">Tile & grout cleaning is available for $<span id="tile_price">X.XX</span> per square foot. </span>' +
			'<ol><li>Select the areas you would like to have cleaned.</li><li>Click Schedule Now to select a date for a <b>free in-home estimate</b>.</li></ol><hr />');

        $('#tile_price').empty().append(Operation.TilePrice.toFixed(2));
    }

    $('#tile_selection').empty()
	.append('<table id="current_tile_selection" class="current_selection">' +
				'<tr><td class="empty_header"></td><td colspan="3" class="header">Enter Quantities</td></tr><tr><td class="room_header">' +
				'Area</td><td class="room_activity">' +
				'<a href="/Home/ResidentialServices/TileAndGroutLanding.aspx"><img alt="Learn more about this service." title="Learn more about this service." src="/Images/play.gif" style="cursor: pointer;vertical-align:text-bottom;" /></a><br />' +
				'Clean</td><td class="room_activity"></td></tr></table><select id="tile_selector" class="selection_option">' +
				'<option value="NA">Select area/room to be cleaned</option></select>');

    if (area.length > 0) {
        for (var i = 0; i < area.length; i++) {
            $("#tile_selector").append('<option class="show areaid_3" value="' +
				area[i].Description.replace(/ /g, '_').replace(/\//g, '-SLASH-') + '">' +
				area[i].Description + '</option>');
        }
    } else {
        $("#tile_selector").append(EMPTY_OPTION);
    }

    $('#tile_selector').selectbox();

    $("#tile_selector").change(function() {
        selectChangeControl("tile_selector", "current_tile_selection", 'tile');
        $("#requires_portable").slideDown("slow");
    });

    if (count > 0) {
        for (var i in ci.Tile.Rooms) {
            var room = ci.Tile.Rooms[i];
            var quantity = [room.CleanQuantity];
            $('#current_tile_selection tbody').append(addNewRow('tile', room.Name, quantity, tileMin, tileMax));

            resetSelector('#tile_selector', room.Name, room.Name.replace(/ /, '_').replace(/\//g, '-SLASH-'));
        }
    } else {
        $('#current_tile_selection').hide();
    }
}

function AddAirDuct(area, ci) {
    var count = 0;
    var pricing_unit = 'Vents / Returns';
    var selector_description = 'Select # of vents and returns by room';
    var Operation = getOperation();
    var byRoom = Operation.IsAirductPerRoom;
    var ductDescription = '<span class="bold">To schedule, follow these simple steps:</span>';

    if (byRoom) {
        pricing_unit = "";
        selector_description = 'Select room/area';
        ductDescription += '<ol><li>Enter total number of rooms in your <span class="bold">entire</span> home. ';
    } else {
        ductDescription += '<ol><li>Enter total number of vents and returns for <span class="bold">every</span> room in your home. ';
    }
    ductDescription += 'We don\'t clean partial homes or our job wouldn\'t be complete.</li>'
    ductDescription += '<li>Click to answer remaining questions.</li><li>Click the Schedule Now button.</li></ol><hr />';
    $('#duct_description').empty().append(ductDescription);

    for (var i in ci.Ducts.Rooms) {
        count++;
    }

    $('#duct_selection').empty()
	.append('<table id="current_duct_selection" class="current_selection">' +
				'<tr><td class="empty_header"></td><td colspan="2" class="header">Enter Quantities</td></tr>' +
				'<tr><td class="room_header">Area</td><td class="room_activity">' + pricing_unit + '</td><td></td></tr>' +
				'</table><select id="duct_selector" class="selection_option">' +
				'<option value="NA">' + selector_description + '</option></select>');

    if ((area != undefined) && (area.length > 0)) {
        var AirDuctExtra = {
            HVAC: {
                AreaID: 0,
                ServiceID: 0
            },
            Dryer: {
                AreaID: 0,
                ServiceID: 0
            },
            AC: {
                AreaID: 0,
                ServiceID: 0
            }
        };

        for (var i in area) {
            switch (area[i].AreaID) {
                case 60:
                    AirDuctExtra.Dryer.AreaID = area[i].AreaID;
                    break;
                case 48:
                    AirDuctExtra.HVAC.AreaID = area[i].AreaID;
                    break;
                default:
                    $('#duct_selector').append('<option class="show areaid_3" value="' +
						area[i].Description.replace(/ /g, '_').replace(/\//g, '-SLASH-') + '">' +
						area[i].Description + '</option>');
                    break;
            }
        }

        // this "or" portion intends to determine whether it's loading an actual quote or not because this method is called even on new 
        //  attempts to schedule with nothing in them and that is causing the AC button to be unchecked, which we don't want
        if (ci.Ducts.AC || (ci.Ducts.HVACs == 1 && !ci.Ducts.Dryer && count == 0)) {
            $('#AC_yes').attr('checked', true);
        } else {
            $('#AC_yes').attr('checked', false);
        }

        if (ci.Ducts.Dryer) {
            $('#dryer_yes').attr('checked', true);
        } else {
            $('#dryer_yes').attr('checked', false);
        }

        if (ci.Ducts.HVACs >= 0) {
            $('#HVAC_num').val(ci.Ducts.HVACs);
        }

        cache.setItem('airDuctExtra', AirDuctExtra, { expirationAbsolute: null,
            expirationSliding: 3600,
            priority: CachePriority.High
        });
    } else {
        $('#duct_selector').append(EMPTY_OPTION);
    }

    $('#duct_selector').selectbox();
    $('#duct_selector').change(function() {
        selectChangeControl('duct_selector', 'current_duct_selection', 'duct');
    });

    if (count > 0) {
        for (var i in ci.Ducts.Rooms) {
            var room = ci.Ducts.Rooms[i];
            var quantity = [room.Quantity];
            $('#current_duct_selection tbody').append(addNewRow('duct', room.Name, quantity, ductMin, ductMax));

            resetSelector('#duct_selector', room.Name, room.Name.replace(/ /, '_').replace(/\//g, '-SLASH-'));
        }
    } else {
        $('#current_duct_selection').hide();
    }
}

//adds list of carpet rooms to the selector
function AddGuaranteedRooms(rooms, ci) {
    var count = 0;
    for (var i in ci.Carpets.Guarantees) {
        count++;
    }

    if (count > 0) {
        removeSpecial(false);
    }

    $('#guar_selection').empty()
	.append('<table id="current_guar_selection" class="current_selection">' +
		'<tr><td class="empty_header"></td><td colspan="4" class="header">Enter Quantities' +
		'</td></tr><tr><td class="room_header"><br />Area</td><td class="room_activity">' +
		'<a href="/Home/ResidentialServices/CarpetCleaning.aspx"><img alt="Learn more about this service." title="Learn more about this service." src="/Images/play.gif" style="cursor: pointer;vertical-align:text-bottom;" /></a>' +
		'<br />Clean</td><td class="room_activity">' +
		'<a href="/Home/ResidentialServices/CarpetCleaning/CarpetProtection.aspx"><img alt="Learn more about this service." title="Learn more about this service." src="/Images/play.gif" style="cursor: pointer;vertical-align:text-bottom;" /></a>' +
		'<br />Protect</td><td class="room_activity">' +
		'<a href="/Home/ResidentialServices/CarpetCleaning/CarpetDeodorizer.aspx"><img alt="Learn more about this service." title="Learn more about this service." src="/Images/play.gif" style="cursor: pointer;vertical-align:text-bottom;" /></a>' +
		'<br />Deodorize</td><td class="room_activity"></td></tr></table>' +
		'<select id="guar_selector" class="selection_option">' +
		'<option value="NA">Select guarantee room/area to be cleaned</option></select>');

    if (rooms.length > 0) {
        for (var i = 0; i < rooms.length; i++) {
            $("#guar_selector").append('<option class="show areaid_3" value="' +
				rooms[i].Description.replace(/ /g, '_').replace(/\//g, '-SLASH-') + '">' +
				rooms[i].Description + '</option>');
        }
    } else {
        $("#guar_selector").append(EMPTY_OPTION);
        $('#current_guar_selection').css('display', 'none');
    }

    $('#guar_selector').selectbox();

    $("#guar_selector").change(function() {
        selectChangeControl("guar_selector", "current_guar_selection", 'guarantee');
        $("#requires_portable").slideDown("slow");
    });

    if (count > 0) {
        $('#current_guar_selection').show();
        for (var i in ci.Carpets.Guarantees) {
            var room = ci.Carpets.Guarantees[i];
            var quantity = [room.CleanQuantity, room.ProtectQuantity, room.DeodorizeQuantity];
            $('#current_guar_selection tbody').append(addNewGuaranteeRow('guarantee', room.Name, quantity, carpetMin, carpetMax));

            resetSelector('#guar_selector', room.Name, room.Name.replace(/ /, '_').replace(/\//g, '-SLASH-'));
        }
    } else {
        $('#current_guar_selection').hide();
    }
}

//handles the close of the franchise selection box
function franchiseOkClick() {
    var id = $('.franchise_select:checked').attr('id');
    if (id === undefined || id === null) {
        return false;
    }

    $('#franchise_selection').fadeOut('slow');
    var id = id.replace(/-/g, ' ');
    var data = id.split('_');

    /*
    PARSE FORMAT
    City_County_OperationID_State_TerritoryDescription_TerritoryID_Zip_ZoneCode___type
    spaces in names will be replaced with '-'
    */

    //assemble object from the radio buttons id
    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 territoryInfo = AjaxManager.Territory || {};
    territoryInfo.setTerritory(terr);
}

function emptyDropDowns() {
    AddAirDuct([], loadCleaningInfo());
    AddAutomobiles([], loadCleaningInfo());
    AddCarpetRooms([], loadCleaningInfo());
    AddLeatherFurniture([], loadCleaningInfo());
    AddTile([], loadCleaningInfo());
    AddUpholsteredFurniture([], loadCleaningInfo());
    AddGuaranteedRooms([], loadCleaningInfo());
    AddGSCs();

    $('#order_disclaimer_detail').hide();

    resetDropDownDimensions();
}


function quoteControlUnsubscribeToPublishers() {
    var territory = AjaxManager.Territory || {};
    onGetTerritoryByZipSuccesss.unsubscribe(territory.onTerritoryChanged);
    onNoTerritoryFound.unsubscribe(territory.onNoTerritoryFound);

    var operation = AjaxManager.Operation || {};
    error_response.unsubscribe(operation.onError);
    formatDisclaimerMessage.unsubscribe(operation.onOperationChanged);
    onOperationChanged.unsubscribe(operation.onOperationChanged);
    setServices.unsubscribe(operation.onOperationChanged);

    var areasAndServices = AjaxManager.AreasAndServices || {};
    removeQuoteLoadGraphic.unsubscribe(areasAndServices.onComplete);
    error_response.unsubscribe(areasAndServices.onError);
    onAreasAndServicesChanged.unsubscribe(areasAndServices.onAreasAndServicesChanged);

    var association = AjaxManager.Associations || {};
    displayAssociations.unsubscribe(association.onAssociationsChanged);
}

function showHardwoodEstimateSection() {
    var operation = AjaxManager.Operation.getOperation();

    if ((operation !== null && operation !== undefined) &&
        (operation.DoesHardwoodDeepCleaning || operation.DoesHardwoodDeepCleaningOnline)) {
        $('#HardwoodEstimateSection').show();
    } else {
        $('#HardwoodEstimateSection').hide();
    }
}

function quoteControlSubscribeToPublishers() {
    var territory = AjaxManager.Territory || {};
    onGetTerritoryByZipSuccesss.subscribe(territory.onTerritoryChanged);
    onNoTerritoryFound.subscribe(territory.onNoTerritoryFound);
    onGetTerritoryComplete.subscribe(territory.onComplete);

    var operation = AjaxManager.Operation || {};
    error_response.subscribe(operation.onError);
    formatDisclaimerMessage.subscribe(operation.onOperationChanged);
    onOperationChanged.subscribe(operation.onOperationChanged);
    setServices.subscribe(operation.onOperationChanged);

    var areasAndServices = AjaxManager.AreasAndServices || {};
    removeQuoteLoadGraphic.subscribe(areasAndServices.onComplete);
    error_response.subscribe(areasAndServices.onError);
    onAreasAndServicesChanged.subscribe(areasAndServices.onAreasAndServicesChanged);

    var association = AjaxManager.Associations || {};
    displayAssociations.subscribe(association.onAssociationsChanged);



    showHardwoodEstimateSection.subscribe(AjaxManager.Operation.onOperationsRetrieved);
    showHardwoodEstimateSection.subscribe(AjaxManager.Operation.onOperationChanged);

    SchedulingTool.showGuaranteeSlideoutDisclaimer.subscribe(AjaxManager.Estimate.onOrderGuaranteed);
    SchedulingTool.hideGuaranteeSlideoutDisclaimer.subscribe(AjaxManager.Estimate.onOrderNotGuaranteed);
}



function onGetTerritoryComplete() {
    onFoundMultipleTerritories.unsubscribe(AjaxManager.Territory.onMultipleTerritoriesFound);
}

function scheduleNow(e) {
    e.stopPropagation();

    if ($('.invalid_offer_message').length > 0) {
        $('.invalid_offer_message').fadeIn();
        return false;
    }

    if ($.cookie(SESSION_GUID, 'zip_code') === null || $.cookie(SESSION_GUID, 'prices') === null) {
        return false;
    } else {
        var o = getOperation();
        ClearSaleing_ScheduleNow(o.OperationID);
        location.href = "/Home/Schedule.aspx";
    }
}

function loadCleaningInfo() {
    var ci = new CleaningInfo(document, 'saved_quote');
    ci.Load();

    return ci;
}

function resetDropDownDimensions() {
    $('.item-0').hide();
    $('.jquery-selectbox').each(function() {
        $(this).css('width', '273px');
    });
    $('.jquery-selectbox-list').each(function() {
        $(this).css('width', '268px');
        $(this).css('height', '');
    });
}

function nullOrUndef(value) {
    if (value === null || value == undefined) {
        return true;
    }

    return false;
}

function getCurrentTab() {
    var c = $.cookie(SESSION_GUID, 'current_tab');
    var currentTab = "";

    if (c === null) {
        currentTab = '#carpet_tab';
    } else {
        currentTab = '#' + $.cookie(SESSION_GUID, 'current_tab') + '_tab';
    }

    return currentTab;
}

function setActiveTab() {
    $('#schedule_tabs UL LI').each(function() {
        $(this).removeAttr('id')
    });

    // the air duct tab ID is a_tab, not d_tab, but we save 'duct'
    var c = getCurrentTab();
    c = c.replace(/#/, '').substr(0, 1);
    if (c == 'd') {
        c = 'a';
        $('#portableY').attr('checked', false);
        $('#requires_portable').hide();
    }

    var t = '.' + c + '_tab';
    $(t).attr('id', 'current');
}

//handles errors for AJAX calls
function error_response(err, isPricing) {
    var table = $('.tab-bg');
    var top = $('#create_quote').position().top;
    var left = $('#create_quote').position().left;
    var width = $('#create_quote').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', $(table).position().top + $('#schedule_section').position().top)
	.css('left', $(table).position().left + $('#schedule_section').position().left);

    //popup handler
    $('#web_service_warning_ok').click(function() {
        if (isPricing) {
            removeRowByTarget($('.last_update'));
        }
        $('#web_service_warning').remove();
        $('#disable_panel').hide();
    });
}

function clearQuote() {
    $('.schedule_min_message').remove();

    var top = 0; //$('#quote_body').position().top;
    var left = -1; //$('#quote_body').position().left;
    var message = '<div class="schedule_min_message" style="display:none;">'
		+ '<p>Are you sure you want to clear your quote?</p>'
	    + '<div style="font-weight: bold; float:right"><a href="#">NO</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <a href="#">YES</a></div></div>';

    $('#quote_body').append(message);
    $('.schedule_min_message').css('top', top + 'px').css('left', left + 'px');
    $('.schedule_min_message').fadeIn();

    $('.schedule_min_message div a:first').click(function() {
        $('.schedule_min_message').fadeOut('fast', function() {
            $(this).remove();
        });
        return false;
    });

    $('.schedule_min_message div a:last').click(function() {
        var zip = $.cookie(SESSION_GUID, 'zip_code');
        $.cookie(SESSION_GUID, 'current_special', null, { path: '/' });
        var empty = new CleaningInfo(document, 'saved_quote');
        empty.ZipCode = zip;
        empty.Save();
        location.reload();
    });

    return false;
}

/*----------- CLEARSALEING FUNCTIONS --------------------*/

//Gets current session ID
//Creates seesion ID if one is not available
function getSessionID() {
    var x = new Date();
    x = x.getTime();
    var GUID = x + '_' + (1000 * Math.random()).toFixed(5);

    if ($.cookie(SESSION_GUID, 'sessionId') === null) {
        $.cookie(SESSION_GUID, 'sessionId', GUID, { path: '/' });
        return GUID;
    } else return $.cookie(SESSION_GUID, 'sessionId');
}

//Executes after a user has entered their zip code
//Accepts an operationID
function ClearSaleing_ZipEntry(opID) {
    resetClearSaleingVariables();

    csSalesStageCode = 'Closed/Won';
    csOrderType = 'ZipCode Entered';
    csOrderNum = 'ZC-' + getSessionID();
    csCustomerRating = opID.toString();
    csPostalCode = $.cookie(SESSION_GUID, 'zip_code');

    try {
        executeShoppingCart();
        executeTrackerAJAX("edata.js");
    } catch (ex) { }
}

//Executes every time that the quote is updated
//Accepts the line items, subtotal, total, tax, and operationID
function ClearSaleing_PriceUpdate(line_items, subtotal, tax, total, opID) {
    resetClearSaleingVariables();

    csSalesStageCode = 'Closed/Won';
    csOrderType = 'Pricing - CTG';
    csOrderNum = 'CTG-';
    csCustomerRating = opID.toString();
    csPostalCode = $.cookie(SESSION_GUID, 'zip_code');
    csOrderSubTotal = subtotal;
    csTax = tax;
    csOrderTotal = total;
    csIds = [];
    csCodes = [];
    csItems = [];
    csPrice = [];
    csQtys = [];

    if ($.cookie(SESSION_GUID, 'current_tab') == 'duct') {
        csOrderType = 'Pricing - AD';
        csOrderNum = 'AD-';
    }
    csOrderNum += getSessionID();

    buildTrackingArray(line_items.Carpet, 'Carpet');
    buildTrackingArray(line_items.Upholstered, 'Upholstered');
    buildTrackingArray(line_items.Leather, 'Leather');
    buildTrackingArray(line_items.Auto, 'Auto');
    buildTrackingArray(line_items.Tile, 'Tile&Grout');
    buildTrackingArray(line_items.Duct, 'AirDuct');
    buildTrackingArray(line_items.Other, 'Other');

    try {
        executeShoppingCart();
        executeTrackerAJAX("edata.js");
    } catch (ex) { }
}

function buildTrackingArray(group, type) {
    for (var i in group) {
        csIds.push(type + ' - ' + group[i].Description);
        csCodes.push(type + ' - ' + group[i].Description);
        csItems.push(type + ' - ' + group[i].Description);
        csPrice.push(group[i].Amount.toString());
        csQtys.push('1')
    }
}

//Called when user clicks "schedule now"
//accepts operationID
function ClearSaleing_ScheduleNow(opID) {
    resetClearSaleingVariables();

    csSalesStageCode = 'Closed/Won';

    if ($.cookie(SESSION_GUID, 'current_tab') == 'duct') {
        csOrderType = 'Schedule - AD';
    } else csOrderType = 'Schedule - CTG';

    csOrderNum = 'SCH-' + getSessionID();
    csCustomerRating = opID.toString();
    csPostalCode = $.cookie(SESSION_GUID, 'zip_code');

    try {
        executeShoppingCart();
        executeTrackerAJAX("edata.js");
    } catch (ex) { }
}

//Resets all global scoped functions used in ClearSaleing functions
function resetClearSaleingVariables() {
    csSalesStageCode = undefined;
    csOrderType = undefined;
    csOrderNum = undefined;
    csCustomerRating = undefined;
    csPostalCode = undefined;
    csOrderSubTotal = undefined;
    csTax = undefined;
    csOrderTotal = undefined;
    csIds = undefined;
    csCodes = undefined;
    csItems = undefined;
    csPrice = undefined;
    csQtys = undefined;
    csCity = undefined;
    csState = undefined;
}

function getTerritory() {
    var territory = AjaxManager.Territory || {};
    return territory.getTerritory();
}

function getOperation() {
    var operation = AjaxManager.Operation || {};
    return operation.getOperation();
}

function getAreasAndServices() {
    var areasAndServices = AjaxManager.AreasAndServices || {};
    return areasAndServices.getAreasAndServices();
}

var SchedulingTool = {};

SchedulingTool.removeGuarantee = function(id) {
    var section = $('#guar_section_' + id);

    section.slideUp(500, function() {
        section.remove();
        updateTotal();
    });
}

SchedulingTool.addGuarantee = function(guar, tabSwitch, renewed) {
    var parent = $('#guarantee_section');
    var isChecked = renewed || AjaxManager.Guarantee.active[guar.Id].isRenewed;
    var container = new div('', 'guarantee_section', 'guar_section_' + guar.Id);
    var html = '';
    var headerRow = new row();
    var tr = new row('', 'room gsc');
    var tb = new table('', 'current_selection');
    var count = guar.OrderDetails.length;
    var currentOp = AjaxManager.Operation.getOperation();

    //build header
    html += container.begin();
    html += tb.begin();
    html += headerRow.begin();
    html += cell('', null, 'empty_header');
    html += cell('Enter Quantities', 4, 'header');
    html += headerRow.end();

    //build services
    html += headerRow.begin();
    html += cell('AREA', null, 'room_header');
    html += cell('Clean', null, 'room_activity');
    html += cell('Protect', null, 'room_activity');
    html += cell('Deodorize', null, 'room_activity');
    html += cell('', null, 'room_activity');
    html += headerRow.end();

    var cleaningInfo = loadCleaningInfo();

    //build areas
    for (var i in guar.OrderDetails) {
        var area = guar.OrderDetails[i];
        var qty = area.Quantity;
        var cleanID = "gsc_" + area.AreaDescription.replace(/[\s\/]/g, '') + "_1_3";
        var protectID = "gsc_" + area.AreaDescription.replace(/[\s\/]/g, '') + "_2_3";
        var deodorizeID = "gsc_" + area.AreaDescription.replace(/[\s\/]/g, '') + "_3_3";

        html += tr.begin();
        html += cell('<span style="padding-left:5px;">' + area.AreaDescription + '</span>');
        html += cell(createQuantityDropdown(cleanID, qty, qty, qty, false), null, 'room_quantity');
        html += cell(createQuantityDropdown(protectID, 0, qty, 0, true), null, 'room_quantity');
        html += cell(createQuantityDropdown(deodorizeID, 0, qty, 0, true), null, 'room_quantity');
        if (i == 0) {
            html += cell('<img class="gtrash_can last_update gsc" title="Remove" '
                + 'alt="Remove" src="/Images/trashcan.gif"/>', null, 'room_quantity', null, count);
        }
        html += tr.end();
    }

    html += tb.end();
    if ($.browser.msie) {
        html += '<hr />';

    } else {
        html += '<hr style="margin-top: 10px; margin-bottom: 10px; margin-left: 0px; width: 275px;"/>';
    }
    html += container.end();

    parent.append(html);
    $('.gtrash_can').click(function() {
        AjaxManager.Guarantee.deactivate(guar.Id);
        SchedulingTool.removeGuarantee(guar.Id);

        if (!AjaxManager.Guarantee.hasActive()) {
            AjaxManager.Estimate.publishOrderNotGuaranteed();
        }
    });

    AjaxManager.Estimate.publishOrderGuaranteed();
    parent.hide();

    if (guar.RemainingCleanings == 1) {
        SchedulingTool.addGuaranteeRenewal(guar, isChecked);
    }

    parent.slideDown(500, function() {
        updateTotal();
    });

    $('#guar').click();
}

SchedulingTool.addGuaranteeRenewal = function(guar, checked) {
    var sectionID = '#guar_section_' + guar.Id;
    var section = $(sectionID);
    var table = section.children("table");
    var isChecked = checked || false;
    var checkbox = $('<input type="checkbox" class="renewal" id="chk_renew_' + guar.Id + '" />');
    var label = $('<label for="chk_renew_' + guar.Id + '"> Renew this guarantee</label>');
    var newRow = $(row());
    var content = $(cell('', 5));

    checkbox.attr('checked', isChecked);
    checkbox.change(function() { updateTotal(); });
    content.append(checkbox);
    content.append(label);
    newRow.append(content);
    table.append(newRow);
}

SchedulingTool.changeLocation = function(zip, operation) {
    requestZipCodeInfo(zip);
}

SchedulingTool.setZipCodeBox = function(zip) {
    $('#zip_code').val(zip);
}

SchedulingTool.ClearOrder = function() {
    var ci = new CleaningInfo();
    ci.Save();
}

SchedulingTool.updateTotal = function(reset) {
    updateTotal(reset);
}

SchedulingTool.loadCleaningInfo = function() {
    return loadCleaningInfo();
}

SchedulingTool.buildRealTimeQuote = function() {
    var op = AjaxManager.Operation.getOperation();
    return buildRealTimeQuote(op);
}

SchedulingTool.showGuaranteeSlideoutDisclaimer = function() {
    $('.specials_items_container').hide();
    $('.slideout_panel_guarantee_content').show();
}

SchedulingTool.hideGuaranteeSlideoutDisclaimer = function() {
    $('.specials_items_container').show();
    $('.slideout_panel_guarantee_content').hide();
}

SchedulingTool.checkHardwoodEstimate = function() {
    var checkbox = $('#HardwoodEstimate');
    var status = checkbox.attr('checked');
    var ci = loadCleaningInfo();

    checkbox.attr('checked', !status);
    ci.HardwoodEstimate = !ci.HardwoodEstimate;
    ci.Save();

    updateTotal();
}

function AddGSCs() {
    AjaxManager.Guarantee.addGSCs();
    updateTotal();
}

SchedulingTool.disableSchedulingTool = function() {
    $('#schedule_tabs UL LI').each(function() {
        $(this).unbind().click(function() { return false; })
    });

    $('#estimation_section').hide();
    $('#requires_portable').hide();
    $('#schedule_section hr').css('visibility', 'hidden');
    $('#schedule_now').hide();
    $('#remove_special').hide();
    $('#zip_entry .go').hide();
    $('#view_specials').hide();
    $('#view_specials_open').hide();
    $('#zip_entry .zip').attr('disabled', 'disabled');
    $('#zip_entry .zip').css('cursor', 'default');
    $('.save_quote').parent().hide();
    $('#add_tile_link').parent().hide();
    $('#what_is_included_link').parent().hide();
    $('#clear_quote').parent().hide();
    $('#requires_portable').hide();
    $('#HardwoodEstimateSection').hide();

    if ($.browser.msie && parseFloat($.browser.version) < 7) {
        try {
            $('#content_pane').css('width', '630px');
            $('#content_pane').css('margin-left', '10px');
            $('.grid_11 UL.global_links li').css('padding', '0 4px');
            $('.confirm_header_info').css('width', '630px');
            $('#registration_block').css('width', '630px');
            $('#grid_11 confirmBox').css('width', '630px');
            $('#grid_11').css('width', '630px');
            $('.container_16 .grid_11').css('width', '630px');
            $('#confirm_email_contents').css('width', '630px');
            $('.service_section_menu').css('width', '640px');
        }
        catch (ex) { }
    }
}


//move to extensions.js
function isNullOrUndefined(val) {
    return (val === undefined) || (val === null);
}
