// Global JavaScript Document

/********** Global Popup **********/
document.onclick = function(e)
{
   var target = e ? e.target : window.event.srcElement;
   
   while (target && !/^(a|body)$/i.test(target.nodeName))
   {
      target = target.parentNode;
   }

   if (target && target.getAttribute('rel'))
   {
      // If no width or height is specified.
      if(target.rel == 'globalPopup')
	  { 
         globalPopup(target.href);
         return false;
      }
	  else
	  {
         // If a width and height is given.
         var targetRel = target.rel.split("-");
		 
         if(targetRel[0] == 'globalPopup')
		 {
            var width    = parseInt(targetRel[1]);
            var height   = parseInt(targetRel[2]);
			var linkHref = target.href;
			
			if(targetRel[3])
			{
				if(targetRel[3] == 'div')
				{
					var linkHrefRaw = target.href.split('/');
					linkHref = linkHrefRaw[linkHrefRaw.length-1];
				}
			}
			
            globalPopup(linkHref,width,height);
            return false;
         }
      }
   }
}

/********** Global Popup end **********/

/********** Item table sorting **********/
var sortDownloadsOrder      = 'DESC';
var sortDataSpeedtOrder     = 'DESC';
var sortMonthlyCostOrder    = 'ASC';
var sortContractLengthOrder = 'ASC';
var sortPriceOrder          = 'ASC';
var currentSearch           = '';

var prevColSort = "";
var colChange   = false;
var currentDir  = "";

function tableSortActions()
{
	if(getById("inclusivedata"))
		{
			var sortDownloadsBtn    = getById("inclusivedata");
			var downloadsSortColumn = sortDownloadsBtn.rel;
			
			sortDownloadsBtn.onclick = function()
			{
				if(prevColSort != "inclusivedata" && prevColSort != "")
				{
					colChange = true;
					currentDir = "";
				}
			
				prevColSort = "inclusivedata";
			
				unHighlightHeaderLinks();
				sortDownloadsBtn.style.backgroundImage = 'url(/templates/1/images/tab-backg-ov.jpg)';
				sortTable(sortDownloadsBtn.id, downloadsSortColumn, sortDownloadsOrder);
			}
		}
		
		if(getById("dataspeed"))
		{	
			var sortDataSpeedtBtn    = getById("dataspeed");
			var dataSpeedSortColumn = sortDataSpeedtBtn.rel;
			
			sortDataSpeedtBtn.onclick = function()
			{
				if(prevColSort != "dataspeed" && prevColSort != "")
				{
					colChange = true;
					currentDir = "";
				}
				
				prevColSort = "dataspeed";
			
				unHighlightHeaderLinks();
				sortDataSpeedtBtn.style.backgroundImage = 'url(/templates/1/images/tab-backg-ov.jpg)';
				sortTable(sortDataSpeedtBtn.id, dataSpeedSortColumn, sortDataSpeedtOrder);
			}
		}
		
		if(getById("dealmonthlyprice"))
		{
			var sortMonthlyCostBtn    = getById("dealmonthlyprice");
			var monthlycostSortColumn = sortMonthlyCostBtn.rel;
			
			sortMonthlyCostBtn.onclick = function()
			{
				if(prevColSort != "dealmonthlyprice" && prevColSort != "")
				{
					colChange = true;
					currentDir = "";
				}
				
				prevColSort = "dealmonthlyprice";
			
				unHighlightHeaderLinks();
				sortMonthlyCostBtn.style.backgroundImage = 'url(/templates/1/images/tab-backg-ov.jpg)';
				sortTable(sortMonthlyCostBtn.id, monthlycostSortColumn, sortMonthlyCostOrder);
			}
		}
		
		if(getById("dealterm"))
		{	
			var sortContractLengthBtn    = getById("dealterm");
			var contractlengthSortColumn = sortContractLengthBtn.rel;
			
			sortContractLengthBtn.onclick = function()
			{
				if(prevColSort != "dealterm" && prevColSort != "")
				{
					colChange = true;
					currentDir = "";
				}
				
				prevColSort = "dealterm";
			
				unHighlightHeaderLinks();
				sortContractLengthBtn.style.backgroundImage = 'url(/templates/1/images/tab-backg-ov.jpg)';
				sortTable(sortContractLengthBtn.id, contractlengthSortColumn, sortContractLengthOrder);
			}
		}
		
		if(getById("dealprice"))
		{	
			var sortPriceBtn    = getById("dealprice");
			var priceSortColumn = sortPriceBtn.rel;
			
			sortPriceBtn.onclick = function()
			{
				if(prevColSort != "dealprice" && prevColSort != "")
				{
					colChange = true;
					currentDir = "";
				}
				
				prevColSort = "dealprice";
			
				unHighlightHeaderLinks();
				sortPriceBtn.style.backgroundImage = 'url(/templates/1/images/tab-backg-ov.jpg)';
				sortTable(sortPriceBtn.id, priceSortColumn, sortPriceOrder);
			}
		}
}

