/**************************************************************************************************************************
     Author              :      PA
     Version             :      1.0
     Date Created        :         
	   
     Change history      :
	
     Task/Bug                  Date(mm-dd-yyyy)       Author            Change Description	
   
     Trac 1680                 09-08-2009             HGolla            Code modified for creativeImageOverride, lead image functionality.
     
     Trac 2025                 01-13-2009             HGolla            Added method setAlternateImageURL(). This method is used to pass the selected 
                                                                        alternate image url to 'download image' and 'open large image' links.
                                                                        
     Trac 2025                 02-01-2010             HGolla            If alternate images are not available for a color, not displaying them.
     
     Internal Defect: 449      03-03-2010             NThota            Code added for main product image should download when
     Child product is                                                   changing color swatch of child product
     downloaded on changing
     color swatch 
                                                                        
     Trac 1974                 06-08-2010             Rpark	            for familymod template     ***************************************************************************************************************************/
var colorList = new Array();

//string constants for scene7 images
var scene7Url = "http://images.anthropologie.com/is/image/Anthropologie/";
var thumbSize = "?$redesign-thumb$";
var scene7ImgSize = "?$redesign-product-zoom$";
var scene7Zoom4x = "?$redesign-zoom-5x$";
var scene7Zoom10x = "?$product-10x$";
var openLargerImg = "?$redesign-openLarger$";
var loaded = false; 
var defaultView = "";
function addEvent(element, ev, handler) 
{
	var doHandler = function(e) {
		return handler(e||window.event);
	};
	if (element.addEventListener) { 
		element.addEventListener(ev, doHandler, false); 
	} else if (element.attachEvent) { 
		element.attachEvent("on" + ev, doHandler); 
	}
}


function addColor(pColorCode, pColorName, pProductImageURL){
	colorList.push(new Color(pColorCode, pColorName, pProductImageURL));
}

function getColor(pColorCode){
	for(var i=0;i<colorList.length;i++){
		if(colorList[i].colorCode == pColorCode){
			return colorList[i];
		}
	}
	return null;
}

function addView(pColorCode, pViewName, pViewURL){
	var color = getColor(pColorCode);
	if(color !== null){
		color.addView(pViewName, pViewURL);
	}
}

function getViewList(pColor){
	if(pColor !== null){
		return pColor.viewList;
	} else {
		return null;
	}	
}

function setViewer(pSku, viewCode){
	if (pSku === null){return false;}
	if(pSku.substr(0,4)!="http"){
		pSku = scene7Url+pSku;
	}else{
	    //Code modified for Trac 2025
	    setAlternateImageURL(pSku);
	    //End of code modified for Trac 2025
	}
	if(defaultView !== undefined){
	if(defaultView!==null && defaultView !== ""){
		if(productSelectorArray[0] !== undefined && productSelectorArray[0].productId !== undefined && productSelectorArray[0].colorList[0].colorCode !== undefined){
	  var newProductURL = scene7Url+productSelectorArray[0].productId+'_'+productSelectorArray[0].colorList[0].colorCode+'_'+defaultView;
	  pSku = newProductURL;
	}
		else{
	      var newProductURL = pSku.replace('_b','_'+defaultView+'');
		  pSku = newProductURL;
		}
	}
	}
	if(window.useModelViews == true){
	  pSku = swapForModelViews(pSku);	
	}
	var viewerElement = getElement("zoomViewer");
	//check if it returned anything & there was a param passed in
	if (viewerElement !== null && pSku!== null){
		viewerElement.innerHTML="";
		var image = document.createElement("img");
		image.setAttribute("data-zoomsrc", pSku+scene7Zoom4x);
		image.setAttribute("data-zoomsrc2", pSku+scene7Zoom10x);
		image.setAttribute("src", pSku+scene7ImgSize);
		viewerElement.appendChild(image);
		var elemOpenLarger = getElement('openLarger');
		elemOpenLarger.setAttribute('href', pSku+"?$openLarger$");
		elemOpenLarger.setAttribute('title', '');
		MojoZoom.init();
		
	}
}

function altViewClickHandler(event){
	//clear all the other classes out there
	var altViewElement = $$("#alternateviewlist .chosen");
	altViewElement.each(function(el){
		el.className = "";
	});
	//add the selected class name to the clicked object
	var altView = Event.element(event);
	altView.addClassName('chosen');
}

function altViewAnchorClickHandler(event){
	setViewer(this.href);
	return false;
}

