/**
 * This function is for updating the Compare bucket with the items in cookie. It
 * is called on load of the search result page ( i.e. when ever search result
 * page refreshes/reloads)
 * 
 * @returns {Boolean}
 */

/*$(document).ready(function(){
    var compareBucketCookie = readCookie("compareBucket");

    if ($('.abTest').css('display') != 'none'){
        if (compareBucketCookie == 'on'){
            $('li.compare ').show();
            $('#compareWrapper').show();
            $('#compareTab').css('border-top', 'none');
            $('#compareTab b').removeClass('compareDownArrow');
            $('#compareTab b').addClass('compareUpArrow');
        } else {
            $('li.compare ').hide();
            $('#compareWrapper').hide();
            $('#compareTab').css('border-top', '1px solid #CCC');
            $('#compareTab b').removeClass('compareUpArrow');
            $('#compareTab b').addClass('compareDownArrow');
        }
    }
    
    $('#compareTab').click(function() {
        $('li.compare').toggle();
        $('#compareWrapper').animate({
            height: 'toggle'
            }, 200);
        if ($('#compareWrapper').css('height') == '1px') {
            Set_Cookie("compareBucket", "on");
            $('#compareTab b').removeClass('compareDownArrow');
            $('#compareTab b').addClass('compareUpArrow');
            $('#compareTab').css('border-top', 'none');
        } else {
            Set_Cookie("compareBucket", "off");
            $('#compareTab b').removeClass('compareUpArrow');
            $('#compareTab b').addClass('compareDownArrow');
            $('#compareTab').css('border-top', '1px solid #CCC');
        }

    });
});*/

function updateCompBucketOnLoad() {
	
	var href= window.location.href;
	Set_Cookie("searchURL",href);
	
	var cookieValue = readCookie("userproduct");
	if (cookieValue != null) {
		var valuePieces = new Array();
		valuePieces = cookieValue.split('%2C');
		if (valuePieces && valuePieces != "" && valuePieces.length > 0) {
			var style;
			// Updating bucket with only the first four items in cookie ( this
			// is for existing users who may have more than 4 items)
			Delete_Cookie('userproduct','/');
			Delete_Cookie('compExtAccess','/');
			Delete_Cookie('removeuserproduct','/');
			for ( var x = 0; x < 4; x++) {
				if (valuePieces[x]) {
					style = valuePieces[x];
					// Adding item to compare bucket and back into the cookie
					toggleCompButton(style, 'add');
				} 
			}
		}
	}
	return false;
}
function isStyleInCompareCookie(cookieName, Style) {
	var isInCompList = false;
	var cookieValue = readCookie(cookieName);
	if (cookieValue != null) {
		var SetSize = cookieValue.length;
		var valuePieces = new Array();
		valuePieces = cookieValue.split('%2C');
		for (var x = 0; ((x < SetSize) && (!isInCompList)); x++) {
			if (valuePieces[x] == Style) {
				isInCompList = true;
			}
		}
	}
	return isInCompList;
}

/*function findParamInQuerySt(name) 
{
	var url = window.location.search.substring(1);
	var keyValues = url.split("&amp;");
	var key;
	for (i=0;i < keyValues.length;i++)
	{
		key = keyValues[i].split("=");
		if (key[0] == name) {
			return key[1];
		}
	}
}

function remove(){
	var mode = findParamInQuerySt('styles');
	var styles ='%20';
	if(mode)
	{
		Set_Cookie("compExtAccess","true");
	}
	if(readCookie("compExtAccess") == 'true' && mode)
	{
		document.userProductUpdate.action = document.userProductUpdate.action + '&styles='+styles ;
		document.userProductUpdate.method = 'post';
	}
	else
	{
		//Delete_Cookie('userproduct','/');
		Set_Cookie('userproduct',"");
		Delete_Cookie('removeuserproduct','/');
	}
	document.userProductUpdate.submit();
}*/

function removeFromCompareCookie(cookieName, style) {
	var cookieValue = readCookie(cookieName);
	if (cookieValue != null) {
		cookieValue = cookieValue.replace('%2C' + style, '');
		cookieValue = cookieValue.replace(style, '');
		if (cookieValue.length == 9) {
			cookieValue = cookieValue.replace('%2C', '');
		}
	}
	cookieValue = unescape(cookieValue);
	Set_Cookie(cookieName,cookieValue,'21');
}

