﻿$(document).ready(function(){
	//register click handlers
	$('#save_quote').click(save_quote);
	$('#save_quote_find').click(view_saved_quote);
		
	//register handler for enter key
	$('.save_quote_email input').keydown(function(e){
	    var charCode = e.which ? e.which : e.keyCode;
		if (charCode == 13) {
			    return false;
			} else {
				return true;
			}
	});

	//register cancel handler
	$('#save_quote_cancel').click(function(){
		window.location = '/Home.aspx';
	});

});

function saveQuoteSubscribeToPublishers(){
	var areasAndServices = AjaxManager.AreasAndServices || {};
	onSaveQuoteAreasAndServicesChanged.subscribe(areasAndServices.onAreasAndServicesChanged);
	error_response.subscribe(areasAndServices.onError);
}

function saveQuoteUnsubscribeToPublishers(){
	var areasAndServices = AjaxManager.AreasAndServices || {};
	onSaveQuoteAreasAndServicesChanged.unsubscribe(areasAndServices.onAreasAndServicesChanged);
	error_response.unsubscribe(areasAndServices.onError);
}

//Saves quote using web service
function save_quote(){
	var email = $('.save_quote_email input:first').val();
	
	if (email === '') {
		return false;
	}
	
	if (!(checkEmail(email))){
		$('.save_quote_email input:first').parent().parent().after('<tr><td style="font-style: italic; padding: 5px; color: #ff0000;" colspan=3>'
		+ 'This email address is not valid. Please enter an email address containing @.  '
		+ '</td></tr>');
	    return false;
	}
	
	var orderInfo = updateTotal('return');
	
	if ($('#AC_yes').attr('checked')) {
		orderInfo.items.push({
			LineID:	   -1, 
			Quantity:	1, 
			AreaID:		0, 
			ServiceID:	0
		});
	}
	
	if(orderInfo.isPortableJob === true){
		orderInfo.items.push({
			LineID:		-3,
			Quantity:	1,
			AreaID:		0,
			ServiceID:	0
		});
	}
	
	var save_quote_request = JSON.stringify({ 
		EmailAddress:	email, 
		Order:	{ Territory: orderInfo.territory, OrderDetails: orderInfo.items }
	});
	var save_quote_response;

	$('#save_quote_error').fadeOut();
	$.ajax({
		url: '/Service.asmx/SaveQuote',
		type: 'POST',
		datatype: 'json',
		timeout: 10000,
		data: save_quote_request,
		contentType: 'application/json; charset=utf-8',
		success: function(res) {
			save_quote_response = JSON.parse(res);
			
			if (save_quote_response) {
				$('#save_quote_email_entry').fadeOut('fast', function(){
					$('#save_quote_thank_you').fadeIn('fast');
				});
				
				var o = AjaxManager.Operation.getOperation();
				ClearSaleing_SaveQuote(o.OperationID);
			} else {
				$('#save_quote_error_email').empty().append(email);
				$('#save_quote_error').fadeIn();
			}	
		},
		error: error_response
	}); 
	
	return false; //prevent default action
}

//Calls web service to retrieve quote information
//builds save_quote cookie from that and territory/operation/service information
//refreshes page to force scheduling tool to refresh
function view_saved_quote(){
	var email = $('.save_quote_email input:first').val().replace(/(<([^>]+)>)/g,"");
	if (email === '') {
		return false;
	}
	
	$('#save_quote_wait').fadeIn();

	var get_saved_quote_request = JSON.stringify({ EmailAddress: email });
	var get_saved_quote_response;

	$('#save_quote_error').fadeOut();

	//get saved quote information
	$.ajax({
		url: '/Service.asmx/GetSavedQuote',
		type: 'POST',
		datatype: 'json',
		timeout: 10000,
		data: get_saved_quote_request,
		contentType: 'application/json; charset=utf-8',
		success: function(res) {
			get_saved_quote_response = JSON.parse(res);
			//email address was not recognized
			if (get_saved_quote_response === null || res == 'null'){
				$('#save_quote_error_email').empty().append(email);
				$('#save_quote_wait').fadeOut();
				$('#save_quote_error').fadeIn();
			} 
			//successful retrieval of saved quote information
			else {
				cache.setItem('SavedQuoteItems', get_saved_quote_response, { expirationAbsolute: null,
					expirationSliding: 3600,
					priority: CachePriority.High
				});
				//since we're only setting the data and then redirecting temporarliy unsubscribe the quote tool.
				quoteControlUnsubscribeToPublishers();
				saveQuoteSubscribeToPublishers();
				var territoryManager = AjaxManager.Territory || {};
				territoryManager.setTerritory(get_saved_quote_response.Territory);
			}
		},
		error: error_response
	}); 
	
	return false; //prevent default action
}
function onSaveQuoteAreasAndServicesChanged(areasAndServices){
	saveQuoteUnsubscribeToPublishers();
	quoteControlSubscribeToPublishers();
	ids = buildIDList(areasAndServices);
	rebuildQuote(ids, cache.getItem('SavedQuoteItems'));
		
	$('#save_quote_wait').fadeOut();
						
	//refresh page to make changes to saved_quote take effect
	window.location = "/Home/ViewSavedQuoteThankYou.aspx";
}

