$(document).ready(function()
{
	$("#mx-paginationButtons").css("display", "block");
});

function bindPaginationButtons()
{
	$("#mx-nextPage").bind("click", function(){
			val = parseInt($("#mx-ResultOffset").val());
			$("#mx-ResultOffset").val(val+intResultToReturn);
			postData();
			window.scrollTo(0,0);
		}
	);
	
	$("#mx-previousPage").bind("click", 
		function()
		{
			val = parseInt($("#mx-ResultOffset").val());
			$("#mx-ResultOffset").val(val-intResultToReturn);
			postData();
			window.scrollTo(0,0);
		}
	);
	
	$("#mx-firstPage").bind("click", 
		function()
		{
			$("#mx-ResultOffset").val(0);
			postData();
			window.scrollTo(0,0);
		}
	);

	$("#mx-lastPage").bind("click", 
		function()
		{
			$("#mx-ResultOffset").val((intTotalPages-1)*intResultToReturn);
			postData();
			window.scrollTo(0,0);
		}
	);
}

function setPagination(intTotalPages, intCurrentPage)
{
	intTotalPages = (intTotalPages == 0) ? 1 : intTotalPages;
	
	if (intCurrentPage == intTotalPages)
	{
		$("#mx-nextPage").attr("disabled","true");
		$("#mx-lastPage").attr("disabled","true");
	}
	else
	{
		$("#mx-nextPage").removeAttr("disabled");
		$("#mx-lastPage").removeAttr("disabled");
	}
	if (intCurrentPage == 1)
	{
		$("#mx-previousPage").attr("disabled","true");
		$("#mx-firstPage").attr("disabled","true");
	}
	else
	{
		$("#mx-previousPage").removeAttr("disabled");
		$("#mx-firstPage").removeAttr("disabled");
	}
	
	$("#mx-currentPage").html(intCurrentPage);
	$("#mx-totalPages").html(intTotalPages);
}

function calculateCurrentPage(intResultOffset, intResultToReturn)
{
	var intCurrentPage = (intResultOffset/intResultToReturn)+1;
	return intCurrentPage;
}

function sortBy(strSortBy)
{
	if ($("#mx-sortOrder").val() == strSortBy)
	{
		if ($("#mx-sortAttribute").val() == 'ascending')
		{
			$("#mx-sortAttribute").val("descending");
		}
		else
		{
			$("#mx-sortAttribute").val("ascending");
		}
	}
	else
	{
		$("#mx-sortAttribute").val("ascending");
	}
	$("#mx-sortOrder").val(strSortBy);
	$("#mx-ResultOffset").val(0);
	postData();
}

function setSortImages(strSortFieldName, strMethod)
{
	$(".mx-sorter").html("");

	if ( strMethod == "ascending" )
	{
		var strImg = '<img src="/images/up.gif" />';
	}
	else
	{
		var strImg = '<img src="/images/down.gif" />';
	}

	$('.mx-'+strSortFieldName).html(strImg);
}

function cycleProviders(arrProviderList)
{
	var i = 0;
	var strArrayLength = arrProviderList.providers.length;
	realAlertProviders();
	function realAlertProviders()
	{
		$("#mx-cycleProviders").html(arrProviderList.providers[i]);
		if ( i <= strArrayLength )
		{
			t = setTimeout(realAlertProviders, 1500);
		}
		i++;
	}
}

function destroyPrequalificationQuestions(intProductId)
{
	strPopupId = 'mx-PrequalPopup_' + intProductId;
	$('#' + strPopupId).remove();

	/*
	$('#' + strPopupId).fadeOut(1500, function() {
		$(this).remove();
 	});
 	*/ 
}