function addToCompareCookie(cookieName, style)
{
	var cookieValue = readCookie(cookieName);
	var cookieLength;
	if (cookieValue != null) {
		cookieLength = cookieValue.length;
	} else {
		cookieLength = 0;
	}

	if (isStyleInCompareCookie(cookieName, style) == false)
	{
		var updatedList="";
		if (cookieLength == 0) {
			 updatedList = style;
		} else if (cookieLength > 0
				&& (cookieValue.substring(cookieLength - 3, cookieLength) == '%2C')) {
			//var updatedList = cookieValue + style;
			 updatedList = style;
		} else if (cookieLength > 0) {
			 updatedList = cookieValue + ',' + style;
		}
		//Cookie expires after 21 days, the items added to bucket will be there for 21 days only
		updatedList = unescape(updatedList);
		Set_Cookie(cookieName,updatedList,'21');
	}	
}

function addStyle(style) {
	addToCompareCookie("userproduct", style);
	removeFromCompareCookie("removeuserproduct",style);
}


function removeStyle(style) {
	if (isStyleInCompareCookie('userproduct',style) == true) {
		removeFromCompareCookie('userproduct',style);
	}
	addToCompareCookie("removeuserproduct", style);
}

function removeStyleFromList(style, styleList) {
	var styleArray = styleList.value.split(",");
	var styleCount = 0;
	styleList.value = "";
	while (styleCount < styleArray.length) {
		if (styleArray[styleCount] != "" && style != styleArray[styleCount]) {
			styleList.value = styleList.value + "," + styleArray[styleCount];
		}
		styleCount++;
	}
}

/**
 * This function is getting the comparison results. It is called on click of
 * Compare button that exists as part of Compare bucket
 */
function compare() {
	document.getElementById('userProductUpdate').submit();
}

/**
 * This function is for toggling Compare button from 'Add' to 'Remove' state and vice-versa.
 * It also updates the Compare bucket accordingly. 
 * @param style - required parameter, it is the sku value.
 * @param inMode - optional parameter and is used to handle the case where items in
 * cookie don't exist on search result page. Ex: User adds 'shoes' to compare
 * bucket and then searches for 'shirt', so the 'shoe' items in cookie would not
 * exist on 'shirt' search result page.
 */
function toggleCompButton(style, inMode) {
	if (style != null && style != '' && style.match(/[0-9]/) != null) {
		var buttonElem = $('#'.concat(style, 'Compare'));
		if (buttonElem && buttonElem.attr('mode')) {
			var mode = buttonElem.attr('mode');
			// Add item to cookie and change add button to remove
			if (mode == 'add') {
				var cookieValue = readCookie("userproduct");
				if (cookieValue != null && cookieValue != "") {
					var cookieArray = new Array();
					cookieArray = cookieValue.split('%2C');
					if (cookieArray[0] == "") {
						cookieArray.splice(0, 1);
					}
					else if (cookieArray[cookieArray.length -1] == "") 
					{
							cookieArray.splice(cookieArray.length -1, 1);
						
					}
					var cookieLength = cookieArray.length;
					if (cookieLength > 3) {
						$
								.fancybox({
									content : '<p></p><p class="compareMsg compareMsgTitle"><b>You can compare up to four items at a time.</b></p><p class="compareMsg">Remove one or more items before adding another item to compare.</p><p class="compareMsg"><a href="javascript:$.fancybox.close();">Close</a></p>',
									autoScale : false,
									autoDimensions : false,
									width : 210,
									height : 145
								});
						return;
					}
				}
				// Add item to cookie
				addStyle(style);
				// Change add button to remove
				buttonElem.unbind('mouseover');
				buttonElem.unbind('mouseout');
				buttonElem.unbind('mousedown');	
				buttonElem.attr('src', '/pix/common/CompareRemove_ON.gif');
				buttonElem.attr('class', 'compareBtnRem');
				buttonElem.attr('mode', 'remove');
				buttonElem.attr('title', 'Remove item from compare list.');
				buttonElem.bind('mouseover',function(event)
						{
								updateCompAddBtn(event);
						}
				);
				buttonElem.bind('mouseout',function(event)
						{
								updateCompAddBtn(event);
						}
				);
				buttonElem.bind('mousedown',function(event)
						{
								updateCompAddBtn(event);
						}
				);
			}
			// Remove item from cookie and change remove button to add
			else if (mode == 'remove') {
				// Remove item from cookie
				removeStyle(style);
				// Change remove button to add
				// Change add button to remove
				buttonElem.unbind('mouseover');
				buttonElem.unbind('mouseout');
				buttonElem.unbind('mousedown');
				buttonElem.attr('src', '/pix/common/Compare_ON.gif');
				buttonElem.attr('class', 'compareBtnAdd');
				buttonElem.attr('mode', 'add');
				buttonElem.attr('title', 'Add item to compare list.');
				buttonElem.bind('mouseover',function(event)
						{
								updateCompRemBtn(event);
						}
				);
				buttonElem.bind('mouseout',function(event)
						{
								updateCompRemBtn(event);
						}
				);
				buttonElem.bind('mousedown',function(event)
						{
								updateCompRemBtn(event);
						}
				);
			
			}
			// Update compare bucket for the item
			updateCompBucket(style, mode);
		} 
		else if (inMode) {
			if (inMode == 'add') {
				// Add item to cookie
				addStyle(style);
				// Update compare bucket for the item
				updateCompBucket(style, 'add', true);
			} else if (inMode == 'remove') {
				// Add item to cookie
				removeStyle(style);
				// Update compare bucket for the item
				updateCompBucket(style, 'remove', true);
			}
		}
		//window.scrollTo(0, 0);
	}

}