/* code modified for trac 1974 */
/* accept pId */
function setAlternateViews(pColor,pId){
	var viewList = getViewList(pColor);
	var altViewMain = getElement("alternateViews");
	var viewCode = new Array();	
	//Code modified for Trac 2025.
	var altViewElement = getElement("alternateviewlist");
	altViewElement.innerHTML = "";
	var alternateViewSelect = false;
	if(viewList!== null && viewList.length>0 && altViewMain!== null){		
		if (viewList.length==1){
		$('alternateviewlist').hide();
		//Code added for child product is downloaded on changing color swatch
		if(window.useModelViews == true){
		 viewList[0].viewURL = swapForModelViews(viewList[0].viewURL);	
		}
		var downloadUrl=scene7Url+viewList[0].viewURL+scene7ImgSize;
		if(getElement("downloadimg")!=null){		
	    getElement("downloadimg").innerHTML = "<a href=\"javascript:downloadImage('"+downloadUrl+"');\">download this image...................</a>";
	    }
		 return false;}
		$('alternateviewlist').show();
		for(var i=0;i<viewList.length;i++){
			viewCode =	(viewList[i].viewURL).split('_');
			if (viewCode[0] == pId) //code modified for trac 1974 - only set alternative views if the productid and color both match up to the swatch that was selected
			{
				var code = getImageViewCode(viewList);
				var listItem = document.createElement("li");
				listItem.setAttribute("id", 'addlImg'+i);
				//create & set anchor element
				var anchorTag = document.createElement("a");
				if(window.useModelViews == true){
		 		  viewList[i].viewURL = swapForModelViews(viewList[i].viewURL);	
		        }
				anchorTag.setAttribute("href", scene7Url+viewList[i].viewURL);
				anchorTag.onclick = function (){
					setViewer(this.href);
					return false;
				};
				//create & set image element
				var image = document.createElement("img");
				image.setAttribute("src", scene7Url+viewList[i].viewURL+thumbSize); 
				image.setAttribute("alt", viewList[i].viewName); 
				image.setAttribute("id", 'addlImgage'+i);
				var seg = "";
				if(window.SEGCATEGORY){seg=window.SEGCATEGORY;}
				image.setAttribute("onclick", "cmCreatePageElementTag('"+seg+": alt view "+viewList[i].viewName+"','Product Page')");
				
				//append the newly created elements
				anchorTag.appendChild(image);
				listItem.appendChild(anchorTag);
				Event.observe(image, 'click', altViewClickHandler);
				
				if(defaultView !== "" && productSelectorArray[0] !== undefined && productSelectorArray[0].productId !== undefined && productSelectorArray[0].colorList[0].colorCode !== undefined){
					if(productSelectorArray[0].productId+'_'+productSelectorArray[0].colorList[0].colorCode+'_'+defaultView === viewList[i].viewURL){
					  image.className = "chosen";
					}
					else{
					  image.className = "";
					}
				} else if (defaultView === "" && (viewCode[2] == code)){
				 alternateViewSelect = true;
				  image.className = "chosen";
				  //Code add for Trac 2025
				  setAlternateImageURL(scene7Url+viewList[i].viewURL);
				  //End of code modified for Trac 2025
				}
				
				altViewElement.appendChild(listItem);
			}
		}
        if(alternateViewSelect==false && document.getElementById("addlImgage0")!=null){			    
				document.getElementById("addlImgage0").className = "chosen";
			    setAlternateImageURL(scene7Url+viewList[0].viewURL);
		}

	} else {		
		altViewMain.style.display="none";
	}
	defaultView = "";
}


/* code modified for trac 1974 */
/* accept pId, prodImg, prodTempl */
function setViewerWithColor(pColorCode, pId, prodImg, prodTempl){
	var color = getColor(pColorCode);
	var viewList = getViewList(color);
	var imageUrl = "";
	if (prodTempl == "familymod") {
		imageUrl = prodImg;
	}
	else { // default action
		for(var i=0; i < viewList.length; i++){
			var viewCode =	(viewList[i].viewURL).split('_');
			var code = getImageViewCode(viewList);
			if (viewCode[2] == code){
				imageUrl = viewList[i].viewURL
			}
		}
		if(imageUrl == ""){
		   imageUrl = color.productImageURL;
		}
	}
	if (!loaded){
			var ev1 = new Event.observe(window, 'load', function(){
			setViewer(imageUrl);
			setAlternateViews(color, pId);
		});
		loaded = true;
	} else{
		setViewer(imageUrl);
		setAlternateViews(color, pId);
	} 
}