function sortTable(sortBy, columnId, sortOrder)
{	
	// Do an AJAX call here to get the sorted results.
	var pageItemId = getById("page_item_id").value;
	// ********** For some reason this causes a growing grey bar at the top of the table. ********** //
	//$("#pricetable").load("/ajax/deal_sort.php?sortby=" + sortBy + '&iditems=' + pageItemId);
	
	if(colChange == false)
	{
		if(currentDir == "ASC")
		{
			currentDir = "DESC";
		}
		else
		{
			currentDir = "ASC";
		}
	}
	else
	{
		currentDir = sortOrder;
		colChange = false;
	}
	
	$.get("/ajax/deal_sort.php?sortby=" + sortBy + '&iditems=' + pageItemId + "&sortorder=" + currentDir, function(data)
	{
		$(".list_container").html('<table width="100%" border="0" cellspacing="0" cellpadding="0" class="nodetablerows" id="itemstable">' + data + '</table>');
		
		tableSortActions();
	});
	  
	// Show the results.
	$().ajaxStop(function(r,s){
		/*$("#contentLoading").fadeOut("fast");*/
		
		// Unhighlight any previously highlighted columns.
		for(var i = 1; i <= 8; i++)
		{	
			if("col_" + i != columnId)
			{
				var currentColumn = getByClass("col_" + i);
				
				for(var count = 0; count < currentColumn.length; count++)
				{
					currentColumn[count].style.backgroundColor = '#FFFFFF';
				}
			}
		}
		
		// Then highlight the column that has been sorted.
		var columnsSorted = getByClass(columnId);
		
		for(var i = 0; i < columnsSorted.length; i++)
		{
			columnsSorted[i].style.backgroundColor = '#F1F1F1';
		}
	});
}

function unHighlightHeaderLinks()
{
	var allLinks = getByClass("table_header_link");
	
	for(var i = 0; i < allLinks.length; i++)
	{
		allLinks[i].style.backgroundImage = 'none';
	}
}

tableSortActions();
/********** Item table sorting end **********/

/********** Rotating Banners **********/
var bannerNo = 1;
var lastBannerNo = 0;

function changeBanner()
{
	if(getById("banner_" + lastBannerNo))
	{
		$("#banner_" + lastBannerNo).fadeOut("slow");
	}
	
	$("#banner_" + bannerNo).fadeIn("slow");
	
	var bannersNumber = (bannersArray.length - 1);
	
	lastBannerNo = bannerNo;
	
	if(bannerNo <= bannersNumber)
	{
		bannerNo++;
		
		if(bannerNo > bannersNumber)
		{
			bannerNo = 1;
	    }
	}
	else
	{
		bannerNo = 1;
	}
	
	
}

var bannersArray = new Array();

function verifyEmail(email){
var status = false;     
var emailRegEx = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
     if (email.search(emailRegEx) == -1) {
          alert("Please enter a valid email address.");
     }
     else {
          status = true;
     }
     return status;
}