/**
 * This function adds/removes items to/from Compare bucket.
 * @param inStyle - required param, it is the sku value.
 * @param inMode -  required param, allowed values are 'add' and 'remove'.
 * @param prodNotOnCurrPage - optional parameter and is used to handle the case where items in
 * cookie don't exist on search result page. Ex: User adds 'shoes' to compare
 * bucket and then searches for 'shirt', so the 'shoe' items in cookie would not
 * exist on 'shirt' search result page.
 */
function updateCompBucket(inStyle, inMode, prodNotOnCurrPage) {
	var cookieValue = readCookie("userproduct");
	
	if (cookieValue != null) {
		var cookieLength = cookieValue.split('%2C').length;
		// Enable compare button if 2 or more items have been added to bucket.
		if (cookieLength > 1) {
			/*$('#compareBucket').attr('src', '/pix/common/compare_items.gif');*/
			$('#compareBucket').attr('disabled', false);
			$('#compareBucket').removeClass('disabled');
		} else {
			/*$('#compareBucket').attr('src',
					'/pix/common/compare_items_disabled.gif');*/
			$('#compareBucket').attr('disabled', true);
			$('#compareBucket').addClass('disabled');
		}
	}
	if (inStyle && inMode && inStyle != '' && inMode != '') {
		// Adding/removing items to/from compare bucket
		// Looping through all the place holders for thumb nails in bucket to,
		// 1> find an empty spot in case of adding item to bucket
		// 2> shift items to left in case of removal of an item from bucket
		for ( var i = 1; i < 5; i++) {
			var parentThumbnail = $('#compareThumbnail_'.concat(i));
			var thumbnail = $('#thumbnail_'.concat(i));
			var closeElem = $('#thumbnail_close_'.concat(i));
			if (inMode == 'add' && thumbnail.attr('available') == 'yes') {
				// Get the image for adding to compare bucket thumb nail
				var img = 'url(/zoom/' + inStyle + '/40)';
				var alt = $('#'.concat(inStyle, 'Image')).attr('alt');
				if (img) {
					parentThumbnail.attr('closeId', inStyle);
					parentThumbnail.bind('click', function(event) {
						removeItemFromBucket(event);
					});
					if (prodNotOnCurrPage) {
						/*closeElem.attr('prodNotOnCurrPage', prodNotOnCurrPage);*/
						parentThumbnail.attr('prodNotOnCurrPage', prodNotOnCurrPage);
					}
					parentThumbnail.attr('hoverId', i);
					parentThumbnail.bind('mouseover',function(event)
							{
									updateHover(event);
							}
					);
					parentThumbnail.bind('mouseout',function(event)
							{
									updateHover(event);
							}
					);
					// Add image to thumb nail
					thumbnail.css('background-image', img);
					thumbnail.attr('title', alt);
					thumbnail.attr('available', 'no');
					thumbnail.attr('removeId', inStyle);
					
					// Show the close image on thumb nail
					closeElem.css('display', 'block');
					closeElem.css('background','url(/pix/common/remove_x.png)');
				}
				break; // out of outer for loop
			} else if (inMode == 'remove'
					&& thumbnail.attr('removeId') == inStyle) {
				var j;
				// Left shift all the items that exist to the right of target(item
				// to be removed)
				for (j = i; j < 5; j++) {
					var k = j + 1;
					var currParElem = $('#compareThumbnail_'.concat(j));
					var nextParElem = $('#compareThumbnail_'.concat(k));
					var currElem = $('#thumbnail_'.concat(j));
					var nextElem = $('#thumbnail_'.concat(k));
					var currCloseElem = $('#thumbnail_close_'.concat(j));
					//var nextCloseElem = $('#thumbnail_close_'.concat(k));
					if (currElem) {
						if (nextElem && nextElem.attr('removeId') != null
								&& nextElem.attr('removeId') != '') {
							currParElem.unbind('click');
							currParElem.unbind('mouseover');
							currParElem.unbind('mouseout');
							currParElem.attr('closeId', nextParElem
									.attr('closeId'));
							currParElem.attr('prodNotOnCurrPage',
									nextParElem.attr('prodNotOnCurrPage'));
							currParElem.bind('click', function(event) {
								removeItemFromBucket(event);
							});
							currParElem.bind('mouseover',function(event)
									{
											updateHover(event);
									}
							);
							currParElem.bind('mouseout',function(event)
									{
											updateHover(event);
									}
							);
							currElem.css('background-image', nextElem
									.css('background-image'));
							currElem.attr('title', nextElem.attr('title'));
							currElem.attr('available', 'no');
							currElem.attr('removeId', nextElem.attr('removeId'));
						} else {
							currParElem.unbind('click');
							currParElem.unbind('mouseover');
							currParElem.unbind('mouseout');
							currParElem.attr('closeId', '');
							currParElem.attr('hoverId', '');
							currParElem.attr('prodNotOnCurrPage', '');
							currElem.css('background-image', 'none');
							currElem.attr('title', '');
							currElem.attr('available', 'yes');
							currElem.attr('removeId', '');
							currCloseElem.css('display', 'none');
							currCloseElem.css('background','')
							break;// out of "j" for loop
						}
					}
				}
				break; // out of outer for loop
			}
		}
	}
}

