// JavaScript Document

HashMap = function(){
  this._dict = {};
}
HashMap.prototype._shared = {id: 1};
HashMap.prototype.put = function put(key, value){
  if(typeof key == "object"){
    if(!key.hasOwnProperty._id){
      key.hasOwnProperty = function(key){
        return Object.prototype.hasOwnProperty.call(this, key);
      }
      key.hasOwnProperty._id = this._shared.id++;
    }
    this._dict[key.hasOwnProperty._id] = value;
  }else{
    this._dict[key] = value;
  }
  return this; // for chaining
}
HashMap.prototype.get = function get(key){
  if(typeof key == "object"){
    return this._dict[key.hasOwnProperty._id];
  }
  return this._dict[key];
}

var categoryMap = new HashMap(); // global map, keys representing the categories on the page

function jsonPagination(pagingURL, category, pageId){
	  var pageMap = categoryMap.get(category); // look up by category
	  if (pageMap == null) {
	    //nothing stored in this category yet
	    pageMap = new HashMap();
	    //create a new map and store it with this categoryId as the key
	    categoryMap.put(category, pageMap);
	  }
	  // pageMap is definitely not null at this point, so we'll check to see if it has results stored for the requested page
	  var results = pageMap.get(pageId);
	  // if results is not null, we've requested this set of data before
	  if (results == null) {
	    // since results was null, make the AJAX call to get the products for this category and page
	    results = ajaxJsonPagination(pagingURL, category, pageId, pageMap);
	  } else {
	 	showResults(results, category, pageId, results.length );
	  }
}



// makes ajax call to get json data for chosen products
function ajaxJsonPagination(pagingURL, category, pageId, pageMap){
		var numProdsReturned;					
		var ajaxURL = pagingURL.replace('/webapp/wcs/stores/servlet/CategoryView','/webapp/wcs/stores/servlet/FSProductFilterJSONView');
 		options = {};
		options.dataType = "json";
 		options.success = function(json, textStatus){
 			numProdsReturned = 0;
 			$.each(json, function(i, loc){
				if (numProdsReturned >= 4) {
					return; 
				}
				numProdsReturned++;
			});
			var curDataset = cloneObj(json);
			 //store the results according to the pageId
			pageMap.put(pageId, curDataset);
			showResults(curDataset, category, pageId, numProdsReturned);
		};	
		options.url = ajaxURL;
		$.ajax(options);	
    
}


function cloneObj(obj){
	if (obj == null || typeof(obj) != 'object') {
		return obj;
	}
	var temp = new obj.constructor();
	for (var key in obj) {
		temp[key] = cloneObj(obj[key]);
	}
	return temp;
}