$(document).ready(function() {
	
	var browserName=navigator.appName; 
	
	if (browserName!="Microsoft Internet Explorer")
	{
			$(".explain-word").hover(function() {
				$(this).next("em").stop(true, true).animate({opacity: "show", top: "200"}, "slow");
				}, function() {
				$(this).next("em").animate({opacity: "hide", top: "300"}, "fast");
			});
	}
	else {
		$(".explain-word").hover(function() {
				$(this).next("em").show();
				}, function() {
				$(this).next("em").hide();
			});
	}

	
	$("#comment_submit").click(function() {
		
		if($("#comment_content").val()!="" && verifyEmail($("#comment_mail").val())) {
			$.post("/ajax/post_comment.php", { 
			idarticle: $("#article_id").val(),
			name: $("#comment_name").val(),
			mail: $("#comment_mail").val(),
			website: $("#comment_website").val(),
			content: $("#comment_content").val() }, function(data)
			{
				var countArt = parseInt($("#countArt").html()) + 1;
				
				if(isNaN(countArt)==true) { countArt = 1; }
				
				$("#countArt").html(countArt);
				$("#comments_list").html(data);
				$("#comment_content").val(""); 
			});
		}
		
	});

	$('a.zoomLinks').zoomimage({
								controls: false,
								opacity: 1,
								beforeZoomIn: function(boxID) {
									$('#' + boxID)
										.find('img')
										.css('opacity', 0)
										.animate(
											{'opacity':1},
											{ duration: 500, queue: false }
										);
								},
								beforeZoomOut: function(boxID) {
									$('#' + boxID)
										.find('img')
										.css('opacity', 1)
										.animate(
											{'opacity':0},
											{ duration: 500, queue: false }
										);
								}
							});

	
			$("#specandreviews").fancybox({
			    'padding'           : 0,
			    'width'           : 860,
			    'height'           : 580,
		        'autoScale'     	: false,
		        'transitionIn'		: 'none',
				'transitionOut'		: 'none'
			});

	if(getById("banner_area"))
	{	
		// Get all the banners
		var banners = getByClass("banner_item");
		var countDown = banners.length;
		
		// Loop through and make an array of all the banner codes
		for(var i = 0; i < banners.length; i++)
		{
			var bannerId = banners[i].id;
			var banner = getById(bannerId);
			
			if(bannerId != 'banner_1')
			{
				banner.style.display = "none";
			}
			
			var attributes = elementAttributes(getById(bannerId));
			var attributeStr = '';
			
			for(key in attributes)
			{
				attributeStr += ' ' + key + '="' + attributes[key] + '"';
			}
			
			bannersArray[countDown] = '<div ' + attributeStr + '>' + banner.innerHTML + '</div>';		
			countDown--;
		}
		
		if(bannersArray != 1)
		{
			changeBanner();
			var interval = setInterval("changeBanner()", 10000);
		}
	}
});


function showBox()
{
	if($("#etafLinkBoxBg").css("display") == "none")
	{
		$("#etafLinkNotifications").hide();
		$("#etafLinkBoxMainContent").show();
		$("#etafLinkBoxBg").css("display", "block");
		$("#recipientName").focus();
	}
	else
	{
		$("#etafLinkNotifications").hide();
		$("#etafLinkBoxMainContent").show();
		$("#etafLinkBoxBg").css("display", "none");
	}
}

function checkEmailAddress(str)
{
	var emailCorrect = false;
	
	var filter = /^.+@.+\..{2,3}$/;

	if(filter.test(str))
	{
    	emailCorrect = true;
 	}
	
	return emailCorrect;
}

function handleEtafSend()
{
	
	var recipientName  = $("#recipientName").val();
	var recipientEmail = $("#recipientEmail").val();
	var yourName       = $("#yourName").val();
	var sendDomain     = document.location.href.replace(/&/g, "{AND}");
	
	var etafErrors   = 0;
	var etafErrorMsg = "Please correct the following errors:\r\n\r\n";
	
	if(recipientName == "")
	{
		etafErrorMsg += "Enter the recipient name!\r\n";
		etafErrors++;
	}
	
	if(recipientEmail == "")
	{
		etafErrorMsg += "Enter the recipient email!\r\n";
		etafErrors++;
	}
	else if(!checkEmailAddress(recipientEmail))
	{
		etafErrorMsg += "Enter a valid recipient email!\r\n";
		etafErrors++;
	}
	
	if(yourName == "")
	{
		etafErrorMsg += "Enter the your name!\r\n";
		etafErrors++;
	}
	
	if(etafErrors == 0)
	{
		
		$.getJSON("/widgets/php/emailafriend.php?recipientName=" + recipientName + "&recipientEmail=" + recipientEmail + "&yourName=" + yourName + "&sendDomain=" + sendDomain, function(data)
		{
			if(data.result.match(/Email sent/))
			{
				$("#recipientName").val("");
				$("#recipientEmail").val("");
				$("#yourName").val("");
				$("#etafLinkBoxMainContent").hide();
				$("#etafLinkNotifications").html(data.result);
				$("#etafLinkNotifications").show();

			}
			else
			{
				alert(data.result);
			}
		});
	}
	else
	{
		alert(etafErrorMsg);
	}
}

