//datasales quote ajax functionality
var oAjax =
{
	
	createXmlHttpRequestObject: function()
	{
		var xhr;
		// this should work for all browsers except IE6 and older
		try {
			// try to create a new instance of XMLHttpRequest object
			xhr = new XMLHttpRequest();
		} catch(e) {
			// assume IE6 or older
			var XmlHttpVersions = new Array('MSXML2.XMLHTTP.6.0',
											'MSXML2.XMLHTTP.5.0',
											'MSXML2.XMLHTTP.4.0',
											'MSXML2.XMLHTTP.3.0',
											'MSXML2.XMLHTTP',
											'Microsoft.XMLHTTP');
			// try every prog id until one works
			for (var $i=0; $i<XmlHttpVersions.length && !xhr; $i++)
			{
				try { 
					// try to create a new instance of  XMLHttpRequest object
					xhr = new ActiveXObject(XmlHttpVersions[$i]);
				} catch (e) {
					//cannot instantiate the object
					xhr = false;
				}
			}
		}
		// return the created object or display an error message
		if (!xhr)
		{
			alert("Error creating the XMLHttpRequest object.");
		}
		else
		{ 
			return xhr;
		}
	}
}



var objListRental = {
	cfcpath:  "library/components/Lists/listRentalService.cfc?method=" ,
	
 	init: function (){
		//ADD EVENT HANDLERS
		
		var frmOrderSetLists = document.getElementById("frmSetLists-submit");
		/* ADD EVENT to First Order page*/
		if (frmOrderSetLists !== null) {	
			/* form sumbit event */
			addEvent(frmOrderSetLists, "onclick", objListRental.validateAddtoBasket);
			/* check box event*/
			var oListTypeIds 	=  document.forms["frmSetlists"].listTypeIDs;
				for (var i=1;i <= oListTypeIds.length;i++){
					var listTypeid = "listTypeID" + i; 
					//alert(listTypeid);
					addEvent(document.getElementById(listTypeid), "onclick", objListRental.onListSelect);
					}
			
			}
	},
	
	validateAddtoBasket: function(){

		if ( objListRental.addToBasket() ){
			var objForm = document.getElementById("frmSetlists");
			//alerr()
			objForm.submit();
			}
		},
	
	
		
	
	/**** FUNCTION* ****/
	requestQuote: function()
	{
		var $remotePath		= objListRental.cfcpath + "getQuote";
		
		var $message		= "";
		var $countMethods	= 0;
		var $valid			= true;
		
		var $listTypeIds	= "";
		var $arrListItems	= new Array();
		
		var $hid_ListTotal	= document.getElementById("hid_listTotal");
				
		// Iterate through the no of lists and create a array containing the listTypeIds
		for (var $i=1; $i <= $hid_ListTotal.value; $i++)
		{
			
			var $hid_ListTypeId = document.getElementById("hid_listtypeid" + $i);		
			
			//append the listTypeId to the array
			$arrListItems.push($hid_ListTypeId.value);
							
			//determine no of comm methods 
			for (var $j=1; $j < 3; $j++)
			{
				if (document.getElementById("commMethod" + $i + "" + $j).checked)
				{
					$countMethods += 1;
				}
			}
	
			//assign total no. of uses for each list based on comm method
			document.getElementById("hid_noofuses" + $i).value = $countMethods;
	
			if (document.getElementById("hid_noofuses" + $i).value == 0)
			{
				document.getElementById("item" + $i).style.backgroundColor = "#BACCEB"; 
				$message 	= "Please select at least one communication method for the highlighted row.\n";
				$valid 		= false;
			}
			else
			{
				document.getElementById("item" + $i).style.backgroundColor = "";
			}
			
			$countMethods = 0;
		}
		
		//convert the array of listTypeIds to a comma-separated list
		$listTypeIds = $arrListItems.toString();

		if (!$valid)
		{
			alert($message);
			return false;
		}
		
		//create a query string to pass to the remote method
		var $queryString 	= "&ListTypeIDs=" + $listTypeIds + "&listType=1";
		
		//disable quote calc button
		objListRental.disableCalcButton();
		
		//send request to remote cfc
		var $url			=  $remotePath + $queryString;
		
		objListRental.returnQuote($url);
	},
	/**** FUNCTION* ****/
	updateFormat: function($sitePath, $idx, $formatId, $quote)
	{
		//determine whether a quote should be processed in the request
		$quote				= ($quote != null) ? $quote : 1;
		//build the ajax url
		var $remotePath 	= objListRental.cfcpath + "updateFormat";
		var $queryString 	= "&idx=" + $idx + "&formatId=" + $formatId;
		var $url 			= $sitePath + $remotePath + $queryString;
		
		//if the list format is labels, user cannot select tel/fax
		if ($formatId == 3){
			alert("NB. you cannot buy tel or fax numbers for set lists supplied as labels");	
			//loop over the communication methods (tel/fax)
			for (var $i=2; $i < 3; $i++)
			{
				//de-select the communication methods (tel/fax) and default the uses to zero
				document.getElementById("commMethod" + $idx + "" + $i).checked 	= false;
				document.getElementById("noOfUses" + $idx + "" + $i).value 		= 0;
				//update the change of communication method and uses, don't quote
				objListRental.updateComm($sitePath, $idx, $i, null, 0);
			}
		}
		
		//update the cart with the correct format for the purchased list
		objListRental.updateSessionCart($url);
		
		//update the overall quote based upon user selection if requested
		if ($quote)
			objListRental.requestQuote($sitePath);
	},
	/**** FUNCTION* ****/
	updateComm: function($sitePath, $idx, $commId, $commNum, $quote)
	{
		//determine whether a quote should be processed in the request
		$quote			= ($quote != null) ? $quote : 1;
		//get the tick box object that is being acted upon
		var $tickboxId 	= document.getElementById("commMethod" + $idx + "" + $commId);
		//get the associated select box id
		var $selectId	= document.getElementById("noOfUses" + $idx + "" + $commId);
		//get the format select box id
		var $formatId 	= document.getElementById("format" + $idx);

		//if the user is using the tick boxes
		if ($commNum == null)
		{
			//update the select box value based upon user's action
			if ($tickboxId.checked)
			{
				$commNum 		= 1;
				$selectId.value = $commNum;
			}
			else
			{
				$commNum 		= 0;
				$selectId.value = $commNum;
			}
		}
		//else the user is using the no. of uses select box.
		else
		{
			if ($commNum == 0)
			{
				$tickboxId.checked = false;
			}
			else
			{
				$tickboxId.checked = true;
			}
		}

		//if the tel/fax communication methods are ticked
		//or the no. of uses for tel/fax greater than zero
		//and the format is labels, default to XLS
		if ((($tickboxId.checked && $tickboxId.value != 1) || ($selectId.value > 0 && $tickboxId.value != 1)) && ($formatId.value == 3))
		{
			//set the format to xls
			$formatId.value = 1;
			//update the format in the session with type XLS, don't quote
			updateFormat($sitePath, $idx, 1, 0);
		}

		//build the ajax url
		var $remotePath 	= objListRental.cfcpath +  "updateComm";
		var $queryString 	= "&idx=" + $idx + "&commMethod=" + $commId + "&noOfUses=" + $commNum;
		var $url 			= $sitePath + $remotePath + $queryString;
		
		//update the cart with the correct communication methods and uses
		objListRental.updateSessionCart($url);
		
		//update the base list price based upon the line item selection
		objListRental.requestQuotePerList($sitePath, $idx);
		
		//update the overall quote based upon user selection if requested
		if ($quote)
			  objListRental.requestQuote($sitePath);
	},
	/**** FUNCTION* ****/
	updateSessionCart: function($url)
	{
		var xhr = oAjax.createXmlHttpRequestObject();
		
		//do the ajax call to update the session basket
		if (xhr != null && xhr) {
			// url where process will be actioned
			xhr.open("GET", $url + "&rid=" + objListRental.randRange(1,9999999));
			//reference to the event
			xhr.onreadystatechange = function()
			{
				//if the XMLHttpRequest ready state is 'complete'
				if (xhr.readyState == 4)
				{
					//if the XMLHttpRequest status is 'OK' or 'Not Modified'
					if (xhr.status == 200 || xhr.status == 304)
					{
						//nothing to do...

					}
				}
			};
			xhr.send(null);
			return false;
		}
		return true;
	},
	/**** FUNCTION* ****/
	returnQuote: function($url){
		
		//alert ($url);
		
		var xhr = oAjax.createXmlHttpRequestObject();
		
		//do the ajax call to update the session basket
		if (xhr != null && xhr) {
			// url where process will be actioned
			xhr.open("GET", $url + "&rid=" + objListRental.randRange(1,9999999));
			//reference to the event
			xhr.onreadystatechange = function()
			{
				//if the XMLHttpRequest ready state is 'complete'
				if (xhr.readyState == 4)
				{
					//alert(xhr.responseText);
					//if the XMLHttpRequest status is 'OK' or 'Not Modified'
					if (xhr.status == 200 || xhr.status == 304)
					{
						//update the quote calc display
						objListRental.updateQuoteResult(xhr.responseText);
						//reset the calc button
						objListRental.enableCalcButton();
						//return true;
					}
				}
			};
			xhr.send(null);
			return false;
		}
		return true;
	},
	/**** FUNCTION* ****/
	updateQuoteResult: function($responseText)
	{
		document.getElementById("QuoteResults").innerHTML =	$responseText;
	},
	/**** FUNCTION* ****/
	disableCalcButton: function()
	{
		//document.getElementById("CalculateQuote1").disabled = true;
	},
	/**** FUNCTION* ****/
	enableCalcButton: function()
	{
		//document.getElementById("CalculateQuote1").disabled = false;
	},
	/**** FUNCTION* ****/
	requestQuotePerList: function($sitePath, $idx)
	{
		var $remotePath		= objListRental.cfcpath + "getQuotePerList";
		var $queryString	= "";
		var $hid_ListTypeId = document.getElementById("hid_listtypeid" + $idx).value;
		
		$queryString		+= "&listTypeId=" + $hid_ListTypeId + "&listType=1";
		
		var $url			= $sitePath + $remotePath + $queryString;
		
		//process the ajax request to update the session and page
		objListRental.returnQuotePerList($url, $idx);
	},
	
	/**** FUNCTION* ****/
	returnQuotePerList: function($url, $idx)
	{
		var xhr = oAjax.createXmlHttpRequestObject();
		
		//do the ajax call to update the session basket
		if (xhr != null && xhr) {
			// url where process will be actioned
			xhr.open("GET", $url + "&rid=" + objListRental.randRange(1,9999999), false);
			//reference to the event
			xhr.onreadystatechange = function()
			{
				//if the XMLHttpRequest ready state is 'complete'
				if (xhr.readyState == 4)
				{
					//if the XMLHttpRequest status is 'OK' or 'Not Modified'
					if (xhr.status == 200 || xhr.status == 304)
					{
						objListRental.updateQuotePerList($idx, xhr.responseText);
					}
				}
			};
			xhr.send(null);
			return false;
		}
		return true;
	},
	
	updateQuotePerList: function($idx, $responseText)
	{
		document.getElementById("baseprice" + $idx).innerHTML = $responseText;
	},
	
	/**** FUNCTION* ****/
	processOrder: function($sitePath, $orderId, $purchaseId, $invoiceId, $paymentType)
	{
		var $remotePath = cfcpath + "processOrder";
		var $queryString = "&orderId=" + $orderId
							+"&purchase_order_no=" + $purchaseId
							+"&invoiceId=" + $invoiceId
							+"&paymentType=" + $paymentType;
		var $url = $sitePath + $remotePath + $queryString;
		//send the request to the server and update the page
		objListRental.updateOrderPage($url);
	},
	
	/**** FUNCTION* ****/
	updateOrderPage: function($url)
	{
		var xhr = oAjax.createXmlHttpRequestObject();
		
		//do the ajax call to update the session basket
		if (xhr != null && xhr) {
			// url where process will be actioned
			xhr.open("GET", $url + "&rid=" + objListRental.randRange(1,9999999), true);
			//reference to the event
			xhr.onreadystatechange = function()
			{
				//if the XMLHttpRequest ready state is 'complete'
				if (xhr.readyState == 4)
				{
					//if the XMLHttpRequest status is 'OK' or 'Not Modified'
					if (xhr.status == 200 || xhr.status == 304)
					{
						document.getElementById('dvprocess').innerHTML = xhr.responseText;
					}
				}
			};
			xhr.send(null);
			return false;
		}
		return true;
	},
	
	/**** FUNCTION* ****/
   getStats: function (obj) {
	var objStats =new Object();
	var totalNo = 0;
	var totalCost = 0;
	var totalRecords = 0;
	
	
	//loop over input object
	for (var i = 0; i < obj.length; i++) {
		if (obj[i].checked) {
			//increment integers
			totalNo++;
			totalCost += Number(document.getElementById('cost' + (i + 1)).value);
			totalRecords += Number(document.getElementById('noofrecords' + (i + 1)).value);
		}
	}
	//alert(totalCost);
	//set vars into return object
	objStats.totalNo 		= totalNo;
	objStats.totalCost 		= totalCost.toFixed(2); //Only return value to 2 decimal places
	objStats.totalRecords 	= totalRecords;
	
	
	return	objStats;
	
	},
	
	/**** FUNCTION* ****/
	onListSelect: function (){
	
		var objCheck = document.forms["frmSetlists"].listTypeIDs;
		
		
		//get object return from getStats function
		var objstats = objListRental.getStats(objCheck);
		
		document.getElementById('listsSelected').innerHTML		= objstats.totalNo ;
		document.getElementById('totalCost').innerHTML			= '<strong>&pound; '+ objstats.totalCost +'</strong>';
		document.getElementById('totalNoOfRecords').innerHTML	= '<strong>'+ objstats.totalRecords +'</strong>';
	
		if (objstats.totalNo > 5){
			alert("You have exceeded the maximum number of setlists you can purchase at one time.\n Please click OK and deselect at least 1 of your choices");
		}

	},
	
  randRange: function($from, $to, $seed){
	// Make sure that we have integers.
	$from 	= Math.floor( $from );
	$to 	= Math.floor( $to );
	// Return the random number.
	return(Math.floor($from + (($to - $from + 1) * Math.random(($seed != null) ? $seed : 0 ))));
	},
	
	
	
	/**** FUNCTION* ****/
	addToBasket: function( ){
		var	frm 			= "frmSetlists"
		var listType		=1;
		var bValid			= true;
		var message			= "";
		var lCount			= 0;
		var oListTypeIds 	= document.forms[frm].listTypeIDs;
		var arrCheckedItems = new Array();
		
		for (var i=0;i<oListTypeIds.length;i++)
		{
			if (oListTypeIds[i].checked)
			{
				arrCheckedItems.push(oListTypeIds[i].value);	
			}
		}
			
		lCount = arrCheckedItems.length;
		
		if (lCount == 0)
		{	
			message = 'Please select a set list.\n';
			bValid = false;
		}
		else if (lCount > 5) {
			message = message + 'You have exceeded the maximum number of setlists you can purchase.\n Please click OK and deselect at least 1 of your choices';
			bValid = false;
		}
		
		if (!bValid ) {
			alert( message );
			return false;
		}
		else
		{
			document.forms[frm].submit();
			return true;
		}
	
	},
	
	/**** FUNCTION* ****/
	// delete from basket function simply asks for confirmation
	deleteBasket: function (){
	var agree = confirm("Are you sure you want to delete the basket?") 
	if (agree)
	{
		return true;			
	}
	else 
		{
		return false;
		}
	},
	/**** FUNCTION* ****/
	sampleListPopUp: function(currentRow, windowUrl){
	//open window using url string
	window.open(windowUrl, 'sampledata', 'width=800, height=600, resizable=yes, scrollbars=yes, toolbar=no');
	},
	
	/**** FUNCTION* ****/
	ExplainListPopUp: function(windowUrl){
		//open window using url string
		window.open(windowUrl, 'ListExplained', 'width=800, height=600, resizable=yes, scrollbars=yes, toolbar=no');
	},

	/**** FUNCTION* ****/
	submitSummary: function($formaction){
		var tickBox = document.getElementById('confirm2');
		frm = document.getElementById('frmCheckoutTCs');
		
		if (tickBox.checked == true) {
			frm.action=$formaction;
				
			frm.submit();
			
			if ($formaction.indexOf('invoice') > 0){
				document.getElementById('buttons').style.display = 'none';
				document.getElementById('message').innerHTML  = '<h3>Loading.......</h3><p>Please wait while we process your order and create  your Lists</p><img src="library/images/loader_anim_fadein.gif" width="149" height="19" /><br /><br />';	
			}
				return true;	
			} 
		else {alert('Please tick to confirm that you have read the terms and conditions and wish to proceed.'); 
				return false;
			}
		},
		
	/**** FUNCTION* ****/
	preloadImages: function (){
    	var img1 = new Image();
  	   img1.src = "library/images/loader_anim_fadein.gif";
   	},
	
	/**** FUNCTION* ****/
	confirmInvoice: function($formaction){
	 if (confirm("By proceeding beyond this point, you will have submitted an order for a your list \n You will have 14 days in which to pay Hemming Information Services the full amount for the use these lists. ")) {
		 objListRental.submitSummary($formaction);
       }
    else {
       return false;}
    },
    
    /**** FUNCTION* ****/
	processList: function($sitePath){
		//alert("here");
		var $remotePath = "library/components/Lists/listRentalService.cfc?method=" + "processList";
		/*var $queryString = "&orderId=" + $orderId
							+"&purchase_order_no=" + $purchaseId
							+"&invoiceId=" + $invoiceId
							+"&paymentType=" + $paymentType;*/
		var $url = $sitePath + $remotePath //+ $queryString;
		//send the request to the server
		objListRental.sendListRequest($url);
    },
    
    /**** FUNCTION* ****/
	sendListRequest: function($url)
	{
		var xhr = oAjax.createXmlHttpRequestObject();
		
		//do the ajax call to update the session basket
		if (xhr != null && xhr) {
			// url where process will be actioned
			xhr.open("GET", $url + "&rid=" + objListRental.randRange(1,9999999), true);
			
			//reference to the event
			xhr.onreadystatechange = function()
			{
				//if the XMLHttpRequest ready state is 'complete'
				if (xhr.readyState == 4)
				{
					//if the XMLHttpRequest status is 'OK' or 'Not Modified'
					if (xhr.status == 200 || xhr.status == 304)
					{
						//document.getElementById('dvprocess').innerHTML = xhr.responseText;
					}
				}
			};
			xhr.send(null);
			return false;
		}
		return true;
	}
	
}



//load the datasales object
addLoadEvent(objListRental.init);


////////////////////////////////////////////////////////////////////////////////
// some extraneous stuff
////////////////////////////////////////////////////////////////////////////////