var displayPageNumber = 10;
function updatePagination(products, category, pageId){
	var catArray = window['pageArray_'+category];

	//switch pages if greater than displayPageNumber
	if(catArray.length > parseInt(displayPageNumber)) { // only if greater than displayPageNumber pages

		if (parseInt(pageId) < parseInt(displayPageNumber)+1){ // first displayPageNumber pages

			for(j = 1; j <= catArray.length; j++){
				var links =document.getElementById('anchor_'+category+'_'+ j+'');
				if(j > parseInt(displayPageNumber) ){
				links.className = "hidePage";
				} else {
					links.className = "";
				} 
			}
		} else if (parseInt(pageId) > parseInt(displayPageNumber)){ 
			for(j = 1; j <= catArray.length; j++){
				var links =document.getElementById('anchor_'+category+'_'+ j+'');
				var tens = parseInt(pageId) / parseInt(displayPageNumber);
				if(j > (parseInt(tens)*parseInt(displayPageNumber)) && j < (parseInt(tens)*parseInt(displayPageNumber)+parseInt(displayPageNumber)+1)){
					links.className = "";
				} else {
					links.className = "hidePage";
				} 
			}
		}
	}

	// need to unselect the rest of the nubmers		
	for(j = 1; j <= catArray.length; j++){
		
	  	var links =document.getElementById('anchor_'+category+'_'+ j+'');
		if(parseInt(pageId) == j){ // set selected pageId
			links.className = "selected";
			links.setAttribute("onClick", "");
			links.setAttribute("href", "#none");
		} else {
			if(catArray.length < parseInt(displayPageNumber)+1) {
				links.className = "";
			}
			links.setAttribute("onClick", "jsonPagination(\'"+catArray[j-1]+"\',\'"+category+"\',\'"+j+"');");
			links.setAttribute("href", "#none");
		}
	}
	
	var nextAnchor = document.getElementById('anchor_'+category+'_next');
	var finalAnchor = document.getElementById('anchor_'+category+'_final');
	var nextAnchorLarge = document.getElementById('rightArrow_'+category+'');
	// set up for small > , >> & large > arrow

	if(parseInt(pageId) < catArray.length){
		nextAnchor.style.display = '';
		finalAnchor.style.display = '';
		nextAnchor.onclick = function(){jsonPagination(catArray[pageId],category,(parseInt(pageId)+1));};
        nextAnchorLarge.className = "categoryPage right"; 
  		nextAnchorLarge.onclick = function(){jsonPagination(catArray[pageId],category,(parseInt(pageId)+1));};      
		nextAnchorLarge.setAttribute("href", "#none");
	} else { // hide  >, >> & large > arrow
		nextAnchor.style.display = 'none';
		finalAnchor.style.display = 'none';
		nextAnchorLarge.className = "categoryPage";
		nextAnchorLarge.setAttribute("href", "#none");
	}
	
	var prevAnchor = document.getElementById('anchor_'+category+'_previous');  
	var initialAnchor = document.getElementById('anchor_'+category+'_initial');  
	var prevAnchorLarge = document.getElementById('leftArrow_'+category+'');
	// set up for small << , <, & large < arrow
	
	if(parseInt(pageId) > 1){
		prevAnchor.style.display = '';
		initialAnchor.style.display = '';
		initialAnchor.onclick = function(){jsonPagination(catArray[0],category,1);};
		prevAnchor.onclick = function(){jsonPagination(catArray[pageId-2],category,(parseInt(pageId)-1));};		
        prevAnchorLarge.className = "categoryPage left"; 
 		prevAnchorLarge.onclick = function(){jsonPagination(catArray[pageId-2],category,(parseInt(pageId)-1));};	       
		prevAnchorLarge.setAttribute("href", "#none");
	} else { // hide  << , <, & large < arrow
		prevAnchor.style.display = 'none';
		initialAnchor.style.display = 'none';
		prevAnchorLarge.className = "categoryPage";
		prevAnchorLarge.setAttribute("href", "#none");
	}

}