// Predictive text search field.
if($("#main_text_search"))
{
	// Speed all the fades go at.
	var fadeSpeeds = "fast";
	
	// Fade speed for the action btn.
	var actionFade = "fast";
	
	// So we don't call duplicate queries.
	var lastValue  = "";
	
	// If the user uses the keyboard to navigate the suggestions, this keeps track of which suggestion is selected.
	var suggestionItem = 0;
	
	// Total suggestions that will show.
	var totalSuggestions = 10;
	
	// Lock key actions.
	var useKeys = true;
	
	// What will the textbox have in it as default?
	var defaultSearchText = 'Click here to search...';
	
	// Are the suggestions open?
	var suggestionsState = false;
	
	// Change the value of the text box.
	function changeTextSearch(id)
	{
		if(id == 1)
		{
			$("#main_text_search").val("");
		}
		else
		{
			$("#main_text_search").val(defaultSearchText);
		}
	}
	
	// Main close function.
	function closeSearchSuggestions()
	{	
		// Fade out the main div and show no close btn.
		$("#predictive_results_node").fadeOut(fadeSpeeds, function()
		{
			// Only hide action btns if there is nothing from the user in the text box.
			if($("#main_text_search").val() == "" || $("#main_text_search").val() == defaultSearchText)
			{
				$("#sactionicon").fadeOut(actionFade);
				$("#sactionicon").attr("class", "");
			}
		});
		
		suggestionsState = false;
		
		// Re show any select boxes hidden in IE6.
		if(identifyBrowser() == 'ie6')
		{
			if($(".hpselwrap"))
			{
				$(".hpselwrap").show();
			}
						
			if($("#laptopfilterselects"))
			{
				$("#laptopfilterselects").show();
			}
		}
	}
	
	function getNewResults(searchVal)
	{
		// Make the call.
		if (currentSearch != searchVal)
		{
			currentSearch = searchVal;
			
			$.get("/ajax/predictive_search.php?searchval=" + searchVal, function(data)
			{
				// This is so if a user deletes letter faster that the AJAX can get responces it forgets the previous calls.
				if($("#main_text_search").val() == searchVal)
				{	
					// Show the close btn.
					$("#sactionicon").attr("class", "sclose");
					$("#sactionicon").fadeIn(actionFade);
					
					// Split the suggestions from the total.
					dataSplit = data.split("|");
					
					totalSuggestions = dataSplit[1];
					
					// Show the new results.
					$("#preSUl").html(dataSplit[0]);
					$("#predictive_results_node").fadeIn(fadeSpeeds);
					suggestionsState = true;
					
					// If the user decides to use their mouse after using keys.
					$("#predictive_results_node ul li a").hover(function()
					{
						$("#predictive_results_node ul li a").attr("class", "up");
						$(this).attr("class", "over");
						
						// Start from the suggestion the mouse is over.
						var splitId = this.parentNode.parentNode.id.split("-");
						suggestionItem = splitId[1];
					},
					
					function()
					{
						$(this).attr("class", "up");
						
						// Start from the top.
						suggestionItem = 0;
					});
					
					// Hide select boxes under the results in IE 6.
					if(identifyBrowser() == 'ie6')
					{
						if($(".hpselwrap"))
						{
							$(".hpselwrap").hide();
						}
						
						if($("#laptopfilterselects"))
						{
							$("#laptopfilterselects").hide();
						}
					}
				}
			});
		}
	}
	
	function updateSuggestionItem(dir)
	{	
		$("#preSearchUlContainer ul li a").attr("class", "up");
		
		if(dir == 'down')
		{	
			if(suggestionItem < (totalSuggestions -1))
			{
				suggestionItem++;
			}
			else if(suggestionItem == (totalSuggestions -1))
			{
				suggestionItem = 1;
			}
		}
		else if(dir == 'up')
		{
			if(suggestionItem > 0)
			{
				suggestionItem--;
			}
		}
		
		$("#pi-" + suggestionItem + " a").attr("class", "over");
		
		// So if the user hold the direction keys down the selection doesn't just jump to the bottom or top.
		setTimeout("unlockKeys()", 50);
	}
	
	function unlockKeys()
	{
		useKeys = true;
	}
	
	function isTextBoxEmpty()
	{
		var complete = false;
		
		// Test to see if the value is just a load of spaces with no characters.
		var whiteSpaceStripped = $("#main_text_search").val().replace(/\s/g, "");
			
		// Is not empty.
		if($("#main_text_search").val() == '' || $("#main_text_search").val() == defaultSearchText || whiteSpaceStripped == "")
		{
			complete = true;
		}
		
		return complete;
	}
	
	// If the field is blured.
	$("#main_text_search").blur(function(e)
	{
		var textBoxValue = e.target.value;
		
		if(textBoxValue == '')
		{
			changeTextSearch(0);
		}
	});
	
	// Bring back suggestions on focus if keyword is still there.
	$("#main_text_search").focus(function(e)
	{
		if(suggestionsState == false)
		{
			var textBoxValue = e.target.value;
			
			if(textBoxValue != '' && textBoxValue != defaultSearchText)
			{
				getNewResults(textBoxValue)
			}
		}
		
		if(textBoxValue == defaultSearchText)
		{
			changeTextSearch(1);
		}
	});
	
	// Hanelding of text box blurs.
	$(document).click(function(e)
	{
		// If user clicked on the action btn.
		if(e.target.id == "sactionicon")
		{
			closeSearchSuggestions();
			lastValue  = "";
			$("#main_text_search").val("");
			$("#main_text_search").focus();
		}
		
		// This is the "Blur" event for the text box as long as user didn't click on "sactionicon" btn.
		if(e.target.id != "main_text_search" && e.target.id != "sactionicon")
		{
			closeSearchSuggestions();
		}
	});
	
	// So users cannot submit empty queries.
	$("#ss-send").click(function()
	{
		// Test to see if the value is just a load of spaces with no characters.
		var whiteSpaceStripped = $("#main_text_search").val().replace(/\s/g, "");
		
		// Is not empty.
		if(isTextBoxEmpty())
		{
			return false;
		}
	});
	
	// Initially create the DIV ready for all use.
	var predictiveResultsDiv = document.createElement('div');
				
	predictiveResultsDiv.setAttribute('id', "predictive_results_node");
	predictiveResultsDiv.style.visiblity = 'none';
	
	var predictiveSearchResults = '<div id="preSearchUlContainer"><ul id="preSUl"></ul></div><div id="ss-btm"></div>';
	
	predictiveResultsDiv.innerHTML = predictiveSearchResults;
	
	// Insert the new DIV into the page ready.
	getById("searchbarouter").insertBefore(predictiveResultsDiv, getById("searchbar-inner"));
	
	$("#main_text_search").attr("autocomplete", "off");
	
	// Handle keying up and down the suggestions.
	$("#main_text_search").keypress(function(e)
	{
		
		if (typeof document.body.style.maxHeight != "undefined") {
			
		
			if(useKeys)
			{
				var userkeyCode = e.keyCode;
				
				// User hit the down arrow.
				if(userkeyCode == 40)
				{
					useKeys = false;
					updateSuggestionItem("down");
					return false;
				}
				else if(userkeyCode == 38) // User hit the up arrow.
				{
					useKeys = false;
					updateSuggestionItem("up");
					return false;
				}
				else if(userkeyCode == 13) // User hit the enter key.
				{
					// User is keying around the suggestions.
					if(suggestionItem != 0)
					{
						window.location = $("#pi-" + suggestionItem + " a").attr("href");
						return false;
					}
					else
					{
						// User hit enter while in the text box.
						
						// Test to see if the value is just a load of spaces with no characters.
						var whiteSpaceStripped = $("#main_text_search").val().replace(/\s/g, "");
				
						// Is not empty.
						if(isTextBoxEmpty())
						{
							return false;
						}
					}
				}
			}
		
		}
		
	});
	
	$("#main_text_search").keyup(function(e)
	{
		var userkeyCode = e.keyCode;
		
		if(userkeyCode != 40 && userkeyCode != 38 && userkeyCode != 13) // User is typing as normal.
		{
			// Test to see if the value is just a load of spaces with no characters.
			var whiteSpaceStripped = $("#main_text_search").val().replace(/\s/g, "");
			
			// If the value is a valid keyword.
			if($("#main_text_search").val() != lastValue && !isTextBoxEmpty())
			{	
				suggestionItem = 0;
				lastValue      = $("#main_text_search").val();
				
				// Show loading gif.
				$("#sactionicon").attr("class", "sload");
				$("#sactionicon").fadeIn(actionFade);
				
				var searchVal = $("#main_text_search").val();
				
				// If there are spaces at the beginning then strip them out and use the keywords only.
				if($("#main_text_search").val().match(/^\s+.*$/))
				{
					searchVal = $("#main_text_search").val().replace(/^\s+/, "");
				}
				
				// Hide the previous results.
				$("#predictive_results_node").fadeOut(fadeSpeeds, function()
				{
					suggestionsState = false;
					getNewResults(searchVal);
				});
			}
			else
			{
				// Cryteria not met so show no results.
				if(isTextBoxEmpty())
				{
					suggestionItem = 0;
					lastValue      = "";
					closeSearchSuggestions();
				
					// Re show any select boxes hidden in IE6.
					if(identifyBrowser() == 'ie6')
					{
						if($(".hpselwrap"))
						{
							$(".hpselwrap").show();
						}
						
						if($("#laptopfilterselects"))
						{
							$("#laptopfilterselects").show();
						}
					}
				}
			}
		}
	});
}

