var HDresultsReceived = false;

function postData()
{
	reloadAdverts();

	$("#mx-loadingContents").css("display", "block");
	$("#mx-errorContents").css("display", "none");
	$("#mx-loading").fadeIn("300");
	cycleProviders(arrProviderList);
		
	$("#mx-ResultsTable-wide, #mx-ResultsTable").fadeTo("300", 0.4,
	function()
	{
		// ******CHANGE POST VARIABLES HERE******
		$.post("/ajax/cards_helper.ajax.php",
			{
				CardType: $(".mx-CardType:checked").val(),
				sortOrder: $("#mx-sortOrder").val(),
				sortAttribute: $("#mx-sortAttribute").val(),
				ResultOffset: $("#mx-ResultOffset").val(),
				ResultToReturn: $("#mx-ResultToReturn").val(),
				WhiteLabelMode: $("#mx-WhiteLabelMode").val(),
				affilId: strAffiliateId
			},
			// ******END******
			function(returned_data)
			{
				arrRawProductData = returned_data;
				//Check Response Code and if Response Code 200, Display Results
				if ( returned_data.Response.StatusCode == 200 )
				{
					$("input").removeClass("mx-inputError");
					$("#mx-resultsHeader").empty();
					$("#mx-fullMarketResults").empty();
					$("#mx-topPicksResults").empty();
					
					$("#mx-resultsHeader").html(returned_data.Header);
					
					// We dont want to overwrite the HD Decisions results with the sponsored //
					if ( !HDresultsReceived )
					{
						$("#mx-topPicksResults").html(returned_data.Sponsored);
					}

					$("#mx-fullMarketResults").html(returned_data.FullMarket);

					intCurrentPage = calculateCurrentPage($("#mx-ResultOffset").val(), intResultToReturn);
					intTotalPages = (returned_data.Parameters.WhitelabelMode) ? Math.ceil(returned_data.ResultStats.TotalSponsoredProducts/intResultToReturn) : Math.ceil(returned_data.ResultStats.TotalProducts/intResultToReturn);
					setPagination(intTotalPages, intCurrentPage);
					
					//if (($("div").hasClass("mx-" + returned_data.SortVariables[0].select) == 'true') || (returned_data.Parameters.CardType == 'LOWEST_STANDARD_APR'))
					if (returned_data.SortVariables[0].select == 'INR_PurchaseRateAER' || returned_data.SortVariables[0].select == 'ProviderName')
					{
						var strSortField = returned_data.SortVariables[0].select;
					}
					else
					{
						var strSortField = 'Primary';
					}
					
					setSortImages(strSortField, returned_data.SortVariables[0].order);
					
					//Fade in New Data
					$("#mx-ResultsTable-wide, #mx-ResultsTable").fadeTo("300", 1);
					if (intCurrentPage == 1)
					{
						$("#mx-topPicksResults").fadeIn("300");
					}
					$("#mx-fullMarketResults").fadeIn("300");
					if (returned_data.Parameters.WhitelabelMode)
					{
						$("#mx-totalProducts").text(returned_data.ResultStats.TotalSponsoredProducts);
					}
					else
					{
						$("#mx-totalProducts").text(returned_data.ResultStats.TotalProducts);
					}
					$("#mx-totalProducts").fadeIn("300");
					$("#mx-loading").fadeOut("300", 0);
				}
				else //If not Response Code 200 Display Error Message
				{
					$("#mx-loadingContents").css("display", "none");
					$("#mx-errorContents").css("display", "block");
					var strErrorLog = '';
					var arrErrorKeys = new Array();
					for ( var i = 0; i < returned_data.Response.StatusInfo.length; i++ )
					{
						jQuery.each(returned_data.Response.StatusInfo[i],
							function(j, val)
							{
								strErrorLog += "- "+val+"<br />";
								arrErrorKeys[i] = j;
							}
						);
					}
					highlightErrors(arrErrorKeys);
					$("#mx-errorContents").html("<h4>Error: "+returned_data.Response.StatusCode+"</h4><p>"+strErrorLog+"</p>");
				}

				//Synchronise Refine Form With Returned Input Parameters
				$("#mx-searchType").val(returned_data.Parameters.CardType);
				
				// Resize iFrame for Whitelabels
				if (returned_data.Parameters.WhitelabelMode)
				{
					setCompletion($("body").height()+ 50 +"px");
				}

			},
			"json"
		)
	});
}

