﻿/// <reference path="jquery-1.2.6-vsdoc.js" />

var months = [
	'January', 'February', 
	'March', 'April', 
	'May', 'June', 
	'July', 'August', 
	'September', 'October', 
	'November', 'December' ];

var week = [
	'Sunday','Monday', 'Tuesday',
	'Wednesday', 'Thursday',
	'Friday', 'Saturday'];

var ROW_BEGIN = '<tr><td class="table_left indent" colspan="2">';
var ROW_END = '</td><td class="table_right"></td></tr>';

$(document).ready(function() {
   // $('.landing_content_container').css('height', 'auto !important');

    if ($('#confirmation_number').length >= 1) {
        subscribeToPublishers();
        SchedulingTool.disableSchedulingTool();
        setCouponText(loadCleaningInfo());
        confirmationSubscribeToPublishers();
    }
});

function subscribeToPublishers() {
    bindTotals.subscribe(AjaxManager.Estimate.onUpdateTotal);
    SchedulingTool.updateTotal.subscribe(AjaxManager.AreasAndServices.onComplete);
}


function confirmationSubscribeToPublishers(){
	initRealTimeQuote.subscribe(AjaxManager.AreasAndServices.onComplete);
}


function initRealTimeQuote(){
	buildRealTimeQuote(AjaxManager.Operation.getOperation());
	execute_confirmation();
	
	//we're done with the order so clear it out to get ready for starting over.
	var ci = new CleaningInfo(document, 'saved_quote');
	ci.ZipCode = $('#zip_code').val();
	ci.Save();
}