function setOpenLargerViewer(pSku){
	if (pSku===null){return false;}
	if(pSku.substr(0,4)!="http"){
		pSku = scene7Url+pSku;
	}
	var viewerElement = getElement("zoomViewer");
	//check if it returned anything & there was a param passed in
	if (viewerElement !== null && pSku!== null){
		viewerElement.innerHTML="";
		var image = document.createElement("img");
		image.setAttribute("src", pSku+openLargerImg);
		viewerElement.appendChild(image);
	}
}

function getImageViewCode(pViewList){
	var code = "";
	for(var i=0; i < pViewList.length; i++){
	   var viewCode =	(pViewList[i].viewURL).split('_'); 
	   if (typeof(isBigImage) != "undefined" && typeof(creativeImage) != "undefined" 
		                                     && isBigImage!= "" && viewCode[2] == creativeImage){
		   code=creativeImage;
		   break;
		}
		if(typeof(imageViewCode) != "undefined" && viewCode[2] == imageViewCode){
		   code=imageViewCode;
		}
	}

	if(code == ""){
	  code = "b";
	}
    
  return code;
  
}

//Code modified for Trac 2025
function setAlternateImageURL(pSku){
	var imageUrl = pSku.split("/");
	var imageParams = imageUrl[imageUrl.length-1];
	var imageAttributes = imageParams.split("_");
	//Assigning alternate image url to 'open larger image' link.
	if(imageAttributes.length === 3){
	   getElement("openlargerimage").href = "javascript:openProductPopupWindow('"+contextPath+"/popups/popup_zoomviewer.jsp?productid="+imageAttributes[0]+"&color="+imageAttributes[1]+"&viewCode="+imageAttributes[2]+"');";
	}
	//Assigning alternate image url to the download input field.
	document.imageDownload.url.value = pSku+scene7ImgSize;
	//Code added for child product is downloaded on changing color swatch
	var downloadUrl=pSku+scene7ImgSize;
	if(getElement("downloadimg")!=null){
	getElement("downloadimg").innerHTML = "<a href=\"javascript:downloadImage('"+downloadUrl+"');\">download this image...................</a>";
	}
}
//End of code modified for Trac 2025
/*
 * Sets the given color code as selected and reinitializes all products.
 * Also takes the extra parameters to show different swatches for selected and
 * unselected image.
 * It calls the imgClicked function from the colorswatches.js. This function takes
 * care of showing the current image as selected and rest of the images below to this
 * color swatch as unselected.
 */
 /* this function setSelectedColor is used on the product level; there's a dup in swatches.js that is used on the category level */
 /* Code modified for Trac 1974 */
 /* added pSizeName, pIsBigImage, pTemplateType so we can use this to specify if template = familymod, update the generic span id selectedColor in function changeColor */
function setSelectedColor(imgElem, pProductId, pColorCode, pProdImg, pSkuId, pColorName, pIsLeaderProduct, pCurrentPage, pSizeName, pIsBigImage, prodTempl){
	var uniqueId = pProductId;
	var imglinkHandle = "imglink" + uniqueId;
	var productSelector = getProductSelector(pProductId, false, pIsLeaderProduct);
	if(productSelector != null){
		productSelector.setSelectedColorCode(pColorCode);
		initializeAllProducts(pIsLeaderProduct);
	}
	changeColor(pProductId, pColorCode, pProdImg, pSkuId, pColorName, pIsLeaderProduct, null, prodTempl);	
	imgClicked(imgElem.id, imgElem);
	// code is added for "Remove javascript links on category pages"(Task 79).
	if(!(pCurrentPage == "ProductDetailPage")){
		if(getElement(imglinkHandle) != null){
		getElement(imglinkHandle).href=encodeURI(contextPath+'/catalog/productdetail.jsp?id='+pProductId+'&catId='+catId+'&pushId='+pushId+'&popId='+popId+'&navAction='+navAction+'&color='+pColorCode+'&isProduct=true');
		}
	}
	// End of code is added for "Remove javascript links on category pages"(Task 79).

	if (prodTempl == "familymod") {
	 var elementId = imgElem.id;
	 var numswatches = $$("span.familyModSwatches a");
	 for (var i=0;i<numswatches.length;i++)
	 {
		 var getswatchelem = numswatches[i].id;
		 var elem=document.getElementById(getswatchelem);
		 if (elementId != getswatchelem) {
			elem.className="unselected";
			elem.name="unselected"; // this is what the swatch looks at and defaults back to after mouseout
		}
	 }
	
	 selectFamilyModSwatches(pProductId);
	}
}