function setupDetailsPopups()
{
	$(".mx-detailsLink").css("display", "block");

	$(".mx-detailsLink").click(
		function()
		{
			var arrProduct = this.className.split(' ');
			$(".mx-detailsPopup."+arrProduct[1]).css("zIndex", intDetailsPopupZindex + intPopupCount);
			intPopupCount++;
		}//~ },
		//~ function()
		//~ {
			//~ var arrProduct = this.className.split(' ');
			//~ removePopup(arrProduct[1]);
		//~ }
	);

	$(".mx-detailsPopup").hover(
		function()
		{
			$(this).addClass("mx-hoverOn");
			var intNewZindex = intDetailsPopupZindex + intPopupCount;
			$(this).css("zIndex", intNewZindex);
			intPopupCount++;		
		},
		function()
		{
			if (!$(this).is(".mx-clicked"))
			{
				$(this).remove();
			}
		}
	);
	
	$(".mx-closeDetails").bind("click",
		function()
		{
			$(this).parent().parent(".mx-detailsPopup").remove();
		}
	);
}

function removePopup(intProductID)
{
	function realRemovePopup()
	{
		if (!$('div.mx-detailsPopup.'+intProductID).is('.mx-hoverOn') && !$('div.mx-detailsPopup.'+intProductID).is('.mx-clicked'))
		{
			$('div.mx-detailsPopup.'+intProductID).remove();
		}
	}
	t = setTimeout(realRemovePopup, 100);
}

function createDraggableDetails()
{
	$(".mx-detailsPopup").draggable({
		handle: '.mx-detailsTopBar',
		revert: false,
		refreshPositions: true,
		drag: function(ev, ui)
		{
			$(this).addClass("mx-clicked");
		}
	});
}

function setupDetailsAccordion(intProductID)
{
	var intDuration = 200;
	$(".mx-detailsAccordion."+intProductID).children(".mx-detailsAccordionItem").children(".mx-detailsAccordionHeader").bind("click",
		function()
		{
			//Pin Down Popup if not already
			if (!$(".mx-detailsPopup."+intProductID).hasClass("mx-clicked"))
			{
				$(".mx-detailsPopup."+intProductID).addClass("mx-clicked");
			}
			
			if ($(this).siblings().css("display") == 'none')
			{
				$(".mx-detailsAccordion."+intProductID).children(".mx-detailsAccordionItem").children(".mx-detailsAccordionItemBody").hide(intDuration);
				$(".mx-detailsAccordion."+intProductID).children(".mx-detailsAccordionItem").children(".mx-detailsAccordionHeader").children("img").attr("src", "/images/mx-popupPlus.jpg");
				$(this).parent().siblings().children("div.mx-detailsAccordionHeader").children("img").attr("src", "/images/mx-popupPlus.jpg");
				$(this).siblings().slideDown(intDuration);
				$(this).children("img").attr("src", "/images/mx-popupMinus.jpg");
			}
			else
			{
				$(this).siblings().hide("blind", { direction : "vertical" }, intDuration);
				$(this).children("img").attr("src", "/images/mx-popupPlus.jpg");
			}
		}
	);
	$(".mx-detailsAccordion."+intProductID).children(".mx-detailsAccordionItem").children("div.mx-detailsAccordionItemBody").hide();
	$(".mx-detailsAccordion."+intProductID).children(".mx-detailsAccordionItem").children(".mx-default").show(); // Add a "mx-default" class to the contents div, within "mx-detailsAccordionItem" for items you want to be initially open
	$(".mx-default").siblings().children("img").attr("src", "/images/mx-popupMinus.jpg");
	$(".mx-detailsTopBar, .mx-detailsTopBar h4, .mx-detailsTopBar span").bind("click",
		function()
		{
			if ($(this).hasClass("mx-detailsTopBar"))
			{
				$(this).parent().addClass("mx-clicked");
			}
			else
			{
				$(this).parent().parent().addClass("mx-clicked");
			}
		}
	);
}

function popupDetails(intProductID)
{
	var strThisPopup = '';
	if (!$("body").children("."+intProductID).length > 0)
	{
		strThisPopup = generatePopup(intProductID);
		$("body").append(strThisPopup);
		$(".mx-detailsPopup."+intProductID).css("display", "block");
		$(".mx-detailsPopup."+intProductID).addClass("mx-clicked");
		$(".mx-detailsPopup."+intProductID).css("left", intPosX/2);
		$(".mx-detailsPopup."+intProductID).css("top", intPosY);
		$(".mx-detailsPopup."+intProductID).css("zIndex", intDetailsPopupZindex + intPopupCount);
		$(".mx-detailsPopup."+intProductID).animate({ opacity: 1 });
		createDraggableDetails();
		setupDetailsAccordion(intProductID);
		setupDetailsPopups();
	}
	else
	{
		$(".mx-detailsPopup."+intProductID).children(".mx-detailsTopBar").effect("pulsate", { times: 2 }, 300);
	}
}