function showResults(products, category, pageId, numProdsReturned){

	updatePagination(products, category, pageId);
	var thisHTML = '';

		for(i = 0; i < numProdsReturned; i++){

			if(products[i]){

				thisResult = products[i];
				var recId = (pageId - 1) * 4 + i + 1;

 				var prodDisplayUrl = jsproductDisplayUrlTemplate.replace('productID_VALUE',thisResult.productID);
 				prodDisplayUrl = prodDisplayUrl.replace('categoryId_VALUE', category);
 				prodDisplayUrl = prodDisplayUrl.replace('rec_VALUE', recId + "");
				thisHTML += '<div id="'+category+'_product'+i+'" class="product quickView">';
				thisHTML += '<a id="productImgUrl'+thisResult.baseSKU+'" href="'+prodDisplayUrl+thisResult.imagePath+'">';
				thisHTML += '<img id="productDisplayImg'+thisResult.baseSKU+'" border="0" alt="'+thisResult.baseSKU+'"'; 
				thisHTML += 'src="'+scene7HostURL_start+thisResult.imagePath+scene7HostURL_end+'"/></a>';
				//	 initailqvlink = is set up on FSCategoryDisplayArea.jsp - just needs productId added
				var qvlink = prodDisplayUrl;
				thisHTML += '<a id="qvImgUrl'+thisResult.baseSKU+'" class="quickViewIcon thickbox" href="'+qvlink+thisResult.imagePath+'&amp;pageFlow=QuickView&amp;width=920&amp;height=510&amp;modal=true&amp;TB_iframe=true" style="display: none;">';
				thisHTML += '<span>'+jsString_Quick_Look+'</span></a>';

				thisHTML += ' <div class="prodInfo"><a id="productLinkUrl'+thisResult.baseSKU+'" href="'+prodDisplayUrl+thisResult.imagePath+'">';
				if(thisResult.newProduct){
					thisHTML += '<span class="newnote">'+jsString_New+'  </span>-';
				}
				thisHTML += thisResult.productName+'';
				if(thisResult.minPrice < thisResult.maxPrice){
					thisHTML += '</a><br/><span class="price">'+ thisResult.minPrice+ ' - '+ thisResult.maxPrice+'</span></div>';
				} else if(thisResult.salePrice != null) {
					thisHTML += '</a><br/><span class="salenote">Sale&nbsp;</span><span class="oldprice">'+ thisResult.price +'</span><span class="saleprice">&nbsp;'+ thisResult.salePrice +'</span></span></div>';
				
				} else {
					thisHTML += '</a><br/><span class="price">'+ thisResult.price +'</span></div>';
				}
				if(thisResult.swatchCount && thisResult.swatchCount > 1){
					
					thisHTML += '<div class="catSwatch">';
					for(j =0; j<thisResult.swatchCount; j++){
						var selectedColor ='class="normal"';
						var colorSwatch = thisResult["colorSwatch_"+j];
						if(colorSwatch == thisResult.imagePath){
							selectedColor = 'class="catSwatchSelect"';
						}
						var productURL = prodDisplayUrl+colorSwatch;
					
						thisHTML +='<a href="javascript:handleSwatchClick(\''+scene7HostURL_start+colorSwatch+scene7HostURL_end+'\',\''+thisResult.baseSKU+'\',\''+productURL+'\',';
						thisHTML +='\''+thisResult.baseSKU+'\',\''+(j+1)+'\',\''+thisResult.swatchCount+'\');">';
	      				thisHTML += '<img width="14" height="14" id="'+thisResult.baseSKU+'_'+(j+1)+'" src="'+scene7HostURL_start+colorSwatch+scene7HostURL_swatch_end+'" '+selectedColor+' /></a>'; 
						if(j+1 % 8 == 0){
							thisHTML += '</div><div class="catSwatch" style="text-align:left">';
						}
					}
				}
				thisHTML += '</div></div>';
			}
		}
	var cat_row = document.getElementById('categoryRow_'+category+'')
	cat_row.innerHTML = thisHTML;
	setupQV(cat_row);
	
	$(".categoryPage.right").bind("mouseover",function(e){
		$(this).css("background-image","url(/wcsstore/Fossil/images/en_US/category/category_page_right_ro.jpg)");
		$(this).css("background-position","left -2px");
	});

	$(".categoryPage.right").bind("mouseout",function(e){
		$(this).css("background-image","url(/wcsstore/Fossil/images/en_US/category/category_page_right.gif)");
		$(this).css("background-position","left top");
	});
	
	$(".categoryPage.left").bind("mouseover",function(e){
	
		$(this).css("background-image","url(/wcsstore/Fossil/images/en_US/category/category_page_left_ro.jpg)");
		$(this).css("background-position","right -2px");
	});
	
	$(".categoryPage.left").bind("mouseout",function(e){
		$(this).css("background-image","url(/wcsstore/Fossil/images/en_US/category/category_page_left.gif)");
		$(this).css("background-position","right top");
	});
}

var qv_params_end = '&pageFlow=QuickView&width=920&amp;height=510&amp;modal=true&TB_iframe=true'; 
function handleSwatchClick(productSwatchImage,baseSku,url,swatchSku,swatchIndex,swatchArrayCount)
{
		var productImg = returnObjById('productDisplayImg'+baseSku);
		productImg.src = productSwatchImage;
		var productLinkUrl = returnObjById('productLinkUrl'+baseSku);
		productLinkUrl.href = url;
		var productImgUrl = returnObjById('productImgUrl'+baseSku);
		productImgUrl.href = url;
		var qvProductLinkUrl = returnObjById('qvImgUrl'+baseSku);
		qvProductLinkUrl.href = url+qv_params_end;		
		handleSwatchSelection(swatchSku,swatchIndex,swatchArrayCount);
		
}
// The script below is for the href to work on all browsers..
function returnObjById( id )
{
    if (document.getElementById) 
    	var returnVar = document.getElementById(id);
    else if 
    	(document.all) var returnVar = document.all[id];
    else if 
    	(document.layers) var returnVar = document.layers[id];
    return returnVar;
}

