//Intervals to make ajax call. May need tweaking. Start by calling startRefreshQuotes() on page load.
//All quotes will be in after 30s so can stop then
var arrPageRefreshTimes = new Array(0,5000,5000,10000,10000);
var intCurrentPageRefreshIndex = 0;
var arrFailedQuotes = new Array();
var intCurrentResultCount = 0;
var strCurrentQuoteID = '';
var arrRawProductData = '';
var boolIsRequoteRefresh = false;

function startRefreshQuotes()
{
	setTimeout(refreshQuotes, arrPageRefreshTimes[0]);
}

function setProgressLevel(intTotal, intCurrent)
{
	var intProgressBarChunk = 100/intTotal;
	var intCurrentPercentageComplete = Math.round(intCurrent*intProgressBarChunk);
	$("#mx-ProgressBarPercentage").html(intCurrentPercentageComplete + '% Complete');
	$("#mx-ProgressBar").progressbar('option', 'value', intCurrentPercentageComplete);
}

function finishSearchingSequence()
{
	setProgressLevel(arrPageRefreshTimes.length, arrPageRefreshTimes.length);
	$("#mx-loadingResults tr").html("<td id=\"mx-SearchComplete\">Search Complete</td>");
	$("#mx-CarInsuranceLoadingProgress").css("display", "none");
	$(".mx-CarInsuranceOptionsWrapper").slideDown(1000);
	$("#mx-loadingResults").fadeOut(4000,
		function()
		{
			$("#mx-loadingResults").empty();
		}
	);
	boolIsRequoteRefresh = false;
}

function refreshQuotes()
{
	if (IsCookieSet == true)
	{
		intCurrentPageRefreshIndex = arrPageRefreshTimes.length;
		postData();
	}
	else
	{
		intCurrentPageRefreshIndex++;	
		setProgressLevel(arrPageRefreshTimes.length, intCurrentPageRefreshIndex);
		postData();
	}
}