function generatePopup(intProductID)
{
	var strThisPopup = "";
	var arrFormattedPopup = new Array();
	var boolProductFound = false;
	//Loops through the Product Details Map (i is an integer representing the row number)
	for (var strSection in arrDetailsPopupMap) //Go through each section in the popup map (eg, Product Details, Restrictions)
	{
		arrSections = arrDetailsPopupMap[strSection];

		for (var i in arrSections) //Go through each key in the current section in the popup map
		{
			strKeyName = arrSections[i];
			
			for(var j in arrRawProductData['Results']) //Loop through the product data
			{
				if (arrRawProductData['Results'][j].ProductId == intProductID) // If we find the right product
				{

					var strThisProductName = arrRawProductData['Results'][j]['ProductName'].fieldValue;
					var strThisProductApplicationURL = (arrRawProductData['Results'][j]['ProductApplicationURL']) ? arrRawProductData['Results'][j]['ProductApplicationURL'] : '';

					boolProductFound = true;
					strPrimaryDataFields = '';
					strSecondaryDataFields = '';
					if (strKeyName in arrRawProductData['Results'][j]) //if the key in the popup map is in the current popup
					{
						if (strSection in arrFormattedPopup)
						{
						}
						else
						{
							arrFormattedPopup[strSection] = new Array();
						}
						//Put the data row in the formatted popup array
						if (arrRawProductData['Results'][j][strKeyName].fieldLabel.simple != null && arrRawProductData['Results'][j][strKeyName].fieldValue !== "" && arrRawProductData['Results'][j][strKeyName].fieldValue !== "-1")
						{
							switch (arrRawProductData['Results'][j][strKeyName].fieldValue)
							{
								case 'yes':
								strDataSentence = "<span class='mx-dataFieldLabel'>" + arrRawProductData['Results'][j][strKeyName].fieldLabel.simple + "</span>";
								arrFormattedPopup[strSection].push(strDataSentence);
								break;
								
								case 'no':
								break;
								
								default:
								var strDataSentence = arrRawProductData['Results'][j][strKeyName].fieldLabel.simple.replace("#VALUE#", arrRawProductData['Results'][j][strKeyName].fieldValue);
								strDataSentence = strDataSentence.replace("<p>", "<p><span class='mx-dataFieldLabel'>");
								if (strDataSentence.search(":") != -1)
								{
									strDataSentence = strDataSentence.replace(":", ":</span>");
								}
								else
								{
									strDataSentence = strDataSentence.replace("</p>", "</span></p>");
								}
								arrFormattedPopup[strSection].push(strDataSentence);
								break;
							}
						}
					}
				}
			}
			
			if (!boolProductFound)
			{
				for(var k in arrRawProductData['SponsoredResults']) //Loop through the product data
				{
					if (arrRawProductData['SponsoredResults'][k].ProductId == intProductID) // If we find the right product
					{
						var strThisProductName = arrRawProductData['SponsoredResults'][k]['ProductName'].fieldValue;
						var strThisProductApplicationURL = (arrRawProductData['SponsoredResults'][k]['ProductApplicationURL']) ? arrRawProductData['SponsoredResults'][k]['ProductApplicationURL'] : '';

						if (strKeyName in arrRawProductData['SponsoredResults'][k]) //if the key in the popup map is in the current popup
						{
							if (strSection in arrFormattedPopup)
							{
							}
							else
							{
								arrFormattedPopup[strSection] = new Array();
							}
							//Put the data row in the formatted popup array
							if (arrRawProductData['SponsoredResults'][k][strKeyName].fieldLabel.simple != null && arrRawProductData['SponsoredResults'][k][strKeyName].fieldValue !== "" && arrRawProductData['SponsoredResults'][k][strKeyName].fieldValue !== "-1")
							{
								switch (arrRawProductData['SponsoredResults'][k][strKeyName].fieldValue)
								{
									case 'yes':
									var strDataSentence = "<span class='mx-dataFieldLabel'>" + arrRawProductData['SponsoredResults'][k][strKeyName].fieldLabel.simple + "</span>";
									arrFormattedPopup[strSection].push(strDataSentence);
									break;
									
									case 'no':
									break;
									
									default:
									var strDataSentence = arrRawProductData['SponsoredResults'][k][strKeyName].fieldLabel.simple.replace("#VALUE#", arrRawProductData['SponsoredResults'][k][strKeyName].fieldValue);
									strDataSentence = strDataSentence.replace("<p>", "<p><span class='mx-dataFieldLabel'>");
									if (strDataSentence.search(":") != -1)
									{
										strDataSentence = strDataSentence.replace(":", ":</span>");
									}
									else
									{
										strDataSentence = strDataSentence.replace("</p>", "</span></p>");
									}
									arrFormattedPopup[strSection].push(strDataSentence);
									break;
								}
							}
						}
					}
				}
			}
		}
	}
	
	strThisPopup += "<div class=\"mx-detailsPopup " + intProductID + "\"><div class=\"mx-detailsTopBar\"><span class=\"mx-closeDetails\">Close x</span><span class=\"mx-moveDetails\"><img src=\"/images/mx-popupMove.jpg\" alt=\"move\" /></span><h4>" + strThisProductName + "</h4></div><div class=\"mx-detailsAccordion "+ intProductID +"\">";
	
	// Loop through formatted popup array and add them to the output string
	for (var arrSectionName in arrFormattedPopup)
	{
		var strSectionName = arrFormattedPopup[arrSectionName];
		for (var strDetailRow in strSectionName)
		{
			// If it's the first row in a section, output the section title
			if (strDetailRow == 0)
			{
				strThisPopup += "<div class=\"mx-detailsAccordionItem\"><div class=\"mx-detailsAccordionHeader\"><img class=\"mx-detailsAccordionIndicator\" src=\"/images/mx-popupPlus.jpg\" /><h4 class=\"mx-detailsSectionTitle\">" + arrSectionName + "</h4></div>";

				if (arrSectionName == "Product Details")
				{
					strThisPopup += "<div class=\"mx-detailsAccordionItemBody mx-default\">";
				}
				else
				{
					strThisPopup += "<div class=\"mx-detailsAccordionItemBody\">";
				}
			}
			
			strThisPopup += strSectionName[strDetailRow];
			
			if (strDetailRow == strSectionName.length - 1)
			{
				if (strThisProductApplicationURL == '')
				{
					strThisPopup += "</div></div>";
				}
				else
				{
					strThisPopup += "<p class=\"mx-detailsPopupApplyLink\"><a target=\"_blank\" href=\"" + strThisProductApplicationURL + "\"><img src=\"/images/mx-applyButton.gif\" width\"79\" height=\"26\" alt=\"Apply\" /></a></p></div></div>";
				}
			}
		}
	}
	
	strThisPopup += "</div>";
	return strThisPopup;
}