function hideControlsForConfirmation(){
	$('#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();
		
	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) { }
	}
}
function execute_confirmation() {
	if (AjaxManager.Customer.getAccount().getSelectedAddress() !== null && $.cookie(SESSION_GUID, 'saved_quote') !== null && $.cookie(SESSION_GUID, 'timeSlot') !== null && $.cookie(SESSION_GUID, 'prices') !== null) {
		// erase cookie indicating that the user is in the scheduling tool.
		// This will force the previous pages to redirect the user to the home page.
		// TODO: an error message needs to be added
		
		//throw new Error("Account Changed", "this needs updated because of changes to the account");

	    hideControlsForConfirmation();
		dataBind();
		
		var quoteInfo = JSON.parse($.cookie(SESSION_GUID, 'saved_quote'));
		var customerInfo = AjaxManager.Customer.getAccount().getSelectedAddress();
		
		var timeSlot = $.cookie(SESSION_GUID, 'timeSlot').split('_');
		var special = $.cookie(SESSION_GUID, 'current_special');

		//fill out pricing information
		line_items = JSON.parse($.cookie(SESSION_GUID, 'prices'));
		var tax = 0;
		var subtotal = 0;
		var total = 0;
		var savings = 0;

		var line_item_groups = {
			Carpet:			[],
			Upholstered:	[],
			Leather:		[],
			Auto:			[],
			Tile:			[],
			Duct:			[],
			Other:          [],
			Savings:        [],
			Tax:			null,
			Subtotal:		0        };

        var actions = {};
		
		var hasCarpet = false;
		var hasTile = false;
		var hasAirDuct = false;
		
		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 offerApplyMessage = line_items.SummaryInfoDetails[i].OfferApplyMessage;
			var line_item = {
				Amount: amount, 
				Description: description,
				OfferApplyMessage: offerApplyMessage
			};
			
			switch (serviceTypeID) {
			    case 1:
			        line_item_groups.Carpet.push(line_item);
			        hasCarpet = true;
			        actions['Carpet_' + line_item.Description.substring(line_item.Description.lastIndexOf(' ') + 1)] = line_item.Description;
			        break;
				case 2: 
					line_item_groups.Upholstered.push(line_item);
					hasCarpet = true;
					actions['Upholstered_' + line_item.Description.substring(line_item.Description.lastIndexOf(' ') + 1)] = line_item.Description;
					break;
				case 9: 
					line_item_groups.Leather.push(line_item);
					hasCarpet = true;
					actions['Leather_' + line_item.Description.substring(line_item.Description.lastIndexOf(' ') + 1)] = line_item.Description;
					break;
				case 3: 
					line_item_groups.Tile.push(line_item);
					hasTile = true;
					actions['Tile_' + line_item.Description.substring(line_item.Description.lastIndexOf(' ') + 1)] = line_item.Description;
					break;
				case 7: 
					line_item_groups.Auto.push(line_item);
					hasCarpet = true;
					actions['Auto_' + line_item.Description.substring(line_item.Description.lastIndexOf(' ') + 1)] = line_item.Description;
					break;
				case 4: 
					line_item_groups.Duct.push(line_item);
					hasAirDuct = true;
					actions['Duct_' + line_item.Description.substring(line_item.Description.lastIndexOf(' ') + 1)] = line_item.Description;
					break;
				case -2: case -3: case -4: case -5:
					line_item_groups.Other.push(line_item);
					break;
				case -1:
					line_item_groups.Tax = line_item;
					break;
	            case -6:
	                line_item_groups.Savings.push(line_item);
	                break;
			}
			
			if (serviceTypeID != -1) {
				line_item_groups.Subtotal += line_item.Amount;
			}
		}

		var operation = AjaxManager.Operation.getOperation();
		formatDisclaimerMessage(operation);

		// determine which terms & conditions the user sees in their confirmation screen and email
		// can't just blindly copy them because, for example, user could go to checkout from T&G tab even though they only have carpet in cart
		$('#confirm_tc').empty();
		if (hasCarpet) {
			$('#confirm_tc').append($('.carpet_tc').html());
			if (hasTile) {
				// the order spans tabs, need to jump through some hoops to meld both carpet and tile T&C without showing duplicate blurbs
				if (operation.IsTilePerRoom) {
					$('#confirm_tc .duplicate_to_carpet').hide();
					$('#confirm_tc').append($('.tile_grout_room_tc').html());
				} else {
					$('#confirm_tc').append($('.tile_grout_square_foot_tc').html());
				}
			}
		} else if (hasTile) {
			if (operation.IsTilePerRoom) {
				$('#confirm_tc').append($('.tile_grout_room_tc').html());
			} else {
				$('#confirm_tc').append($('.tile_grout_square_foot_tc').html());
			}		
		} else if (hasAirDuct) {
			if (operation.IsAirductPerRoom) {
				$('#confirm_tc').append($('.air_duct_room_tc').html());
			} else {
				$('#confirm_tc').append($('.air_duct_vent_tc').html());
			}
		}
		// now add the t&c common to all services
		$('#confirm_tc').append($('.common_tc').html());
		$('#confirm_tc span:hidden').remove();

		if (!operation.ConfirmsAppointmentsByPhone) {
		    $('#schedule_confirmation_call').hide();
		} 

		var firstTable = true;
		
		var quantities = JSON.parse($.cookie(SESSION_GUID, 'quantities'));
		
		subtotal = line_item_groups.Subtotal;
		tax = line_item_groups.Tax.Amount;
		total = subtotal + tax;

	    //add totals section
	    total = tax + subtotal;
				
		$('#confirm_print').click(function() {
			window.print();
			return false;
		});
	}

	/* CLEARSALEING */	
	ClearSaleing_ScheduleConfirmation(line_item_groups, operation.OperationID, customerInfo.City, 
		customerInfo.State, customerInfo.Zip, $.cookie(SESSION_GUID, 'confirmationNo'), subtotal, tax, total); 
	/****************/
	
	//clear quote information
	var ci = loadCleaningInfo();
	ci.ClearOrder(true, true, true);
	ci.Save();

	var cookies = {};
	cookies['current_special'] = null;
	cookies['current_tab'] = null;
	$.setCookieInBulk(SESSION_GUID, cookies, true);

	AjaxManager.Discount.clearActiveDiscount();
	AjaxManager.Guarantee.clear();

	// Write accepted credit cards list
	var acceptedCC = '';
	if (operation.AcceptsAmericanExpress){
	    acceptedCC += '&nbsp;&nbsp;American Express<br/>';
    }
    if (operation.AcceptsDiscover){
	    acceptedCC += '&nbsp;&nbsp;Discover Card<br/>';
    }
    if (operation.AcceptsMasterCard){
	    acceptedCC += '&nbsp;&nbsp;MasterCard<br/>';
    }
    if (operation.AcceptsVisa){
	    acceptedCC += '&nbsp;&nbsp;Visa<br/>';
    }
    // Replace the span tag text
    $('#accepted_credit_cards').empty().append(acceptedCC);

    resizeSidebar();
    readyForPrinting();
}