function postData()
{
	if (arrPageRefreshTimes.length == intCurrentPageRefreshIndex && !boolIsRequoteRefresh)
	{
		boolSendLead = true;
	}
	else
	{
		boolSendLead = false;
	}
	
	$.post("/ajax/motoring_helper.ajax.php",
		{
			boolSendLead: boolSendLead,
			quoteId: $("#mx-quoteId").val(),
			IsReQuote: $("#mx-IsReQuote").val(),
			CoverType: $("#mx-CoverType").val(),
			VoluntaryExcess: $("#mx-grantedVoluntaryExcess").val(),
			NCBProtection: $("#mx-NCBProtection").attr('checked'),
			sortOrder: $("#mx-sortOrder").val(),
			sortAttribute: $("#mx-sortAttribute").val(),
			ResultOffset: $("#mx-ResultOffset").val(),
			ResultToReturn: $("#mx-ResultToReturn").val(),
			Page: strPage,
			Domain: strDomain
		},
		function(returned_data)
		{
			// To allow the compare popup to access the data (needs doing a different way)
			arrRawProductData = returned_data;
			
			//Check Response Code and if Response Code 200, Display Results
			if ( returned_data.Response.StatusCode == 200 )
			{
				// Set ReQuote form defaults from original returned data
				if (returned_data.Parameters.NCBProtection == 'true')
				{
					$("#mx-NCBProtection").attr('checked', true);
				}
				$("#mx-grantedVoluntaryExcess").val(returned_data.Parameters.VoluntaryExcess);		
				
				switch (returned_data.Parameters.CoverType)
				{
					case '1':
					$("#mx-CoverType").val('Comprehensive');
					break;
					
					case '2':
					$("#mx-CoverType").val('ThirdPartyFireTheft');
					break;
					
					case '3':
					$("#mx-CoverType").val('ThirdParty');
					break;
				}
				
				// If the user has requested a re-quote
				if ($("#mx-IsReQuote").val() == 'true')
				{
					$("#mx-quoteId").val(returned_data.Parameters.QuoteID);
					$("#mx-IsReQuote").val('false');
					$("#mx-loadingResults").html("<tr><td>Searching</td><td><div id=\"mx-ProgressBar\"></div></td><td id=\"mx-ProgressBarPercentage\">0% Complete</td></tr>");
					$("#mx-ProgressBar").progressbar({ value: 0 });
					if (returned_data.Parameters.QuoteID != strCurrentQuoteID)
					{
						$("#mx-results").empty();
						strCurrentQuoteID = returned_data.Parameters.QuoteID;
					}
					else
					{
						//return;
					}
				}
				else
				{
					strCurrentQuoteID = returned_data.Parameters.QuoteID;
				}


				//Show Number of Results
				$("#mx-totalProducts").html(returned_data.ResultStats.TotalProducts);

				//Load Results (if different from previous request)
				if (returned_data.ResultStats.TotalProducts != intCurrentResultCount)
				{
					$("#mx-results").html(returned_data.ResultsFormatted);
					intCurrentResultCount = returned_data.ResultStats.TotalProducts;
				}

				//Apply any selected filter options to the new results
				filterResults();

				// Setup ToolTips for compare checkboxes
				$(".mx-CompareCheckBox").hoverIntent(
					{
						'over' : function()
								{
									$(this).parent("td").append("<div class=\"mx-ToolTipPopup\"><h1>Help</h1>" + arrToolTipText['CompareResults'] + "</div>");
								},
						'out' : function()
								{
									$(this).siblings(".mx-ToolTipPopup").fadeOut();
									$(this).siblings(".mx-ToolTipPopup").remove();
								},
						'interval' : 1000
					}
				);
				
				// Display compare box when the 'details' link is pressed //			
				$(".mx-ccCarInsuranceProductDetails").bind("click",
					function()
					{
						// Empty all checkboxes //
						$("#mx-ResultsTable input[type='checkbox']").attr('checked', false);
						
						// Set the checkbox for the current row //
						$(this).parent().next('td').children(".mx-CompareCheckBox").attr('checked', true);
						
						// Call the function to create the compare lightbox //
						compareQuotes();
					}
				);			
						
			}
			//If not Response Code 200
			else
			{
				// Only display error if last refresh
				if (intCurrentPageRefreshIndex == arrPageRefreshTimes.length)
				{
					$("#mx-totalProducts").html(0);
					$("#mx-results").append('<tr><td colspan="11">There are no quotes available for this reference code.</td></tr>');
				}
			}

			// Search for new quotes or finish searching and display filter options
			if(intCurrentPageRefreshIndex < arrPageRefreshTimes.length)
			{
				setTimeout(refreshQuotes, arrPageRefreshTimes[intCurrentPageRefreshIndex]);
			}
			else
			{
				finishSearchingSequence();
			}
		},
		'json'
	);
}

//Calculates total payable for monthly installments
function calculateTotalPayable(strDeposit, strNumberPayments, strPaymentsAmount)
{
	var floatDeposit = parseFloat(strDeposit);
	var intNumberPayments = parseInt(strNumberPayments);
	var floatPaymentsAmount = parseFloat(strPaymentsAmount);
	
	if(floatDeposit > 0  && intNumberPayments > 0)
	{
		var floatTotalPayable = floatDeposit + (intNumberPayments * floatPaymentsAmount);
		var preFormatTP = floatTotalPayable;
		floatTotalPayable += "";
		//Format number nicely
		//floatTotalPayable = floatTotalPayable.substr(0, floatTotalPayable.lastIndexOf(".")+3); // Courtesy of Rob T.
		floatTotalPayable = (Math.round(floatTotalPayable*100)/100).toFixed(2);
		return floatTotalPayable;
	}
	else
	{
		return "";
	}
}

//Adds any providers we failed to get a quote for to the bottom of the list
function addFailedProviders()
{
	for ( i in arrFailedQuotes )
	{
		$("#mx-results").append('<tr><td>' + arrFailedQuotes[i] + '</td><td colspan="10">Unable to quote</td></tr>');
	}
}