// Compare table.
if($(".removecompareitem"))
{
	$(".removecompareitem").click(function()
	{
		$(".tdid_" + this.id).fadeOut();
		
		var compareCookie = getCookie('comparebasket');
		var placementVals = compareCookie.split("|");
		var newCookieVal  = '';
		var count = 0;
		
		for(var i = 0; i < placementVals.length; i++)
		{
			var splitVals = placementVals[i].split("=");
			
			if(parseInt(splitVals[1]) != this.id && placementVals[i] && placementVals[i] != '')
			{
				var oldPlacement = splitVals[0];
				var newPlacement = oldPlacement.replace(/[0-9]/, count);
				
				newCookieVal += placementVals[i].replace(oldPlacement, newPlacement) + "|";
				count++;
			}
		}
		
		setCookie('comparebasket', newCookieVal, 3600);
		
		return false;
	});
}

// This gives the row highlighting on tables.
function setTableRowHovers(tableId, rowClassName, hoverColour)
{
	var origBgColour;

	$('#' + tableId + ' tr').hover(function()
	{
		if(this.className == rowClassName)
		{
			var rowHTML  = this.innerHTML;
			var rowCells = $(this).find("td");
		
			for(var i = 0; i < rowCells.length; i++)
			{
				origBgColour = rowCells[i].style.backgroundColor;
				rowCells[i].style.backgroundColor = hoverColour;
			}
		}
	},
	
	function()
	{
		if(this.className == rowClassName)
		{
			var rowHTML  = this.innerHTML;
			var rowCells = $(this).find("td");
		
			for(var i = 0; i < rowCells.length; i++)
			{
				rowCells[i].style.backgroundColor = origBgColour;
			}
		}
	});
}