function readyForPrinting()
{
//	var registrationBlock =$('.registration_block').html();
//	$('body').contents().each(function(){
//		$(this).addClass('no_print');
//	});
//	
//	$('body').append("<div id='print_target' class='print'>" + registrationBlock.replace(/PRINT/, '') + "</div>");
}

function AddPriceSection(type, group, amounts) {
	AddDescriptionRow(type);
	var qty = ' - 0';
	
	for (var i in group) {
	    if (amounts !== null) {
	        if (group[i].Description.toLowerCase().indexOf('clean') >= 0) {
	            if (type === "TILE & GROUT" && group[i].Amount === 0) {
	                group[i].Description = 'In-home Estimate';
	            } else {
	                qty = ' - ' + amounts.Clean;
	            }
	        } else if (group[i].Description.toLowerCase().indexOf('protect') >= 0) {
	            qty = ' - ' + amounts.Protect;
	        } else if (group[i].Description.toLowerCase().indexOf('deodorize') >= 0 || group[i].Description.toLowerCase().indexOf('moisturize') >= 0) {
	            qty = ' - ' + amounts.Deodorize;
	        } else {
	            qty = ' - 0';
	        }
		}
		AddPriceRow(group[i], qty);
	}
	GetLastRow().after('<tr><td class="table_left confirm_spacer"  colspan="2"></td><td class="table_right"></td></tr>');
}

function AddPriceRow(item, qty) {
	text = item.Description + qty
	if(item.OfferApplyMessage != null && item.OfferApplyMessage.length > 0){
		text = item.Description + qty + '<br/>(' + item.OfferApplyMessage  + ')'
	}
		
	if (item.Amount === 0) {
		GetLastRow().after('<tr><td class="table_left indent">' + text + '</td><td class="confirm_price">'
			+ '</td><td class="table_right"></td></tr>');
	} else {
		GetLastRow().after('<tr><td class="table_left indent">' + text + '</td><td class="confirm_price">$'
			+ item.Amount.toFixed(2) +'</td><td class="table_right"></td></tr>');
	}
}

function AddDescriptionRow(type) {
	GetLastRow().after('<tr><td class="table_left">' + type + '</td><td></td><td class="table_right"></td></tr>');
}

function GetLastRow() {
	return $('#confirm_table tr:last').prev();
}

/* ------ ClEARSALEING FUNCTIONS ------ */
function ClearSaleing_ScheduleConfirmation(line_items, opID, city, state, zip, confirmNum, subtotal, tax, total) {
		
	resetClearSaleingVariables();
	
	csSalesStageCode = 'Closed/Won';
	csOrderNum = 'CTG-';

	if ($.cookie(SESSION_GUID, 'current_tab') == 'duct') {
		csOrderType = 'Online Order - AD';
		csOrderNum = 'AD-';
	} else {
		csOrderType = 'Online Order - CTG';	
	}

	csOrderNum += confirmNum;	
	csCustomerRating = opID.toString();
	csPostalCode = zip;
	csCity = city;		
	csState = state;	
	csOrderSubTotal = subtotal;			
	csTax = tax;				
	csOrderTotal = total;
	
	csIds = [];
	csCodes = [];
	csItems = [];
	csPrice = [];
	csQtys = [];

	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){}
}

