function postData()
{
	//reloadAdverts();
	$("#mx-loadingContents").css("display", "block");
	$("#mx-errorContents").css("display", "none");
	$("#mx-loading").fadeIn("300");
	//cycleProviders(arrProviderList);
	$("#mx-ResultsTable, #mx-ResultsTable-wide, #mx-SEMsavingsResultsTable").fadeTo("300", 0.4,
	function()
	{
		// ******CHANGE POST VARIABLES HERE******
		$.post("/ajax/banking_helper.ajax.php",
			{
				AccountType: $("#mx-AccountType").val(),
				ChargesPerMonth: $("#mx-currentAccountChargePerMonthText").val(),
				OverdraftChargesPerMonth: $("#mx-currentAccountOverdraftFeesText").val(),
				TransactByTelephone: $("#mx-currentAccountsTransactByTelephone").attr("checked"),
				TransactByInternet: $("#mx-currentAccountsTransactByInternet").attr("checked"),
				TransactByBranch: $("#mx-currentAccountsTransactByBranch").attr("checked"),
				AmountToSave: $("#mx-AmountToSave").val(),
				IsTransferISAIn: $("#mx-CashISASTransferIn").val(),
				IsTransferISAOut: $("#mx-CashISASTransferOut").val(),
				WithdrawalNotice: $("#mx-AccessTermText").val(),
				sortOrder: $("#mx-sortOrder").val(),
				sortAttribute: $("#mx-sortAttribute").val(),
				ResultOffset: $("#mx-ResultOffset").val(),
				ResultToReturn: $("#mx-ResultToReturn").val(),
				WhiteLabelMode: $("#mx-WhiteLabelMode").val(),
				subid: strAffiliateSubID,
				uid: strAffiliateUID,				
				affilId: strAffiliateId
			},
			// ******END******
			function(returned_data)
			{
				arrRawProductData = returned_data.RawProductData;
				
				//Check Response Code and if Response Code 200, Display Results
				if ( returned_data.Response.StatusCode == 200 )
				{		
					$("input").removeClass("mx-inputError");
					$("#mx-fullMarketResults").empty();
					$("#mx-topPicksResults").empty();
					
					if ((returned_data.ResultStats.TotalProducts != 0) || (returned_data.ResultStats.TotalProducts == 0 && returned_data.ResultStats.TotalSponsoredProducts != 0))
					{
				
						//if (returned_data.ResultStats.TotalSponsoredProducts != 0 && returned_data.ResultStats.ResultOffset == 0)
						//{
						
						//	$("#mx-topPicksResults").html(returned_data.Sponsored);
						//}

						//******FULL MARKET RESULTS START******
						//if (returned_data.Parameters.AccountType != 'TopPicks')
						//{
			
							$("#mx-fullMarketResults").html(returned_data.FullMarket);
						//}
					}
					else
					{
						$("#mx-fullMarketResults").append('<div class="mx-general-box mx-right-innerbox"  align="center"><table class="mx-results-table" width="99%" border="0" align="center" cellpadding="0" cellspacing="0"><tr><td>There are no results matching your search criteria.</td></tr></table></div>');
						setPagination('1', '1');
					}
					
					setupDetailsPopups();
					
					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);
					setSortImages(returned_data.SortVariables[0].select, returned_data.SortVariables[0].order);
					
					//Fade in New Data

					//~ if (returned_data.Parameters.AccountType == 'CashISAs')
					//~ {
						//~ $("#mx-ResultsTable, #mx-ResultsTable-wide, #mx-SEMsavingsResultsTable").css("tableLayout", "auto"); //CashISAs wouldn't listen to column widths, this forces it to.
					//~ }
					//~ else
					//~ {
						//~ $("#mx-ResultsTable, #mx-ResultsTable-wide, #mx-SEMsavingsResultsTable").css("tableLayout", "fixed");
					//~ }
					
					$("#mx-ResultsTable, #mx-ResultsTable-wide, #mx-SEMsavingsResultsTable").fadeTo("300", 1);
					if (intCurrentPage == 1)
					{
						$("#mx-topPicksResults").fadeIn("300");
					}

	
					if (returned_data.Parameters.WhitelabelMode)
					{
						$("#mx-totalProducts").text(returned_data.ResultStats.TotalSponsoredProducts);
					}
					else
					{
						if (returned_data.Parameters.AccountType == 'TopPicks')
						{
							$("#mx-totalProducts").text(returned_data.ResultStats.TotalSponsoredProducts);
							setPagination('1', '1');
						}
						else
						{
							$("#mx-totalProducts").text(returned_data.ResultStats.TotalProducts);
						}
					}
					$("#mx-totalProducts").fadeIn("300");
					$("#mx-loading").fadeOut("300");
				}
				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.searchType);

				// 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)
	{
		generatePopup(intProductID);
	}
	else
	{
		$(".mx-detailsPopup."+intProductID).children(".mx-detailsTopBar").effect("pulsate", { times: 2 }, 300);
	}
}

function appendPopup(intProductID, strThisPopup)
{
	$("body").prepend(strThisPopup);
	$(".mx-detailsPopup."+intProductID).css("display", "block");
	$(".mx-detailsPopup."+intProductID).addClass("mx-clicked");
	//$(".mx-detailsPopup."+intProductID).css("left", intPosX/2);
	$(".mx-detailsPopup."+intProductID).css("left", (document.body.scrollWidth/2) - 160);
	$(".mx-detailsPopup."+intProductID).css("top", intPosY);
	$(".mx-detailsPopup."+intProductID).css("margin-top", '-300px');
	$(".mx-detailsPopup."+intProductID).css("margin-left", 'auto');
	$(".mx-detailsPopup."+intProductID).css("margin-right", 'auto');
	$(".mx-detailsPopup."+intProductID).css("zIndex", intDetailsPopupZindex + intPopupCount);
	$(".mx-detailsPopup."+intProductID).animate({ opacity: 1 });
	createDraggableDetails();
	setupDetailsAccordion(intProductID);
	setupDetailsPopups();
}

function generatePopup(intProductID)
{
	var boolBankingTypeFound = false;
	var intResultsArrayIndex = null;
	var intSponsoredArrayIndex = null;

	for(var j in arrRawProductData['Results']) //Loop through the product data
	{
		if (arrRawProductData['Results'][j].ProductId == intProductID) // If we find the right product
		{
			var intBankingTypeId = arrRawProductData['Results'][j].BankingTypeId;
			boolBankingTypeFound = true;
			intResultsArrayIndex = j;
		}
	}

	if (!boolBankingTypeFound)
	{
		for(var k in arrRawProductData['SponsoredResults']) //Loop through the product data
		{
			if (arrRawProductData['SponsoredResults'][k].ProductId == intProductID) // If we find the right product
			{
				var intBankingTypeId = arrRawProductData['SponsoredResults'][k].BankingTypeId;
				boolBankingTypeFound = true;
				intSponsoredArrayIndex = k;
			}
		}
	}

	switch (intBankingTypeId)
	{
		case 1: // Current A/C
		strAccountType = 'CurrentAccounts';
		break;
		case 2: // East Access/Instant A/C
		strAccountType = 'InstantAccess';
		break;
		case 3: // Notice A/C
		strAccountType = 'NoticeAccounts';
		break;
		case 4: // Term A/C
		strAccountType = 'TermAccounts';
		break;
		case 5: // Cash ISA
		strAccountType = 'CashISAs';
		break;
		case 6: // Offshore A/C
		strAccountType = 'Offshore';
		break;
	}

	if ($("#mx-AccountType").length == 0 || $("#mx-AccountType").val() == '')
	{
		$.post('/ajax/banking_helper.ajax.php', { btid : intBankingTypeId, AccountType : strAccountType, pid : intProductID },
			function(objReturnedData)
			{
				if(intResultsArrayIndex)
				{
					arrRawProductData['Results'][intResultsArrayIndex] = objReturnedData['Results'][0];
				}
				else if (intSponsoredArrayIndex)
				{
					arrRawProductData['SponsoredResults'][intSponsoredArrayIndex] = objReturnedData['Results'][0];
				}
				strThisPopup = generatePopupHTML(strAccountType, intProductID);
				appendPopup(intProductID, strThisPopup);
			},
			'json'
		);
	}
	else
	{
		strThisPopup = generatePopupHTML(strAccountType, intProductID);
		appendPopup(intProductID, strThisPopup);
	}
}

function generatePopupHTML(strAccountType, 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[strAccountType]) //Go through each section in the popup map (eg, Product Details, Restrictions)
	{
		arrSections = arrDetailsPopupMap[strAccountType][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;
					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>";
								strDataSentence = strDataSentence.replace(":", ":</span>");
								arrFormattedPopup[strSection].push(strDataSentence);
								break;
								
								case 'no':
								break;
								
								default:
								if (arrRawProductData['Results'][j][strKeyName].fieldValue != -1)
								{
									var strDataSentence = "<span class='mx-dataFieldLabel'>" + arrRawProductData['Results'][j][strKeyName].fieldLabel.simple.replace("#VALUE#", arrRawProductData['Results'][j][strKeyName].fieldValue);
									strDataSentence = strDataSentence.replace(":", ":</span>");
									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:
									if (arrRawProductData['SponsoredResults'][k][strKeyName].fieldValue != -1)
									{
										var strDataSentence = "<span class='mx-dataFieldLabel'>" + arrRawProductData['SponsoredResults'][k][strKeyName].fieldLabel.simple.replace("#VALUE#", arrRawProductData['SponsoredResults'][k][strKeyName].fieldValue);
										strDataSentence = strDataSentence.replace(":", ":</span>");
										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 += "<p>" + strSectionName[strDetailRow] + "</p>";
			
			if (strDetailRow == strSectionName.length - 1)
			{
				if (strThisProductApplicationURL == '')
				{
					strThisPopup += "</div></div>";
				}
				else
				{
					strThisPopup += "<p class=\"mx-detailsPopupApplyLink\"><a target=\"_blank\" href=\"" + strThisProductApplicationURL + "\"><img src=\"/images/genesis/product/mx-apply-button-sll.jpg\" width\"79\" height=\"26\" alt=\"Apply\" /></a></p></div></div>";
				}
			}
		}
	}
	
	strThisPopup += "</div>";
	
	return strThisPopup;
}


function createSliders()
{
	$("#mx-currentAccountChargePerMonth").slider({
			animate: true,
			min: intChargePerMonthMin,
			max: intChargePerMonthMax,
			slide: function(event, ui)
					{
						$("#mx-currentAccountChargePerMonthText").val(ui.value);
					}
	});
	
	$("#mx-currentAccountChargePerMonth").slider('option', 'value', intChargePerMonthHandlePosition);
	
	$("#mx-currentAccountOverdraftFees").slider({
			animate: true,
			min: 0,
			max: intOverdraftFeesMax,
			slide: function(event, ui)
					{
						$("#mx-currentAccountOverdraftFeesText").val(ui.value);
					}
	});
	
	$("#mx-currentAccountOverdraftFees").slider('option', 'value', intOverdraftFeesHandlePosition);

	$("#mx-AccessTerm").slider({
			animate: true,
			min: intAccessTermMin,
			max: intAccessTermMax,
			slide: function(event, ui)
					{
						$("#mx-AccessTermText").val(ui.value);
					}
	});

	$("#mx-AccessTerm").slider('option', 'value', intAccessTermHandlePosition);
	
	$("#mx-currentAccountChargePerMonthText").bind("blur",
		function()
		{
			$("#mx-currentAccountChargePerMonth").slider("moveTo", $("#mx-currentAccountChargePerMonthText").val());
		}
	);

	$("#mx-currentAccountOverdraftFeesText").bind("blur",
		function()
		{
			$("#mx-currentAccountOverdraftFees").slider("moveTo", $("#mx-currentAccountChargePerMonthText").val());
		}
	);
	
	$("#mx-AccessTermText").bind("blur",
		function()
		{
			$("#mx-AccessTerm").slider("moveTo", $("#mx-AccessTermText").val());
		}
	);
}

function destroySliders()
{
	$("#mx-currentAccountChargePerMonth").slider("destroy");
	$("#mx-currentAccountOverdraftFees").slider("destroy");
	$("#mx-AccessTerm").slider("destroy");
}

