/*!
 * Compare Basket JS V1.0
 * http://www.shoplaptop.co.uk
 *
 * Copyright (c) 2009 http://www.shoplaptop.co.uk
 *
 * Author Dan Whitfield
 *
 * Date: 22-04-2009 (Wed, 22 Apr 2009)
 */

// Check that there is a compare basket.
if($("#comparebasket"))
{
	// Make sure that there are no more than the limited amount of items in the basket.
	var basketLimit = 4;
	var basketTotal = 0;
	
	// Limit the length of model names.
	var nameLength = 20;
	
	// Keep track of which image is being dragged.
	var activeImage = '';
	
	// Get the original placement image path for resetting images.
	var comparePlacesOriginalSrc = $("#compareplace0").attr("src").replace("1.gif", "");
	
	// This holds the compare palcement number, item ID and item src for each item added into the basket.
	var comparePlaces = new Array();
	
	// Fill the comparePlaces array with it's placements.
	for(var i = 0; i < basketLimit; i++)
	{	
		// If a placement is blank it has no item in it.
		comparePlaces[i] = '';
	}
	
	// Find the next blank placement that is ok to use.
	function getBlankPlacement()
	{	
		// Loop through all the placements to see if they have an ims src taken from an item.
		for(var i = 0; i < comparePlaces.length; i++)
		{
			if(comparePlaces[i] == '')
			{
				// Return the name of the next blank placement.
				return "compareplace" + i;
			}
		}
	}
	
	// Check if a value is in an array.
	function inArray(needle, haystack)  
	{
		// Loop through each element in the array.
		for(var i in haystack)
		{
			var checkElement = haystack[i].split("|");
			
			// If the value is in the array return true.
			if(needle == checkElement[1])
			{
				return true;
			}
		}  
	} 
	
	// Store the compare placements in a cookie.
	function storeComparePlacements()
	{	
		var cookieValue    = '';
		
		// Loop around for each placement.
		for(var i = 0; i < basketLimit; i++)
		{
			// Split each element to get the info needed.
			var placementInfo = comparePlaces[i].split("|");
			
			// Check that the entrys in the compareIds array are not empty.
			if(placementInfo[1] == '')
			{
				cookieValue += "compareplace" + i + "=|";
			}
			else
			{
				// Add the item ID and src of the image.
				cookieValue += "compareplace" + i + "=" + placementInfo[0] + "=" + placementInfo[1] + "=" + placementInfo[2] + "|";
			}
		}
		
		// Set the cookie for the compare basket.
		setCookie('comparebasket', cookieValue, 3600);
		
		// Disable the checkboxes that are unchecked if the basketLimit is reached.
		if(basketTotal == basketLimit)
		{
			$(".comparecheckbox").attr("disabled", "disabled");
			$(".comparecheckbox:checked").removeAttr("disabled");
		}
		else
		{
			$(".comparecheckbox").removeAttr("disabled");
		}
	}
	
	// This is so when the page loads it loads the content of the basket and checks the relevant checkboxes.
	function loadCompareBasket()
	{
		// Get the item id's from the cookie.
		var compareCookie = getCookie('comparebasket');
		var placementVals = compareCookie.split("|");
		
		// Loop around each id in placementVals to set the item into a placement.
		for(var i = 0; i < placementVals.length; i++)
		{
			var itemInfo = placementVals[i].split("=");
			
			if(itemInfo[1] && itemInfo[1] != '' && itemInfo[1] != 'undefined')
			{	
				// Get a placement that we can use.
				var usePlacement = getBlankPlacement();
				
				// Retreive the item ID and src.
				activeImageId = itemInfo[1];
				var imgSrc = itemInfo[2];
				var imgAlt = itemInfo[3].substr(0, nameLength);
				
				// Only add the item if it is not already in there and if the basket is not full.
				if(!inArray(imgSrc, comparePlaces) && basketTotal < 4)
				{
					// Show the item image and alt in the placement.
					$("#" + usePlacement).attr("src", imgSrc);
					$("#" + usePlacement).attr("alt", imgAlt);
					$("#" + usePlacement).attr("title", imgAlt);
					
					// Show the model name of the item in the compare basket.
					$("#" + usePlacement + "-p").html(imgAlt);
				
					// Add the item into the comparePlaces array.
					var placementNumber = parseInt(usePlacement.replace("compareplace", ""));
					comparePlaces[placementNumber] = activeImageId + "|" + imgSrc + "|" + imgAlt;
					
					// Check the corisponding checkbox.
					$("#compare_" + activeImageId).attr("checked", "checked");
					
					// Increment the total of items by 1.
					basketTotal++;
				}
			}
		}
		
		// Store the state of the placements.
		storeComparePlacements();
	}
	
	// This add items to the compare basket for both drags and checkboxes.
	function addCompareItem()
	{
		// Get the item id of the item to be added into the compare basket.
		if(activeImage.match("laptop_"))
		{
			// If the addition came from a drag remove the string "laptop_" to get the ID.
			var activeImageId = parseInt(activeImage.replace("laptop_", ""));
		}
		else
		{
			// If the addition came from a checkbox click remove the string "compare_" to get the ID.
			var activeImageId = parseInt(activeImage.replace("compare_", ""));
		}
			
		// Get a placement that we can use.
		var usePlacement = getBlankPlacement();
		
		// Get the img src and alt that need to go into a compare basket placement.
		var imgSrc = $(".laptop_" + activeImageId).attr("src");
		var imgAlt = $(".laptop_" + activeImageId).attr("alt").substr(0, nameLength);
		
		// Only add the item if it is not already in there and if the basket is not full.
		if(!inArray(imgSrc, comparePlaces) && basketTotal < 4)
		{	
			// Show the item image and alt in the placement.
			$("#" + usePlacement).attr("src", imgSrc);
			$("#" + usePlacement).attr("alt", imgAlt);
			$("#" + usePlacement).attr("title", imgAlt);
			
			// Show the model name of the item in the compare basket.
			$("#" + usePlacement + "-p").html(imgAlt);
		
			// Add the item into the comparePlaces array.
			var placementNumber = parseInt(usePlacement.replace("compareplace", ""));
			comparePlaces[placementNumber] = activeImageId + "|" + imgSrc + "|" + imgAlt;
			
			// Check the corisponding checkbox.
			$(".compare_" + activeImageId).attr("checked", "checked");
			
			// Increment the total of items by 1.
			basketTotal++;
			
			// Store the state of the placements.
			storeComparePlacements();
		}
	}
	
	// This handles removing an item from the compare basket.
	function removeCompareItem(id)
	{	
		// Get the item id of the item to be removed from the compare basket.
		if(id.match("laptop_"))
		{
			// If the removal came from a drag remove the string "laptop_" to get the ID.
			var itemId    = parseInt(id.replace("laptop_", ""));
			var removeSrc = $(".laptop_" + itemId).attr("src");
			var removeAlt = $(".laptop_" + itemId).attr("alt").substr(0, nameLength);
		}
		else
		{
			// If the removal came from a checkbox click remove the string "compare_" to get the ID.
			var itemId    = parseInt(id.replace("compare_", ""));
			var removeSrc = $(".laptop_" + itemId).attr("src");
			var removeAlt = $(".laptop_" + itemId).attr("alt").substr(0, nameLength);
		}
		
		var placmentToReset = '';
		
		// Loop through the compare basket and find the placement to reset.
		for(var i = 0; i < basketLimit; i++)
		{	
			var checkSrc = $("#compareplace" + i).attr("src");
			
			// Set the placement to reset if the placement src matches that of the removed item.
			if(checkSrc == removeSrc)
			{
				placmentToReset = "compareplace" + i;
			}
		}
		
		// Loop through and reset the element that had held the item src.
		for(var i = 0; i < comparePlaces.length; i++)
		{
			if(comparePlaces[i] == itemId + "|" + removeSrc + "|" + removeAlt)
			{
				comparePlaces[i] = '';
			}
		}
		
		// Get the placement number from the placementToReset variable.
		var resetSrcId  = parseInt(placmentToReset.replace("compareplace", "")) + 1;
		
		// Reset the placement image to show a blank placement.
		$("#" + placmentToReset).attr("src", comparePlacesOriginalSrc + resetSrcId + ".gif");
		$("#" + placmentToReset).attr("alt", "");
		$("#" + placmentToReset).attr("title", "");
		
		// Remove the model name of the item in the compare basket.
		$("#" + placmentToReset + "-p").html("&nbsp;");
		
		// Update the basketTotal.
		basketTotal--;
		
		// Store the state of the placements.
		storeComparePlacements();
	}
	
	// Reset the placements on click of the clear button.
	$("#clearcomparebasket").click(function()
	{
		// Loop through all placements.
		for(var i = 0; i < comparePlaces.length; i++)
		{	
			// Remove the images from the placements.
			comparePlaces[i] = '';
			
			// Put the original placement images back.
			var imgSrcNo = i + 1;
			$("#compareplace" + i).attr("src", comparePlacesOriginalSrc + imgSrcNo + ".gif");
			$("#compareplace" + i).attr("alt", "");
			$("#compareplace" + i).attr("title", "");
			
			// Remove the model names.
			$("#compareplace" + i + "-p").html("&nbsp;");
			
			// Reset the number of items in the basket to 0.
			basketTotal = 0;
			
			// Delete the cookie that holds the item id's.
			deleteCookie("comparebasket");
		}
		
		// Reset the checkboxes.
		$(".comparecheckbox").removeAttr("checked");
		$(".comparecheckbox").removeAttr("disabled");
	});
	
	// Set the item image as draggable.
	/*$(".laptopimg").draggable({ revert: true, scrollSensitivity: 50, scrollSpeed: 40, opacity: 0.35, drag: function()
	{
		// Set the activeImage ready for the on drop event.
		activeImage = this.id;
	}});*/
	
	// On drop event adds a dropped item.
	$("#selectedlaptops").droppable({ drop: function()
	{
		addCompareItem();
	}});
	
	// If a checkbox is clicked.
	$(".comparecheckbox").click(function()
	{
		// Either add or remove an item depending on the checkbox's check state.
		if(this.checked == false)
		{
			removeCompareItem(this.id);
		}
		else
		{	
			if(basketTotal < basketLimit)
			{
				activeImage = this.id;
				addCompareItem();
			}
		}
	});
	
	// If a user tries to add an item to a full basket.
	$(".checkboxbg").click(function()
	{
		var thisCheckbox = $(this).find("input");
		
		if(thisCheckbox.attr("disabled") == true)
		{
			globalPopup("/static/comparebasket/basketfull.html", 360, 170);
		}
	});
	
	function compareSubmit()
	{
		// Get the item id's from the cookie.
		var compareCookie = getCookie('comparebasket');
		var placementVals = compareCookie.split("|");
		
		// This is the page that will show comparisons.
		var compareUrl = '/compare-laptops.php?';
		
		// Turns true after one loop so an & symbol is not added imidiately after the ? in the URL.
		var firstParam = false;
		
		// Loop through all the placements that have values.
		for(var i = 0; i < placementVals.length; i++)
		{
			var splitInfo = placementVals[i].split("=");
			
			if(splitInfo[1] && splitInfo[1] != 'undefined' && splitInfo[1] != '')
			{
				amp = '&';
				
				if(firstParam == false)
				{
					amp = '';
					firstParam = true;
				}
				
				// Create the URL query string.
				compareUrl += amp + "id[]=" + splitInfo[1];
			}
		}
		
		// If there is a query string to pass then send the user.
		if(compareUrl != '/compare-laptops.php?' && basketTotal > 1)
		{
			window.location = compareUrl;
		}
		else
		{
			return false;
		}
	}
	
	// The main compare submit button.
	$("#comparesubmit").click(function()
	{
		$.get("/ajax/record-click.php?href=compare-basket&title=Compare_basket&rel=Compare");
		compareSubmit();
	});
	
	// Fill the basket on load if a cookie is there.
	if(getCookie('comparebasket'))
	{
		loadCompareBasket();
	}
}