var sortStatus = $("#issorted").val();

if(sortStatus == "false" || sortStatus == "")
{
	// Table hovers on item.php
	if($("#pricetable"))
	{
		setTableRowHovers('pricetable', 'itemtablerows', '#F1F1F1');
	}

	// Table hovers on node.php
	if($("#itemstable"))
	{
		setTableRowHovers('itemstable', 'itemtablerows', '#F1F1F1');
	}

	// Table hovers on compare-laptops.php
	if($("#comparelaptops"))
	{
		setTableRowHovers('comparelaptops', 'comparetablerow', '#CCCCCC');
	}
	
	// Table hovers on mobile broadband tables
	if($("#mbbdeals"))
	{
		setTableRowHovers('mbbdeals', 'dealtablerows', '#F1F1F1');
	}
	
	// Table hovers on mobile broadband tables
	if($("#paygmbbdeals"))
	{
		setTableRowHovers('paygmbbdeals', 'paygdealtablerows', '#F1F1F1');
	}
}

// Set up any historyback links to go back when clicked.
var historyBackLinks = $(document).find(".historyback");

if(historyBackLinks.length > 0)
{
	$(".historyback").click(function()
	{
		history.go(-1);
		return false;
	});
}


var thisBrowser = identifyBrowser();

if(thisBrowser != 'ie6')
{
	// Give any div with the rc class rounded corners.
	$(".rc").append('<span class="tl"></span><span class="tr"></span><span class="bl"></span><span class="br"></span>');
	$(".rc-t").append('<span class="tl"></span><span class="tr"></span>');
	$(".rc-b").append('<span class="bl"></span><span class="br"></span>');
	$(".rc-l").append('<span class="tl"></span><span class="bl"></span>');
	$(".rc-r").append('<span class="tr"></span><span class="br"></span>');
}

// This is for the submit button on the homepage to submit a filter search.
if($("#hpfs"))
{
	$("#hpfs").click(function()
	{
		$("#laptopfilterselects").submit();
		return false;
	});
}



// Highlight colums for sorting.
var currentUrl = window.location.search;

var matchedParam = currentUrl.match(/scb=([a-z]{0,3})/);

if(matchedParam)
{
	var getClassKey = matchedParam[1];
	
	$("." + getClassKey + "cell").css("backgroundColor", "#f1f1f1");
}