function rebuildQuote(ids, items) {
	var ci = new CleaningInfo(document, 'saved_quote');
	ci.ZipCode = items.Territory.Zip;
	$.cookie(SESSION_GUID, 'current_tab', 'carpet', {path: '/'});

	//check each item against areas and services to rebuild it
	for (var i in items.OrderDetails) {
		var found = false;
		var item = items.OrderDetails[i];
		
		if (item.LineID == -1) {
			ci.Ducts.AC = true;
		}
		
		if(item.LineID == -3){
			ci.isPortable = true;
		}
		
		//run the item through each service
		ci = rebuildService(item, ids, 'Carpet', ci);
		ci = rebuildService(item, ids, 'Upholstered', ci);
		ci = rebuildService(item, ids, 'Leather', ci);
		ci = rebuildService(item, ids, 'Auto', ci);
		ci = rebuildService(item, ids, 'Tile', ci);	
		ci = rebuildService(item, ids, 'Duct', ci);
	}	
	//save quote information
	ci.Save();
}

function rebuildService(item, ids, type, ci) {
	var IDs = null;
	var Rooms = null;
	var Services = null;
	var isAirDuct = false;
	var NewItem;
	
	switch (type) {
		case 'Carpet':
			IDs = ids.CarpetIDs;
			Rooms = ci.Carpets.Rooms;
			Services = ids.CarpetServices;
			NewItem = new CarpetItem('', 0, 0, 0);
			isAirDuct = false;
		break;
		case 'Upholstered':
			IDs = ids.UpholsteredIDs;
			Rooms = ci.Carpets.ClothFurniture;
			Services = ids.UpholsteredServices;
			NewItem = new CarpetItem('', 0, 0, 0);
			isAirDuct = false;
		break;
		case 'Leather':
			IDs = ids.LeatherIDs;
			Rooms = ci.Carpets.LeatherFurniture;
			Services = ids.LeatherServices;
			NewItem = new CarpetItem('', 0, 0, 0);
			isAirDuct = false;
		break;
		case 'Auto':
			IDs = ids.AutoIDs;
			Rooms = ci.Carpets.Autos;
			Services = ids.AutoServices;
			NewItem = new CarpetItem('', 0, 0, 0);
			isAirDuct = false;
		break;
		case 'Tile':
			IDs = ids.TileIDs;
			Rooms = ci.Tile.Rooms;
			Services = ids.TileServices;
			NewItem = new TileItem('', 0, 0);
			isAirDuct = false;
		break;
		case 'Duct':
			IDs = ids.DuctIDs;
			Rooms = ci.Ducts.Rooms;
			Services = ids.DuctServices;
			NewItem = new DuctItem('', 0);
			isAirDuct = true;
		break;
	}

	for (var j in IDs) {
		//Check for dryer service if it is AirDuct
		if (item.AreaID == 60) {
			ci.Ducts.Dryer = true;
		}
		//Check for the number of HVACs if it AirDuct
		else if (item.AreaID == 48) {
			ci.Ducts.HVACs = item.Quantity;
			$.cookie(SESSION_GUID, 'current_tab', 'duct', {path: '/'});
		}
		
		//Check if the area is in the list for this service
		else if (IDs[j].AreaID == item.AreaID) {
			
			for (var k in Services) {
				if (Services[k].ServiceID == item.ServiceID) {
					//if the room has not been created for a different service, create it
					if (Rooms[IDs[j].Description] === null || Rooms[IDs[j].Description] === undefined){
						Rooms[IDs[j].Description] = NewItem;
						Rooms[IDs[j].Description].Name = IDs[j].Description;
					}
					//add quantity for that room
					if (Services[k].Description.toLowerCase().indexOf('clean') >= 0) {
						if (isAirDuct) {
							Rooms[IDs[j].Description].Quantity = item.Quantity;
						} else {
							Rooms[IDs[j].Description].CleanQuantity = item.Quantity; 
						}
					} else if (Services[k].Description.toLowerCase().indexOf('protect') >= 0) {
					    Rooms[IDs[j].Description].ProtectQuantity = item.Quantity; 
					} else if (Services[k].Description.toLowerCase().indexOf('deodorize') >= 0) {
					    Rooms[IDs[j].Description].DeodorizeQuantity = item.Quantity; 
					}
				}
			}
			break;
		}
	}
	//return the saved quote information
	return ci;
}

//executes when a user saves their quote
//accepts operationID
function ClearSaleing_SaveQuote(opID) {
	resetClearSaleingVariables();
	
	csSalesStageCode = 'Closed/Won';
	csOrderType = 'Save Quote';		
	csOrderNum = 'SQ-' + getSessionID();
	csCustomerRating = opID.toString();	
	csPostalCode =  $.cookie(SESSION_GUID, 'zip_code');
   
   try{
		executeShoppingCart();
		executeTrackerAJAX("edata.js");
	} catch(ex){}
}

function checkEmail(val){
	val = val.split('');
	var count = 0;
	
	for (var i in val){
		if (val[i] === "@") {
			count ++;
		}
	}
	
	if (count === 1) { return true; }
	else { return false; }
}