/**
 * This function handles the click of 'x' present on thumbnail
 * @param event
 */
function removeItemFromBucket(event) {
	var id="";
	if (event.srcElment)
		id = event.srcElement.id;
	else if (event.currentTarget) // For firefox
		id = event.currentTarget.id;

	var closeElemId = $('#'.concat(id)).attr('closeId');
	var prodNotExists = $('#'.concat(id)).attr('prodNotOnCurrPage');
	if (prodNotExists) {
		toggleCompButton(closeElemId, 'remove');
	} else {
		toggleCompButton(closeElemId);
	}
}
/**
 * This function is for updating the Add state of Compare button present on Search result page.
 * @param event
 */
function updateCompAddBtn(event)
{
	var id="";
	if (event.srcElment)
		id = event.srcElement.id;
	else if (event.target) // For firefox
		id = event.target.id;
	if(event.type == 'mouseover')
	{
		$('#'.concat(id)).attr('src','/pix/common/CompareRemove_OVER.gif');
	}
	else if(event.type == 'mouseout')
	{
		$('#'.concat(id)).attr('src','/pix/common/CompareRemove_ON.gif');
	}
	else if(event.type == 'mousedown')
	{
		$('#'.concat(id)).attr('src','/pix/common/CompareRemove_OnCLICK.gif');
	}
}
/**
 * This function is for updating the Remove state of Compare button present on Search result page.
 * @param event
 */
function updateCompRemBtn(event)
{
	var id="";
	if (event.srcElment)
		id = event.srcElement.id;
	else if (event.target) // For firefox
		id = event.target.id;
	if(event.type == 'mouseover')
	{
		$('#'.concat(id)).attr('src','/pix/common/CompareOVER.gif');
	}
	else if(event.type == 'mouseout')
	{
		$('#'.concat(id)).attr('src','/pix/common/Compare_ON.gif');
	}
	else if(event.type == 'mousedown')
	{
		$('#'.concat(id)).attr('src','/pix/common/Compare_OnCLICK.gif');
	}
}

/**
 * This function is for changing the state of x button in compare bucket on hovering over the image
 * @param event
 */

function updateHover(event)
{
	var id="";
	if (event.srcElment)
		id = event.srcElement.id;
	else if (event.currentTarget) // For firefox
		id = event.currentTarget.id;
	
	id = $('#'.concat(id)).attr('hoverId');
	var closeElemId = $('#thumbnail_close_'.concat(id));  
	
	if(event.type == "mouseover")
	{
		closeElemId.css('background','url(/pix/common/remove_x.png) no-repeat 0 -28px');
	}
	
	if(event.type == "mouseout")
	{
		closeElemId.css('background','url(/pix/common/remove_x.png)');
	}	
}