// Hovers for recommended laptops.
$(".laptoptitle").hover(function()
{
	var rowIdSplit = this.id.split("-");
	var rowId = rowIdSplit[1];
	$("#title-" + rowId).css("textDecoration", "underline");
},
function()
{
	var rowIdSplit = this.id.split("-");
	var rowId = rowIdSplit[1];
	$("#title-" + rowId).css("textDecoration", "none");
});

if(document.getElementById("isnodepage") && identifyBrowser() != "ie6")
{
	var divAfter  = "wrapper";
	var divBefore = "header";
	
	var headerWrapper = document.createElement('div');
	headerWrapper.setAttribute('id', 'floatingHeaders');
	
	$("#floatingHeaders").css("display", "none");
	
	getById(divAfter).insertBefore(headerWrapper, getById(divBefore));
	
	var headersHTML = '<span><table id="" class="nodetablerows" width="100%" cellspacing="0" cellpadding="0" border="0"><tbody><tr class="nonreltabs headernode">';
	headersHTML += $(".headernode").html();
	headersHTML += '</tr></tbody></table></span>';
	
	// This is to match when an item has been selected and swap the header col classes for different widths.
	if(location.href.indexOf("item.html") != -1)
	{
		headersHTML = headersHTML.replace("modelcol", "modelcol-fl");
		headersHTML = headersHTML.replace("screencol", "screencol-fl");
		headersHTML = headersHTML.replace("procesorcol", "procesorcol-fl");
		headersHTML = headersHTML.replace("ramcol", "ramcol-fl");
		headersHTML = headersHTML.replace("harddrivecol", "harddrivecol-fl");
		headersHTML = headersHTML.replace("oscol", "oscol-fl");
		headersHTML = headersHTML.replace("retalercol", "retalercol-fl");
		headersHTML = headersHTML.replace("pricecol", "pricecol-fl");
	}
	
	$("#floatingHeaders").html(headersHTML);
	
	$(window).scroll(function()
	{
		var scollPos = getScrollPosition();
		
		var headersPosRaw = $("#itemstable").position();
		var headersPos = headersPosRaw.top;
		
		if(scollPos[1] > headersPos)
		{
			$("#floatingHeaders").css("display", "block");
		}
		else
		{
			$("#floatingHeaders").css("display", "none");
		}
	});
}

/********** FULL CLICKABLE TABLE ROWS **********/
if($(".comparecol p a").length)
{
	if($(".buy_now_link").html() != null || $(".comparecol p a").attr("href").match("/out.php?"))
	{
		$(".itemtablerows").css("cursor", "pointer");
		
		$(".itemtablerows").click(function()
		{	
			if(1 == 1)
			{
				var sentToUrl = false;
				
				if(sentToUrl == false)
				{
					if($(".comparecol").find("a"))
					{
						$(this).find(".comparecol").find("a").triggerHandler('click');
						
						if($(this).find(".comparecol").find("a").attr("href"))
						{
							sentToUrl = true;
							
							if($(this).find(".comparecol").find("a").attr("href").match("/out.php?"))
							{
								window.open($(this).find(".comparecol").find("a").attr("href"));
							}
							else
							{
								window.location = $(this).find(".comparecol").find("a").attr("href");
							}
						}
					}
				}
				
				if(sentToUrl == false)
				{
					if($(".pricecol").find("a"))
					{
						$(this).find(".pricecol").find("a").triggerHandler('click');
						
						if($(this).find(".pricecol").find("a").attr("href"))
						{
							sentToUrl = true;
							
							if($(this).find(".pricecol").find("a").attr("href").match("/out.php?"))
							{
								window.open($(this).find(".pricecol").find("a").attr("href"));
							}
							else
							{
								window.location = $(this).find(".pricecol").find("a").attr("href");
							}
						}
					}
				}
			}
			
			return false;
		});
	}
}

if($(".dealtablerows"))
{
	$(".dealtablerows").css("cursor", "pointer");
	
	$(".dealtablerows").click(function()
	{
		var rowGoToLink = "";
		
		if($(this + ".mbb-retailer-col a"))
		{
			$(this + ".mbb-retailer-col a").triggerHandler('click');
			
			window.open($(this).find(".mbb-retailer-col").find("a").attr("href"));
		}
		
		return false;
	});
}

/********** FULL CLICKABLE TABLE ROWS END **********/

/********** DYNAMIC SITE SEARCH FILTERS **********/