function popupPrequalificationQuestions(intProductId, objReference)
{
	var boolDebug = false;
	var boolFoundPrequal = false;
	var objFoundProduct = {};
	var objPrequalData = {};
	var fltFlipPointPercentageX = 0.5;
	var fltFlipPointPercentageY = 0.5;

	if (!boolFoundPrequal)
	{
		for(var intResultIndex in arrRawProductData['SponsoredResults']) // Loop through sponsored 
		{
			if (arrRawProductData['SponsoredResults'][intResultIndex].ProductId == intProductId)
			{
				objFoundProduct = arrRawProductData['SponsoredResults'][intResultIndex];
				boolFoundPrequal = true;
			}
		}
	}

	if (!boolFoundPrequal)
	{
		for(var intResultIndex in arrRawProductData['Results']) // If not found in sponsored loop through unsponsored 
		{
			if (arrRawProductData['Results'][intResultIndex].ProductId == intProductId)
			{
				objFoundProduct = arrRawProductData['Results'][intResultIndex];
				boolFoundPrequal = true;
			}
		}
	}

	if (boolFoundPrequal)
	{
		objPrequalData.Notes = objFoundProduct.PrequalificationNotesText;
		objPrequalData.Questions = objFoundProduct.PrequalificationQuestions;
		objFoundProduct = {};
		strPopupId = 'mx-PrequalPopup_' + intProductId;

		strQuestionsHTML = '';
		for (var intQuestionIndex in objPrequalData.Questions)
		{
			strQuestionsHTML += '				<tr>\n';
			strQuestionsHTML += '					<th><img src="/images/debt-management-tick.jpg" /></th>\n';
			strQuestionsHTML += '					<td>' + objPrequalData.Questions[intQuestionIndex] + '</td>\n';
			strQuestionsHTML += '				</tr>\n';
		}

		strPopupHTML = '';
		strPopupHTML += '<div class="mx-applyPopUpContainer" id="' + strPopupId + '" style="display: none;">\n';		
		strPopupHTML += '	<div class="mx-applyPopUpContent">\n';
		strPopupHTML += '		<div class="mx-importantApplyInformation">\n';
		strPopupHTML += '			<h1>Important - If you apply</h1>\n';
		strPopupHTML += '			<p>' + objPrequalData.Notes + '</p>\n';
		strPopupHTML += '			<table class="mx-criteria" cellpadding="0" cellspacing="0">\n';
		strPopupHTML += strQuestionsHTML;		
		strPopupHTML += '			</table>\n';
		strPopupHTML += '		</div>\n';
		strPopupHTML += '	</div>\n';
		strPopupHTML += '</div>\n';

		$('body').prepend(strPopupHTML);
		
		objButtonPosition = $(objReference).offset();
		
		intButtonCenterX = objButtonPosition.left + ($(objReference).width() / 2);
		intButtonCenterY = objButtonPosition.top - ($(objReference).height() / 2);

		intScrollPosX = $(window).scrollLeft();
		intScrollPosY = $(window).scrollTop();

		intRelativeButtonCentreX = intButtonCenterX - intScrollPosX;
		intRelativeButtonCentreY = intButtonCenterY - intScrollPosY;

		intWindowWidth = $(window).width();
		intWindowHeight = $(window).height();

		fltPercentageX = intRelativeButtonCentreX / intWindowWidth;
		fltPercentageY = intRelativeButtonCentreY / intWindowHeight;

		strArrowBackgroundPositionCSS = '';

		if (fltPercentageX > fltFlipPointPercentageX)
		{
			$('#' + strPopupId).addClass('mx-appyPopUpContainerArrowRight');
			strArrowBackgroundPositionCSS += 'right'; // Arrow placement to right of popup
		}
		else
		{
			$('#' + strPopupId).addClass('mx-appyPopUpContainerArrowLeft');
			strArrowBackgroundPositionCSS += 'left'; // Arrow placement to left of popup
		}

		if (fltPercentageY > fltFlipPointPercentageY)
		{
			strArrowBackgroundPositionCSS += ' bottom'; // Arrow placement to bottom of popup
		}
		else
		{
			strArrowBackgroundPositionCSS += ' top'; // Arrow placement to top of popup
		}

		$('#' + strPopupId).css('background-position', strArrowBackgroundPositionCSS);
		
		intPopupWidth = $('#' + strPopupId).outerWidth();
		intPopupHeight = $('#' + strPopupId).outerHeight();

		fltPercentageX = intRelativeButtonCentreX / intWindowWidth;
		fltPercentageY = intRelativeButtonCentreY / intWindowHeight;

		if (fltPercentageX > fltFlipPointPercentageX)
		{
			intPopupLeftPos = intButtonCenterX - intPopupWidth - ($(objReference).width() / 2); // Popup placement to left of button
			strHorizontalPlacement = 'ToLeft';
		}
		else
		{
			intPopupLeftPos = intButtonCenterX + ($(objReference).width() / 2);  // Popup placement to right of button
			strHorizontalPlacement = 'ToRight';
		}

		
		intVerticalArrowNudge = 15;

		intIENudgeValue = ($.support.cssFloat) ? 0 : intVerticalArrowNudge; // If using IE needs a bit of a nudge down..

		if (fltPercentageY > fltFlipPointPercentageY)
		{
			intPopupTopPos = intButtonCenterY - intPopupHeight + ($(objReference).height() / 2) + intVerticalArrowNudge + intIENudgeValue;
			strVerticalPlacement = 'ToTop';
		}
		else
		{
			intPopupTopPos = intButtonCenterY + ($(objReference).height() / 2) - intVerticalArrowNudge + intIENudgeValue; 
			strVerticalPlacement = 'ToBottom';
		}
		
		if (boolDebug)
		{
			strDebug = '';
			strDebug += 'Button Centre X: ' + intButtonCenterX + '\n';

			strDebug += 'Button Centre Y: ' + intButtonCenterY + '\n';
			strDebug += 'Relative Button Centre X: ' + intRelativeButtonCentreX + '\n';
			strDebug += 'Relative Button Centre Y: ' + intRelativeButtonCentreY + '\n';
			strDebug += 'Scroll Top X: '  + intScrollPosX + '\n';
			strDebug += 'Scroll Top Y: '  + intScrollPosY + '\n';
			strDebug += 'Window Width: '  + intWindowWidth + ' (' + fltPercentageX + ')' + '\n';
			strDebug += 'Window Height: '  + intWindowHeight + ' (' + fltPercentageY + ')' + '\n';
			strDebug += strVerticalPlacement + ' ' + strHorizontalPlacement + '\n';

			alert(strDebug);
		}

    	$('#' + strPopupId).css({
								position: "absolute",
								marginLeft: 0, marginTop: 0,
								top: intPopupTopPos, left: intPopupLeftPos
							});
            									
		$('#' + strPopupId).show();
		//$('#' + strPopupId).fadeIn(500);
	}
}