function handleSwatchSelection(swatchSku,swatchIndex,swatchArrayCount)
{
	for (i=1; i<=swatchArrayCount; i++) {
		if (swatchIndex==i) 
			returnObjById(swatchSku+'_'+swatchIndex).className="catSwatchSelect";
		else 
			returnObjById(swatchSku+'_'+i).className="normal";		
	}
}
var initThickbox = false;
onclick = 'setupQV($(this).parents(".categoryWrapper"));'
//quick view rollover
function setupQV(_scd){ 
	$("div.quickView a:first-child, div.quickView a.quickViewIcon", (typeof(_scd)=='undefined') ? 'body' : _scd).bind("mouseenter",function(e){
		$(this).parent().children(".quickViewIcon").css("display", "inline");
	});
	$("div.quickView a:first-child, div.quickView a.quickViewIcon", (typeof(_scd)=='undefined') ? 'body' : _scd).bind("mouseleave",function(e){
		$(this).parent().children(".quickViewIcon").css("display", "none");
	});
	
	tb_init($("div.quickView a.quickViewIcon", (typeof(_scd)=='undefined') ? 'body' : _scd));//pass where to apply thickbox
	
}


 /* the following methods are used to build up the pagination for flattened URLs */ 
 function getFlattenedURL(NoValue)
 {
  	var currentURL = window.location.href;
  	var NoParam = "";
  	if(isSeoUrl(currentURL)){
  		NoParam = getNoParam( 'No', currentURL );
  	}else{
  	// get everything after last /
	  	currentURL = currentURL.substring(currentURL.indexOf('Category'))
	  	currentURL = currentURL.replace(/%257c/g,'|');
	  	NoParam = getNoParam( 'No', '/webapp/wcs/stores/servlet/'+currentURL );
	}
	if(NoParam) { 

		var currentParam = 'No='+NoParam;
 		var newParam = 'No='+NoValue;
 	    currentURL = currentURL.replace(currentParam,newParam);
  	} else {
  		currentURL = currentURL+ '&No='+NoValue; 
  	}
  	
	return currentURL;
  }
  
     
 function getNoParam( name, pageUrl )
 {
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( pageUrl );
  if( results == null )
    return "";
  else
    return results[1];
 }
 
   
function setUpFlattenedPagination()
{
	for (var i = 1; i <= pageArray.length; i++){
	var pageAnchorTop = document.getElementById('pageID_'+(i)+'_top_pagination');
	var pageAnchorBottom = document.getElementById('pageID_'+(i)+'_bottom_pagination');	
		if(pageAnchorTop){
			pageAnchorTop.href = pageArray[i-1];
			pageAnchorBottom.href = pageArray[i-1];			
		}
	}
}
 
function setUpPaginateLink(){
	
 	var currentURL = window.location.href;
 	
 	var paginateAnchorTop = document.getElementById('paginate_top_pagination');
	var paginateAnchorBottom = document.getElementById('paginate_bottom_pagination');		
  	// get everything after last /
  	if(isSeoUrl(currentURL)){
  		//do nothing
  	}else{
	  	currentURL = currentURL.substring(currentURL.indexOf('Category'));
	  	currentURL = currentURL.replace(/%257c/g,'|');
  	}
  	VaParam = getNoParam( 'Va', currentURL );
	if(VaParam != "") { 
		var currentParam = '&Va='+VaParam;
 	    currentURL = currentURL.replace(currentParam,'')
  	}
  	if(paginateAnchorTop){
  	
		paginateAnchorTop.href = currentURL;
	}
	if(paginateAnchorBottom){
	
		paginateAnchorBottom.href = currentURL;
	}
} 

function setUpPaginateLinkJSON(categoryId, subcatURL){

	
	var currentURL = window.location.href;
	if(subcatURL){
		currentURL = subcatURL;
	}
 	var paginateAnchor = document.getElementById('paginate_'+categoryId+'');
  	// get everything after last /
  	currentURL = currentURL.substring(currentURL.indexOf('Category'))
  	currentURL = currentURL.replace(/%257c/g,'|');
  	VaParam = getNoParam( 'Va', currentURL );
	if(VaParam != "") { 
		var currentParam = '&Va='+VaParam;
 	    currentURL = currentURL.replace(currentParam,'')
  	}
  	if(paginateAnchor){
  	
		paginateAnchor.href = '/webapp/wcs/stores/servlet/'+currentURL;
	}
}
  