//bind order review information
function dataBind() {
    $('#confirmation_number').empty().append($.cookie(SESSION_GUID, 'confirmationNo'));
    bindSpecialRequests();
    bindOrderInfo();
    bindAddress();
    bindArrival();
}

//binds special request information, hides the section if none exist
function bindSpecialRequests() {
    var requests = $.cookie(SESSION_GUID, 'specialRequests');
    if (requests === null || requests === undefined || requests === '') {
        $('#SpecialRequestSection').hide();
    } else {
        $('#SpecialRequests').text(requests);
    } 
}

//bind quote information
function bindOrderInfo() {
    bindSummary();
    bindDetails();
}

//binds order summary information
function bindSummary() {
    var summaryInfo = OrderUtility.getSummary();
    var summarySection = $('#SummarySection');

    for (var i in summaryInfo.OrderSummaryGroups) {
        var group = summaryInfo.OrderSummaryGroups[i];
        if (group.Id != -1) {
            summarySection.appendLine(group.Name);
            for (var j in group.Items) {
                var item = group.Items[j];
                summarySection.appendLine(item.Description + ' ' + item.Amount.toMoney());
            }
        }
    }
}

//binds order detail information
function bindDetails() {
    var orderDetails = OrderUtility.getDetails();
    var detailSection = $('#DetailSection');

    for (var i in orderDetails) {
        detailSection.appendLine(orderDetails[i].toReviewPageString());
    }
}

//binds order total information
function bindTotals() {
    var totalsSection = $('#TotalsSection');
    var totals = OrderUtility.getTotals();
    var html = '';
    var tb = new table();
    var tr = new row();

    html += tb.begin(); 
    if (totals.savings != 0) {
        html += row(cell('<strong>Savings</strong>') + cell(totals.savings.toMoney()) + cell());
    }
    html += row(cell('<strong>Subtotal</strong>') + cell((totals.subtotal + totals.savings).toMoney()) + cell());
    html += row(cell('<strong>Tax</strong>') + cell(totals.tax.toMoney()) + cell());
   
    html += row(cell('<strong>Total</strong>') + cell(totals.total.toMoney()) + cell());
    html += tb.end();

    totalsSection.empty();
    totalsSection.append(html);
}

//binds order address information
function bindAddress() {
    var account = AjaxManager.Customer.getAccount();
    var customerInfo = account.getSelectedAddress();
    var addressSection = $('#AddressSection');

    with (addressSection) {
        appendLine(customerInfo.FirstName + ' ' + customerInfo.LastName);
        appendLine(customerInfo.AddressLineOne);
        if (customerInfo.AddressLineTwo !== "" && customerInfo.AddressLineTwo !== null) {
            appendLine(customerInfo.AddressLineTwo);
        }
        appendLine(customerInfo.City + ", " + customerInfo.State + " " + customerInfo.Zip);
        appendLine(customerInfo.PhoneNumberOne.toPhone());
        if (customerInfo.PhoneNumberTwo !== null && customerInfo.PhoneNumberTwo !== undefined) {
            appendLine(customerInfo.PhoneNumberTwo.toPhone());
        }
    }
}

//binds order arrival window information
function bindArrival() {
    var timeSlot = $.cookie(SESSION_GUID, 'timeSlot').split('_');
    var arrivalSection = $('#ArrivalSection');
    var arrivalDate = new Date(parseInt(timeSlot[0], 10));
    var arriavlDateString = week[arrivalDate.getDay()] + ', '
                + months[arrivalDate.getMonth()] + ' '
                + arrivalDate.getDate();

    arrivalSection.appendLine(arriavlDateString);
    arrivalSection.appendLine(timeSlot[1]);
}