function getOverlayImage(strYesOrNo)
{
	if(strYesOrNo == "Yes")
	{
		return '<img height="16" width="16" alt="Yes" src="/images/mx-transactionTick.gif"/>';
	}
	else
	{
		return '<img height="16" width="16" alt="No" src="/images/mx-transactionCross.gif"/>';
	}
}


function filterResults()
{
	var objFilterOptions = { 'mx-grantedVoluntaryExcessValue' : parseInt($("#mx-grantedVoluntaryExcess").val()) };
	
	//Get all the filter checkboxes from the page
	$('#mx-filterOptions input[type="checkbox"]').each(function()
		{
			objFilterOptions[this.value] = $(this).is(":checked");
		}
	);
	
	//Enable all rows first
	$('#mx-ResultsTable > tbody > tr').each(function(i)
		{
			$(this).removeClass("mx-InsuranceBlankedOutRows");
			//$(this).children("td").fadeTo(100, 1); //This works but slows IE down a lot
			//$(this).show();
		}
	);
	
	//Then disable any selected ones
	for(i in objFilterOptions)
	{
		//Special case for excess
		if(i == 'mx-grantedVoluntaryExcessValue')
		{
			//~ $('.'+i).each(function()
				//~ {
					//~ //cut &pound; off the front and remove any commas in number
					//~ var intExcessAmount = parseInt(this.innerHTML.substr(1).replace(/,/, ''));
					//~ if( objFilterOptions[i] < intExcessAmount )
					//~ {
						//~ $(this).parent().addClass("mx-InsuranceBlankedOutRows");
					//~ }
				//~ }
			//~ );
		}
		else
		{
			//Is the filter on?
			if( objFilterOptions[i] )
			{
				$('.'+i+'No').each(function()
					{
						$(this).parent().addClass("mx-InsuranceBlankedOutRows");
						//$(this).parent().children("td").fadeTo(100, 0.2); //This works but slows IE down a lot
						//$(this).parent().hide();
					}
				);
			}
		}
	}
}

function createSliders()
{
	var options  = 
	{ 
		min: intVoluntaryExcessMin, 
		max: intVoluntaryExcessMax, 
		step: intVoluntaryExcessSteps, 
		startValue: intVoluntaryExcessStartValue, 
		animate: true,
		slide: function(e,ui)
			{
				$("#mx-grantedVoluntaryExcess").val(ui.value);
			}, 
		change: function(e,ui)
			{
				filterResults();
			}
	};
	$("#mx-sliderTestBgCarInsurance").slider(options);
	
	//if change manualy
	$("#mx-grantedVoluntaryExcess").bind("change", function()
		{
			filterResults();
		}
	);
}


var arrComparisonFieldsInTable = new Array('brokerRef', 'premium', 'instalmentDeposit', 'instalmentAmount', 'instalmentTotalPayment',
										 'compulsoryExcess', 'grantedVoluntaryExcess', 'carHire', 'greenCardDays', 'legalExpenses', 
										 'windscreenLimit', 'audioLimit','contentsLimit', 'ProductApplicationURL', 'NCDProtection',
										 'NCDProtectionClaims', 'ReplacementWindscreenXS', 'UKBreakdownCover', 'LossOfKeys',
										 'RescueCover', 'AdditionalDataProviderImage', 'LogoImageSource');