// HD Decisions functions //
function cycleHDmessages(returned_data)
{
	// Close lightbox //
	$("#mx-HDDecision_Lightbox").mxlightbox('destroy');	
	
	var arrHDMessages=new Array();
	arrHDMessages[0]="Personal Details";
	arrHDMessages[1]="Contact Details";
	arrHDMessages[2]="Address Information";
	//arrHDMessages[3]="Employment Details";
	//arrHDMessages[4]="Credit Card Information";
		
	var i = 0;
	var strArrayLength = arrHDMessages.length;	
	
	processReturnedData();
		
	function AlertHDMessages()
	{
		$("#mx-cycleProviders").html(arrHDMessages[i]);
		if ( i <= strArrayLength )
		{
			t = setTimeout(AlertHDMessages, 1000);
		}
		else
		{
			// the last loading message has been displayed //
			returned_data.boolShowLoading = 'false';
			$("#mx-loading").fadeOut("300");
			processReturnedData();
		}
		i++;	
	}
	
	function processReturnedData()
	{
		if ( returned_data.boolShowLoading == 'true' )	
		{
			// Show the loading image //
			$("#mx-loading").fadeIn("300");
			AlertHDMessages();

		}			
		else
		{				
			if ( returned_data.ShowLightbox == false )
			{
								
				// credit-profile.php functionallity // 
				if ( $("input[name=NoLightbox]").val() == 'true' )
				{
					if (returned_data.RecommendedResults.length == 0 && returned_data.BankerResults.length == 0)
					{
						// HD have found no suitable cards //
						$("#mx-resultsHeader").html(returned_data.DefaultProductHeader); 
						$("#mx-topPicksResults").html(returned_data.DefaultProduct);
					}
					else
					{
						// Append header for the normal results
						$("#mx-resultsHeader").html(returned_data.Header);
					}
					
					// hide form //
					$("#mx-HD_mainContent").css("display", "none");
					
					// display results table //
					$("#mx-yourSearchResults").css("display", "block");	
					
					// Display option to show the form again //
					$(".mx-apply-call-to-action-box_wide").css("display", "block");
				}
				else
				{
					// append the header for the normal results //
					$("#mx-resultsHeader").html(returned_data.Header);
				}
								
				
				// If there are no results and the card type is ZERO_BALANCE_TRANSFER, display the default product //
				if (returned_data.RecommendedResults.length == 0 && returned_data.BankerResults.length == 0
					&& $("input[name='CardType']:checked").val() == 'ZERO_BALANCE_TRANSFER')
				{
					$("#mx-topPicksResults").html(returned_data.DefaultProduct);
				}
				else
				{
					$("#mx-topPicksResults").html(returned_data.RecommendedResults);
					$("#mx-topPicksResults").append(returned_data.BankerResults);
				}
								
				if ( $("input[name=DontShowSponsored]").val() != 'true' )
				{
					$("#mx-topPicksResults").append(returned_data.Sponsored);
				}
				
				HDresultsReceived = true;				
			}
			else
			{
				if ( $("input[name=NoLightbox]").val() != 'true' )
				{
					// Open lightbox //
					$("#mx-HDDecision_Lightbox").mxlightbox();	
				}
				
				// Soap service has returned an error //
				if ( returned_data.HDerror != undefined )
				{
					var HDerrors = returned_data.HDerror.ErrorMessage;
					$("#mx-HD_TopMessage").html("<p style='color: red;'>" + HDerrors + "</p>");
						
				}
			}
		}
	}
}