function setUpViewAll(endecaViewAll){
 	var currentURL = window.location.href;
 	var VAanchorTop = document.getElementById('viewAll_top_pagination');
	var VAanchorBottom = document.getElementById('viewAll_bottom_pagination');
	// get everything after last /
  	currentURL = currentURL.substring(currentURL.lastIndexOf('/')+1);
  	currentURL = currentURL.replace(/%257c/g,'|');
  	VaParam = getNoParam( 'Va', endecaViewAll );
  	NoParam = getNoParam( 'No', currentURL);
  	if (NoParam != ""){
  		var currentNoParam = '&No='+NoParam;
 	    currentURL = currentURL.replace(currentNoParam,'');
  	}
	if(VaParam != "") { 
 	    currentURL = currentURL+ '&Va='+VaParam;
  	}
	VAanchorTop.href = currentURL;
	if(VAanchorBottom){
	VAanchorBottom.href = currentURL;
	}
}

function isFlatUrl(urlArg) {
  return (urlArg.indexOf('Category_') >= 0);
}

function getCategoryIdFromURL(currentURL){

  if (isFlatUrl(currentURL)) {
    var URLarray =currentURL.split("_");

    return URLarray[4];
  }
  return getNoParam('categoryId', currentURL);

}

function isSeoUrl(url){
	return (url.indexOf('/shop/') >= 0);
}
function setUpViewAllJSON(category, endecaViewAll){
	
	
 	var currentURL = window.location.href;
 	var VAanchor = document.getElementById('viewAll_'+category+'');
	// get everything after last /
	
	// new logic to handle SEO url
	if(isSeoUrl(currentURL)){
		currentURL = VAanchor.href;
		
	}else{
		
		currentURL = currentURL.substring(currentURL.indexOf('Category'));
  		var catergoryToBeReplaced = getCategoryIdFromURL(currentURL);
   		currentURL = currentURL.replace(catergoryToBeReplaced,category);  
	}
  		
   	currentURL = currentURL.replace(/%25/g,'%');
   	currentURL = currentURL.replace(/%7c/g,'|');
   	currentURL = currentURL.replace(/#.*/g,'');
  	VaParam = getNoParam( 'Va', endecaViewAll );
  	NoParam = getNoParam( 'No', currentURL);
  	if (NoParam != ""){
  		var currentNoParam = '&No='+NoParam;
 	    currentURL = currentURL.replace(currentNoParam,'');
  	}
	if(VaParam != "") { 
 	    currentURL = currentURL+ '&Va='+VaParam;
  	}
	
	VAanchor.href = currentURL;
}


function setUpArrows(pageId){
	if(pageId < pageArray.length){
		document.getElementById('frontarrows1_top_pagination').href = pageArray[pageId];
	  	document.getElementById('frontarrows2_top_pagination').href = pageArray[pageArray.length-1];	
		document.getElementById('frontarrows1_bottom_pagination').href = pageArray[pageId];
		document.getElementById('frontarrows2_bottom_pagination').href = pageArray[pageArray.length-1];
	} 
	if(pageId > 1){
		document.getElementById('backarrows1_top_pagination').href = pageArray[pageId-1];
	  	document.getElementById('backarrows2_top_pagination').href = pageArray[0];	
		document.getElementById('backarrows1_bottom_pagination').href = pageArray[pageId-1];
		document.getElementById('backarrows2_bottom_pagination').href = pageArray[0];	
	} 
}


function setUpURLs(viewURL, pageId){
   		setUpFlattenedPagination(); // sets up page numbers
   		setUpViewAll(viewURL); //set up view all
		setUpArrows(pageId);
}

$(document).ready(function(){

	$(".categoryPage.right").bind("mouseover",function(e){
		$(this).css("background-image","url(/wcsstore/Fossil/images/en_US/category/category_page_right_ro.jpg)");
		$(this).css("background-position","left -2px");
	});

	$(".categoryPage.right").bind("mouseout",function(e){
		$(this).css("background-image","url(/wcsstore/Fossil/images/en_US/category/category_page_right.gif)");
		$(this).css("background-position","left top");
	});
	
	$(".categoryPage.left").bind("mouseover",function(e){
		//alert("left");
		$(this).css("background-image","url(/wcsstore/Fossil/images/en_US/category/category_page_left_ro.jpg)");
		$(this).css("background-position","right -2px");
	});
	
	$(".categoryPage.left").bind("mouseout",function(e){
		$(this).css("background-image","url(/wcsstore/Fossil/images/en_US/category/category_page_left.gif)");
		$(this).css("background-position","right top");
	});
});