function compareQuotes()
{
	window.scrollTo(0,0);

	//Find any selected rows
	var objSelectedRows = $("#mx-ResultsTable input[type='checkbox']:checked");
	
	var intNumberOfSelectedCheckboxes = objSelectedRows.length;
	if(intNumberOfSelectedCheckboxes < 1)
	{
		alert("Select up to 4 quotes to compare by checking the 'Compare' box next to each quote.");
		return;
	}
	if(intNumberOfSelectedCheckboxes > 4)
	{
		alert("You may only select up to 4 quotes to compare at once. Please unselect " + (intNumberOfSelectedCheckboxes-4) + " quote(s).");
		return;
	}
	
	var arrSelectedQuotes = new Array();
	
	//Find the quotes we are intrested in in the product array data as its 0 indexed rather than indexed by result id
	for(x in arrRawProductData.Results)
	{
		var intThisRowResultId = parseInt(arrRawProductData.Results[x].resultID);
		objSelectedRows.each(function(i)
			{	
				if( intThisRowResultId == parseInt(this.value) )
				{
					arrSelectedQuotes.push(arrRawProductData.Results[x]);
				}
			}
		);
	}
	
	var intNumberOfSelectedQuotes = arrSelectedQuotes.length;
	
	//Loop over all rows in our comparsion table
	for(x in arrComparisonFieldsInTable)
	{
		//Fill in a column for each selected quote
		$("#mx-CompareQuotes-"+arrComparisonFieldsInTable[x]).children().each(function(i)
			{
				//Skip over first as its the row description
				if(i != 0)
				{
					var strFieldValue = '';
					var thisBrokerRef = '';
					if(i <= intNumberOfSelectedQuotes)
					{
						switch(arrComparisonFieldsInTable[x])
						{

							case 'AdditionalDataProviderImage':
							//strFieldValue = (arrSelectedQuotes[i-1][arrComparisonFieldsInTable[x]] != '') ? '<img src="' + arrSelectedQuotes[i-1][arrComparisonFieldsInTable[x]] + '" />' : '';
							break;
							
							case 'brokerRef':
							strFieldValue = arrSelectedQuotes[i-1][arrComparisonFieldsInTable[x]];
							thisBrokerRef = arrSelectedQuotes[i-1][arrComparisonFieldsInTable[x]];
							break;
							
							case 'LogoImageSource':
							strFieldValue = '<img src="' + arrSelectedQuotes[i-1][arrComparisonFieldsInTable[x]] + '" alt="' + thisBrokerRef + '" />';
							break;
							
							case 'ProductApplicationURL':
							if (arrSelectedQuotes[i-1].IsPhoneApply == 1)
							{
								if (arrSelectedQuotes[i-1].resultKey != '')
								{
									strFieldValue = '<a href="javascript:showApplyOptionsPopups(\'' + arrSelectedQuotes[i-1].resultKey + '\')"><img src="/images/mx-buyNowButtonSmall.jpg" width="67" height="25" /></a>';
								}
								else
								{
									strFieldValue = '<a href="javascript:showApplyOptionsPopups(\'' + arrSelectedQuotes[i-1].resultID + '\')"><img src="/images/mx-buyNowButtonSmall.jpg" width="67" height="25" /></a>';
								}
							}
							else
							{
								if (arrSelectedQuotes[i-1].ProductApplicationURL != '')
								{
									strFieldValue = '<a href="' + arrSelectedQuotes[i-1].ProductApplicationURL + '" target="_blank"><img src="/images/mx-buyNowButtonSmall.jpg" width="67" height="25" /></a>';
								}
								else
								{
									strFieldValue = '';
								}
							}
							break;
							
							//Money Values
							case 'premium':
							case 'compulsoryExcess':
							case 'grantedVoluntaryExcess':
							strFieldValue = '&pound;' + arrSelectedQuotes[i-1][arrComparisonFieldsInTable[x]];
							break;
							
							case 'windscreenLimit':
							var strThisWindscreenLimit = arrSelectedQuotes[i-1][arrComparisonFieldsInTable[x]];

								if (strThisWindscreenLimit > 0)
								{
									if (strThisWindscreenLimit == '99900')
									{
										strFieldValue = getOverlayImage('Yes');
									}
									else
									{
										strFieldValue = '&pound;' + strThisWindscreenLimit;
									}
								}
								else
								{
									strFieldValue = getOverlayImage('No');
								}
							break;
								
							case 'instalmentDeposit':
								strFieldValue = (arrSelectedQuotes[i-1].instalmentDeposit > 0) ? 
														'&pound;' + arrSelectedQuotes[i-1].instalmentDeposit :
														"n/a";
								break;
							
							case 'instalmentAmount':
								strFieldValue = (arrSelectedQuotes[i-1].instalmentNumberOfPayments > 0) ?
									arrSelectedQuotes[i-1].instalmentNumberOfPayments + ' x &pound;' + arrSelectedQuotes[i-1].instalmentAmount :
									'n/a';
								break;
								
							case 'instalmentTotalPayment':
							var strTotalPayable = calculateTotalPayable(arrSelectedQuotes[i-1].instalmentDeposit, 
																		  arrSelectedQuotes[i-1].instalmentNumberOfPayments,
																		  arrSelectedQuotes[i-1].instalmentAmount);
																		  
							strFieldValue = (strTotalPayable == "") ? "n/a" : "&pound;"+strTotalPayable;
							break;
								
							//Yes/No
							case 'carHire':
							case 'legalExpenses':
								strFieldValue = (arrSelectedQuotes[i-1][arrComparisonFieldsInTable[x]] == 1) ? getOverlayImage('Yes') : getOverlayImage('No');
								break;
								
							case 'greenCardDays':
								strFieldValue = (arrSelectedQuotes[i-1].greenCardDays && arrSelectedQuotes[i-1].greenCardDays > 0) ?
													arrSelectedQuotes[i-1].greenCardDays + ' days' : 'n/a';
							break;
							
							// Additional Comparison Data
							
							case 'audioLimit':
							strFieldValue = FormatComparisonData(arrSelectedQuotes[i-1][arrComparisonFieldsInTable[x]], 'pound');
							break;
							
							case 'contentsLimit':
							strFieldValue = FormatComparisonData(arrSelectedQuotes[i-1][arrComparisonFieldsInTable[x]], 'pound');
							break;
							
							case 'NCDProtection':
							strFieldValue = FormatComparisonData(arrSelectedQuotes[i-1][arrComparisonFieldsInTable[x]]);
							break;
							
							case 'UKBreakdownCover':
							strFieldValue = FormatComparisonData(arrSelectedQuotes[i-1][arrComparisonFieldsInTable[x]]);
							break;
							
							case 'NCDProtectionClaims':
							strFieldValue = FormatComparisonData(arrSelectedQuotes[i-1][arrComparisonFieldsInTable[x]]);
							break;
							
							case 'ReplacementWindscreenXS':
							strFieldValue =  FormatComparisonData(arrSelectedQuotes[i-1][arrComparisonFieldsInTable[x]], 'pound');
							break;
							
							case 'LossOfKeys':
							strFieldValue = FormatComparisonData(arrSelectedQuotes[i-1][arrComparisonFieldsInTable[x]]);
							break;
							
							case 'RescueCover':
							strFieldValue = FormatComparisonData(arrSelectedQuotes[i-1][arrComparisonFieldsInTable[x]]);
							break;
								
							default:
							strFieldValue = arrSelectedQuotes[i-1][arrComparisonFieldsInTable[x]];
							break;
						}
					}
					$(this).html(strFieldValue);
				}
			}
		);
	}
	$("#mx-compareQuotesWrapper").mxlightbox();
}

function closeCompareQuotes()
{
	$("#mx-compareQuotesWrapper").mxlightbox("destroy");
}

function FormatComparisonData(mixValue, strUnit)
{
	var strDefaultText = 'Check with insurer';
	var mixValue = mixValue.toString();
	switch(mixValue)
	{
		case 'yes':
		case 'Yes':
		case 'standard':
		var strData = getOverlayImage('Yes');
		break;
		
		case 'no':
		case 'No':
		var strData = getOverlayImage('No');
		break;
		
		case 'cost':
		case 'repairer':
		case '':
		case ' ':
		var strData = strDefaultText;
		break;
		
		default:
		var strData = mixValue;
	}
	
	//Add Units if needed
	if (strUnit && strData != strDefaultText)
	{
		switch (strUnit)
		{
			case 'pound':
			if (strData.indexOf('&pound;') == -1 && strData.indexOf('£') == -1 && strData != 'unlimited')
			{
				strData = '&pound;' + strData;
			}
			break;
			
			case 'percent':
			strData = strData + '%';
			break;
		}
	}
	
	return strData;
}