// Read a page's GET URL variables and return them as an associative array.
function getUrlVars()
{
	var vars = [], hash;
	var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');

    for(var i = 0; i < hashes.length; i++)
	{
		hash = hashes[i].split('=');
		vars.push(hash[0]);
		vars[hash[0]] = hash[1];
	}
	
	$("#filter-cond").val(vars['cond']);
	$("#filter-price").val(vars['price']);
	$("#filter-ss").val(vars['ss']);
	$("#filter-ps").val(vars['ps']);
	$("#filter-hd").val(vars['hd']);
	$("#filter-manu").val(vars['manu']);
	$("#filter-ret").val(vars['ret']);
	
}
      
var linkpage = location.href.split('?');

// Start the query string for the AJAX call.
var queryParams = "/ajax/dynamic_filters.php?ajax=1";

$("#resetfsearch").click(function()
	{
		queryParams = "/ajax/dynamic_filters.php?ajax=1";
		
		updateFilterSelects();
		
		return true;
	});
	
	
function updateFilterSelects(etat)
{
	if(etat == 1)
	{
		queryParams += ("&" + linkpage[1]);
	}
	
	$.get(queryParams, function(data)
	{
		// Get the bands seperated.
		var splitBandsRaw = data.split("|");
		
		// Remove any blank elements.
		var splitBandsClean = new Array();
		
		// Loop to remove blank elements and make the array structured: key = band type name, value = html.
		for(var i = 0; i < splitBandsRaw.length; i++)
		{
			if(splitBandsRaw[i] != "")
			{
				splitBandElement = splitBandsRaw[i].split("=>");
				
				var bandElementKey  = splitBandElement[0];
				var bandElementHtml = splitBandElement[1];
				
				splitBandsClean[bandElementKey] = bandElementHtml;
			}
		}
		
		// This is for translations between band type names and select IDs.
		var selectTypeIds = new Array();
		
		selectTypeIds["reconditioned"]        = "filter-cond";
		selectTypeIds["price_band"]           = "filter-price";
		selectTypeIds["screensize"]           = "filter-ss";
		selectTypeIds["processor_speed_band"] = "filter-ps";
		selectTypeIds["hard_drive_band"]      = "filter-hd";
		selectTypeIds["idmanufacturers"]      = "filter-manu";
		selectTypeIds["idretailers"]          = "filter-ret";
		
		// Set the new select values.
		for(key in splitBandsClean)
		{
			$("#" + selectTypeIds[key]).html(splitBandsClean[key]);
		}
		
		if(etat==1)
		{
			getUrlVars();
		}
	});
}

if($("#laptopfilterselects").length)
{
	$("#laptopfilterselects select").change(function()
	{
		queryParams = "/ajax/dynamic_filters.php?ajax=1";
		
		// Grab all the selects.
		var allFilterSelects = $("#laptopfilterselects select");
		
		// Loop through all the select boxes.
		for(var i = 0; i < allFilterSelects.length; i++)
		{
			// Grab the current values for the specific filters.
			switch(i)
			{
				case 0:
					queryParams += "&cond=" + $(allFilterSelects[i]).val();
					break;
				case 1:
					queryParams += "&price=" + $(allFilterSelects[i]).val();
					break;
				
				case 2:
					queryParams += "&ss=" + $(allFilterSelects[i]).val();
					break;
					
				case 3:
					queryParams += "&ps=" + $(allFilterSelects[i]).val();
					break;
					
				case 4:
					queryParams += "&hd=" + $(allFilterSelects[i]).val();
					break;
					
				case 5:
					queryParams += "&manu=" + $(allFilterSelects[i]).val();
					break;
					
				case 6:
					queryParams += "&ret=" + $(allFilterSelects[i]).val();
					break;
			}
		}
		
		updateFilterSelects();
	});
	
	$(document).ready(function()
	{
		updateFilterSelects(1);
		
	});
}
/********** DYNAMIC SITE SEARCH FILTERS END **********/


function mainmenu(){
	$(" #nav ul ").css({display: "none"}); // Opera Fix
	$(" #nav li").hover(function(){
		
		$(this).find('ul:first').css({visibility: "visible",display: "none"}).show(400);
				},function(){
				$(this).find('ul:first').css({visibility: "hidden"});
				});
				
}

var $dialog = $('<div></div>')
		.dialog({
			autoOpen: false,
			height: 760,
			width: 600,
			draggable: false,
			resizable: false,
			close: function(ev, ui) {
			     $('#searchbar').show();
			},
			title: 'Leave a review on Shoplaptop.co.uk'
		});
		
	$('.opendialog').click(function() {

	$.get("/review.php?id="+ $('#item_id').val(), function(data)
	{
		$dialog.html(data);
		
		$('#searchbar').hide();
	});
		
	$dialog.dialog('open');
	
});