function postHDform(boolShowLoading)
{
	// remove the class so no inputs so red // 
	$('form').find(':input, :select').removeClass('mx-inputError');
	
	// Change call to action message //
	$(".mx-HDcallToAction").html("If you would like to edit details for your personalised recommendation results");
	
	$.post("/credit-cards/index.php",
	{	
		DOBYear: $("select[name=DOBYear[]]").val(), 
		DOBMonth: $("select[name=DOBMonth[]]").val(),
		DOBDay: $("select[name=DOBDay[]]").val(),
		CardType: $("input[name='CardType']:checked").val(),
		LeadTitle: $("select[name=LeadTitle[]]").val(),
		LeadFirstName:  $("input[name=LeadFirstName]").val(),
		LeadSurname: $("input[name=LeadSurname]").val(),
		LeadAddress1: $("input[name=LeadAddress1]").val() ,
		LeadPostCode: $("input[name=LeadPostCode]").val(),
		LeadEmail:  $("input[name=LeadEmail]").val(),
		LeadTelephone: $("input[name=LeadTelephone]").val(),
		TimeAtAddress:  $("input[name=TimeAtAddress]").val(),
		EmploymentStatus: $("select[name=EmploymentStatus[]]").val(),
		ResidentialStatus: $("select[name=ResidentialStatus[]]").val(),
		BalanceToTransfer: $("select[name=BalanceToTransfer[]]").val(),
		OriginatingID: $("input[name=OriginatingID]").val(),
		affilId: $("input[name=affilId]").val(),
		boolShowLoading: boolShowLoading,
		isJS: "yes",
		_IsSubmit_HD_CardSearchForm: $("input[name=_IsSubmit_HD_CardSearchForm]").val(),
		AllCards:  $("input[name=AllCards]").val()
	},
		function(returned_data)
		{
			// Renable the submit button and fade back in //
			$(".mx-HD_submitButton").attr("disabled", false);
			$(".mx-HD_submitButton").css({ "opacity": '1' });
			
			// this allows clickthroughs to track the leadID if a card type is selected //
			$("input[name=OriginatingID]").val(returned_data.OriginatingID);			
			
			if ( returned_data.ResponseMessage != undefined )
			{
				// this is so that the tracking pixel displays (if there is one) //
				$("#mx-yourSearchResults").append(returned_data.ResponseMessage);
			}
			
			if ( returned_data.ShowLightbox == false )
			{
				cycleHDmessages(returned_data);
			}
			else
			{
				// Soap service has returned an error //
				if ( returned_data.HDerror != undefined )
				{
					cycleHDmessages(returned_data);
				}

				// Form errors //
				if ( returned_data.SearchFormErrorMessages != undefined )
				{
					var FormErrors =  returned_data.SearchFormErrors;
					var FormErrorMessages = returned_data.SearchFormErrorMessages;
					
					for ( var index in FormErrors )
					{
						$("#" + index + "").addClass("mx-inputError");
					}
					
					//SearchFormErrorMessages
					$("#mx-HD_TopMessage").html( FormErrorMessages );
						
				}
			}
		},
			"json"	
	)
}
// End HD Decisions functions //



