var colorArray = new Array();
var currItemBackordered = false;

function getFirstATB(el) {
	return YUD.getElementsByClassName('AddToBag', null, el)[0];
}

function colorObj(seq,name,oprice,lprice,copy,image,skus){  
	this.seq = seq;  
	this.name = name; 
	this.oprice = oprice; 
	this.lprice = lprice; 
	this.copy = copy;
	this.image = image;
	this.skus = skus
}

function skuObj(sku,catentry,size,seq,backdate,backordered){  
	this.sku = sku;  
	this.catentry = catentry; 
	this.size = size; 
	this.seq = seq;
	this.backdate = backdate;
	this.backordered = backordered;
}

function customSort(a,b){
   return(a.seq-b.seq);
}

function customSizeSort(a,b){
    if(a.sizeseq > b.sizeseq){return 1}
    if(a.sizeseq < b.sizeseq){return -1}
    return 0
}

function submitWish(){
	var wishList = HTB.readCookie('wishList');
	if(!wishList || wishList == 'false'){ createCookie('wishList', true); }
	document.forms.wishListForm.submit()
}

var productObject = function(o) {
	this.colorArray = o.colorArray || null;
	this.template = o.template || null;
	this.view = o.view || null;
	this.productCopy = o.productCopy || null;
	this.productId = o.productId || null;
	this.collection = o.collection || null;
	this.selectedColor = o.selectedColor || '01';
	this.price = o.price || null;
	this.highlightSwatch = null;
	this.oneSize = o.oneSize || null;
	this.sizeChart = o.sizeChart || 0;
	
	var productId = o.productId;
	var oneSize = o.oneSize || null;
	var colorArray = o.colorArray || null;
	var template = o.template || null;
	var view = o.view || null;
	var productCopy = o.productCopy || null;
	var productId = o.productId || null;
	var collection = o.collection || null;
	var selectedColor = o.selectedColor || '01';
	var price = o.price || null;
	var highlightSwatch = null;
	var sizeChart = o.sizeChart || 0;
	
	
	this.chngColor = function(e, po){
		var t = e.target || e.srcElement;
		if(t.tagName.toUpperCase().indexOf('SELECT') > -1){
			if(t.name.indexOf('sizelist') > -1){
				po.selectedColor = t.options[t.selectedIndex].value;
				po.setColor(po);
			}else{
				po.getVBImg(po);
			}
			var atbBtn = getFirstATB(po.pn);
			atbBtn.style.cursor = 'pointer';
			YUD.removeClass(atbBtn, "processingBtn");
			YUD.removeClass(atbBtn, "itemAddedBtn");
			YUD.addClass(atbBtn, "addToBagBtn");
		}
	}
	
	this.clickHandler = function(e){
		var t = e.target || e.srcElement, po = null, pn = t.parentNode;
		while(pn.tagName.toLowerCase() != 'body'){
			if(YUD.hasClass(pn, 'productDiv')){
				po = pn.po;
				break;
			}else{
				pn = pn.parentNode
			}
		}
		
		if(YUD.hasClass(t,'colorSwatch')){
			po.selectedColor = t.id.split('_')[2];
			po.setColor(po);
		}else if(YUD.hasClass(t, 'AddToBag')){
			po.addToBag(po);
		}else{
			return true;
		}
	}
	
	this.addToBag = function(po){
		var f = po.form, currItemBackordered = false;
		if((!po.oneSize) && (f.size.options && f.size.selectedIndex == 0)) {
			alert('Please select a size.');
			return false;
		} else if((po.template == 'v') && (f.sizelist && f.sizelist.value == '')){
			alert("Please select a style.");
			return false;
		} else if (YUD.hasClass(getFirstATB(po.pn), "notAvailableBtn") || YUD.hasClass(getFirstATB(po.pn), "itemAddedBtn")) {
			return;
		} else {
			var catentry = f.size.value;
			for(var y = 0; y != po.colorArray.length; y++){
				if(po.colorArray[y].name == f.color.value){
					for(var t = 0; t != po.colorArray[y].skus.length; t++){
						if (po.colorArray[y].skus[t].catentry == catentry){
							f.partnumber.value = po.colorArray[y].skus[t].sku;
							currItemBackordered = po.colorArray[y].skus[t].backordered;
							break;
						}
					}
				}
			}
	   
	   		f.catEntryId.value = catentry;
	        f.URL.value = '#';
	     
	       	/* prepare to bag item */
	        YUD.replaceClass(getFirstATB(po.pn), "addToBagBtn", "processingBtn");// Processing ...
	        HTB.fixPngs();
	        f.action = '/webapp/wcs/stores/servlet/OrderItemAdd';
	        var oiuCB = {
	        	success: function(o){
					if(o.responseXML.getElementsByTagName('wasItemAdded')[0].firstChild.nodeValue === "true") {	 
	        			YUD.replaceClass(getFirstATB(po.pn), "processingBtn", "itemAddedBtn");       			
		        		HTB.fixPngs();
		        		HOL.miniCart.getCart('add');
		        		setTimeout(function(){
		        			YUD.replaceClass(getFirstATB(po.pn), "itemAddedBtn", "addToBagBtn");
							if($("size") && $("size").tagName.toUpperCase() == "SELECT"){
								$("size").selectedIndex = 0;
							}else if($("sizelist") && $("sizelist").tagName.toUpperCase() == "SELECT"){
								setColor(initColor);
		        				for(var i=0; i< $("sizelist").options.length; i++){
		        					if($("sizelist").options[i].value == initColor){
		        						$("sizelist").selectedIndex = i;
		        					}
		        				}
							}
							po.getVBImg(po);
		        		}
		        		, 2500);
		        		
		        	} else {
		        		YUD.replaceClass(getFirstATB(po.pn), "processingBtn", "addToBagBtn");
		        		alert(o.responseXML.getElementsByTagName('statusMsg')[0].firstChild.nodeValue);
		        	}
		    
		        	YUD.setStyle(getFirstATB(po.pn), "cursor", "pointer");
			   	},
	        	failure: function(o){
	        		YUD.replaceClass(getFirstATB(po.pn), "processingBtn", "addToBagBtn");
	        		HTB.fixPngs();
	        	}
	        }
	        
	       	YUC.setForm(f);
			var transaction = YUC.asyncRequest('GET', f.action, oiuCB, null);
	    }
	}
	
	/***************************************************************************************************************/
	
		
	this.getVBImg = function(po){
		var cartNum = HTB.readCookie('myCart'), cartParts = cartNum ? cartNum.split(",") : null, num = cartParts ? cartParts[0] : null;
		if(num != '0' && cartNum != null){
			YUD.setStyle($('viewBag'), "display", "inline");
		}else{
			return;
		}
	}
	
	this.addToWishList= function(po){
		var f = po.form, storeId = globalStoreId, catalogId = globalCatalogId, collection = po.collection, sequence = po.selectedColor;
		if((!po.oneSize) && (f.size.selectedIndex == 0)){
			alert('Please select a size.');
		}else if((po.template == 'v') && (document.forms.OrderItemUpdate.sizelist.value == '')){
			alert("Please select a style.");
		}else{
			var size = '', sizeOptions = po.oneSize && po.template == 'v' ? f.sizelist.getElementsByTagName('option') : f.size.getElementsByTagName('option');
			if (po.oneSize){
				var catentry = f.size.value;
				if(po.template == 'v'){
		    		 for(i = 0; i < sizeOptions.length; i++){
		    	 		if(sizeOptions[i].selected){
		    	 			size = sizeOptions[i].innerHTML + '<br/>';
		    	 		}
		    	 	}
		    	}
			}else{
		    	 var catentry = f.size.value;
		    	 for(i = 0; i < sizeOptions.length; i++){
		    	 	if (sizeOptions[i].selected){
		    	 		size = sizeOptions[i].innerHTML + '<br/>';
		    	 	}
		    	 }
		    }
		    
		    document.forms.wishListForm.catEntryId.value = catentry;
		    
			var name = YUD.getElementsByClassName('prodName', null, po.pn)[0].innerHTML;
			var price = YUD.getElementsByClassName('prodPrice', null, po.pn)[0].innerHTML;
			var rightContent = '<h1 class="title">' + name + '</h1>' + size + price + '<br/><br/> <label for="field3">Comments</label><br/><textarea name="field3" cols="30" rows="3" onkeypress="limitChars(this, 100)" style="width:180px;"></textarea><br/><span class="caption">(up to 100 characters)</span><br/><br/><a href="javascript:submitWish();" id="addToWishLink"><img src="/hol/images/button_addtowishlist_white.jpg" alt="Add To Wish List" /></a><a href="javascript:closeFade(document.getElementById(\'wishCtn\'));" id="cnclAddToWishLink"><img src="/hol/images/button_cancel_white.jpg" /></a>';
			var leftContent = '<img src="' + collPath + collection + '_' + sequence + '_b.jpg" />';
			
			$('wishProdLft').innerHTML = leftContent;
			$('wishProdRgt').innerHTML = rightContent;
			
			cmCreatePageviewTag("WISHLIST - ADD ITEM FADEUP","13000");
			
			getFadeUp('wishCtn', true);
			JSFX_FloatTopDiv('fadeCtn');
		}			
	}
	function togSwatch(e){
		var t = YUE.getTarget(e);
		if(YUD.hasClass(t, "colorSwatch")){
			if(!YUD.hasClass(t,"swatchHighlight") && !YUD.hasClass(t,"selected")){
				YUD.addClass(t, "swatchHighlight");
			}else if(!YUD.hasClass(t,"selected")){
				YUD.removeClass(t,"swatchHighlight");
			}
		}else{
			return true;
		}
	}
	this.highlightSwatch = function(po,s){
		if(!s || !po){ return; }
		var sws = YUD.getElementsByClassName('colorSwatch', null, po.pn);
		for(var x = 0; x < sws.length; x++){
			if(sws[x].id == s.id){ YUD.addClass(sws[x],'selected'); }
			else{ 
				YUD.removeClass(sws[x],'selected'); 
				YUD.removeClass(sws[x],'swatchHighlight'); 
			}
		}
	}
	
	this.setColor = function(po){
		var seq = po.selectedColor, seqPrefix = '', f=po.form;
		if(typeof(seq) != 'string' && seq < 10){ seqPrefix = '0'; }
		
		po.highlightSwatch(po, $('swatch_'+po.productId+'_'+seq));
		
		var copy = '';
		
		//hackityhack for showing zoomed jean fronts on multiproduct until f/b support is added.
		var zoomType = (po.view == 2) ? 'f' : 'x'; 
		
		for(var y = 0; y < po.colorArray.length; y++){
			if(po.colorArray[y].seq == seq){
				if (po.template != 'v'){
					YUD.getElementsByClassName('productImage', null, po.pn)[0].src = po.colorArray[y].image.src;
					if($("zoomImg_" + po.productId)){
						$("zoomImg_" + po.productId).src = collPath + po.collection + "_" + seq + "_900_" + zoomType + ".jpg";
					}
				}
				var color = po.colorArray[y].name, price = po.colorArray[y].oprice;
				f.color.value = color;
				
				var copy = po.productCopy;
				if (po.colorArray[y].copy != 'null' && po.colorArray[y].copy != ''){
					copy = po.colorArray[y].copy;
				}
				
				if((f.size) && (f.size.tagName.toLowerCase() == 'select')){
					f.size.options.length = 0;
					f.size.options[0] = new Option("Select Size");
				}
				
				for(var t = 0; t < po.colorArray[y].skus.length; t++){
					if (po.colorArray[y].skus[t].backordered){
						var shipDate = po.colorArray[y].skus[t].backdate, today = new Date(), month = today.getMonth() +1, day = today.getDate();
						if(month <10){ month = "0"+month; }
						if(day<10){ day = "0"+day; }
						var now = today.getFullYear() +""+ month +""+ day;
					}
					if (po.colorArray[y].skus[t].size == 'ONE SIZE'){
						po.oneSize = true;
						var html = '<input type="hidden" name="size" value="'+po.colorArray[y].skus[t].catentry+'" />';
				        if(po.colorArray[y].skus[t].backordered == true){
				        	if(shipDate <= now){ 
				        		html += 'Backordered<br/>'; 
				        	}else{ 
								shipStr = shipDate.substring(4,6) + "/" + shipDate.substring(6,8) + "/" + shipDate.substring(2,4);
				        		html += 'Will Ship ' + shipStr + '<br/>'; 
				        	}
				        }
				        YUD.getElementsByClassName('sizeBox', null, po.pn)[0].innerHTML = html;
				      
					} 
					if(!po.oneSize){
						//Set Sizes 
						if (po.colorArray[y].skus[t].backordered){
							if(shipDate <= now){
								f.size.options[f.size.options.length] = new Option((po.colorArray[y].skus[t].size)+" - Backordered",po.colorArray[y].skus[t].catentry);
							}else{
								shipStr = shipDate.substring(4,6) + "/" + shipDate.substring(6,8) + "/" + shipDate.substring(2,4);
								f.size.options[f.size.options.length] = new Option((po.colorArray[y].skus[t].size)+" - Will Ship " + shipStr,po.colorArray[y].skus[t].catentry);
							}
						} else {
							f.size.options[f.size.options.length] = new Option((po.colorArray[y].skus[t].size),po.colorArray[y].skus[t].catentry);
						}
					}
				}
				var pcol = YUD.getElementsByClassName('prodColor', null, po.pn)[0], poff = YUD.getElementsByClassName('prodOff', null, po.pn)[0], pcpy = YUD.getElementsByClassName('prodCopy', null, po.pn)[0];
				if(pcol){ pcol.innerHTML = color; }
				if(poff){ poff.innerHTML = price; }
				if(pcpy){ pcpy.innerHTML = copy; }
				var atbBtn = getFirstATB(po.pn);
				atbBtn.style.cursor = 'pointer';
				YUD.removeClass(atbBtn, "processingBtn");
				YUD.removeClass(atbBtn, "itemAddedBtn");
				YUD.addClass(atbBtn, "addToBagBtn");
			}
		}
	}
	
	function displayProdUtil(pu, po){
		HTB.toggleSelects("hidden");
		YUD.setStyle(pu, "opacity", "0");
		YUD.setStyle(pu, "display", "block");
		var showPU = new YUA(pu, { opacity:{ to:1 } },.25);
		showPU.onComplete.subscribe(function(){
			HTB.fixPngs();
		});
		showPU.animate();
	}
	
	function closeProdUtil(pu){
		var hidePU = new YUA(pu, { opacity:{ to:0 } },.25);
		var pic = YUD.getElementsByClassName("prodImgCntnr", "div", pu.parentNode)[0];
		hidePU.onComplete.subscribe(function(){
			YUD.setStyle(pu, "display", "none");
		});
		
		if(YUD.hasClass(pu, 'eafUtil')){
			YUD.setStyle("EmailFriendForm_" + productId, "display", "block");
			YUD.setStyle("eafResponse_" + productId, "display", "none");
		}else if(YUD.hasClass(pu, 'wlUtil')){
			YUD.setStyle($("wishListForm_" + productId), "display", "block");
			YUD.setStyle("wlResponse_" + productId, "display", "none");
		}
		
		hidePU.animate();
		HTB.toggleSelects("visible");
	}
	
	function prepWishlist(po){
		var f = $("wishListForm_" + po.productId);
		var f2 = po.form
		var size;
		var sizeOptions = po.oneSize && po.template == 'v' ? po.form.size.getElementsByTagName('option') : po.form.getElementsByTagName('option');
		if (po.oneSize){
			var catentry = f2.size.value;
			if(template == 'v'){
	    		 for(i = 0; i < sizeOptions.length; i++){
	    	 		if(sizeOptions[i].selected){
	    	 			size = sizeOptions[i].innerHTML;
	    	 		}
	    	 	}
	    	}
		}else{
	    	 var catentry = po.form.size.value;
	    	 for(i = 0; i < sizeOptions.length; i++){
	    	 	if (sizeOptions[i].selected){
	    	 		size = sizeOptions[i].innerHTML;
	    	 	}
	    	 }
	    }
	    f.catEntryId.value = catentry;
	    if(size){
			$("wlSize_" + po.productId).innerHTML = size;
		}else{
			YUD.setStyle($("wlSize_" + po.productId), "display", "none");
		}
		$("wlColor_" + po.productId).innerHTML = $("prodColor_" + po.productId).innerHTML;
		$("wlPrice_" + po.productId).innerHTML = $("prodOff_" + po.productId).innerHTML;
		YUD.setStyle($("wlResponse_" + po.productId), "display", "none");
	}
	
	function prepEAF(po){
		var f = $("EmailFriendForm_" + po.productId);
		$("eafColor_" + po.productId).innerHTML = $("prodColor_" + po.productId).innerHTML;
		$("eafPrice_" + po.productId).innerHTML = $("prodOff_" + po.productId).innerHTML;
	}
	
	function wlSubmit(e,po){
		var f = $("wishListForm_" + po.productId), cookie = HTB.readCookie('wishList');
		var cb = {
			success: function(o){
				YUD.setStyle($("wlSubmit_" + po.productId), "cursor", "pointer");
				YUD.setStyle(f, "display", "none");
				f.reset();
			
				if(o.responseXML.getElementsByTagName('wasItemAdded')[0].firstChild.nodeValue === "true") {	 
		        	if(!cookie || cookie == "false"){
						HTB.createCookie('wishList', true);
					}
					YUD.setStyle($("wishListLink"), "display", "inline");
				} else {
					$('wlResponse_'  + po.productId).innerHTML = o.responseXML.getElementsByTagName('statusMsg')[0].firstChild.nodeValue;
				}

				YUD.setStyle($("wlResponse_" + po.productId), "display", "block");
			},
			failure: function(o){
				YUD.setStyle($("wlSubmit_" + po.productId), "cursor", "pointer");
			}
		}
		YUD.setStyle($("wlSubmit_" + po.productId), "cursor", "wait");
		YUC.setForm(f);
		YUC.asyncRequest("GET", f.action, cb);
	}
	
	function eafSend(e, po){
		var f = $("EmailFriendForm_" + po.productId), r = $("eafResponse_" + po.productId);
		var cb = {
			success: function(o){
				$("eafLastRecipient_" + po.productId).innerHTML = f.toEmail.value;
				YUD.setStyle(f.parentNode, "cursor", "default");
				YUD.setStyle(f, "display", "none");
				f.toEmail.value = "";
				f.fromEmail.value = "";
				f.bodyEmail.value = "";
				YUD.setStyle(r, "display", "block");
				$("eafUtil_" + po.productId).closeTO = setTimeout(function(){ closeProdUtil($("eafUtil_" + po.productId)); }, 1000);
			},
			failure: function(o){
				//failed...
				YUD.setStyle(f.parentNode, "cursor", "default");
			}
		}
		YUD.setStyle(f.parentNode, "cursor", "wait");
		if(HTB.validateEmail(f.toEmail) && HTB.validateEmail(f.fromEmail)){
			f.collection.value = po.collection;
			f.price.value = $("prodOff_" + po.productId).innerHTML;
			f.name.value = $("prodName_" + po.productId).innerHTML;
			f.color.value = $("prodColor_" + po.productId).innerHTML;
			f.productId.value = productId;
			f.storeId.value = globalStoreId;
			f.catalogId.value = globalCatalogId;
			f.langId.value = -1;
			f.cseq.value = parseInt(po.selectedColor, 10);
			YUC.setForm(f);
			YUC.asyncRequest("POST", f.action, cb);
			$("eafMsg_" + po.productId).innerHTML = "";
		}else{
			YUD.setStyle(f.parentNode, "cursor", "default");
			$("eafMsg_" + po.productId).innerHTML = "Please provide valid e-mail addresses.";
		}
	}
	
	function openSizeChart(po){
		if(!po || !po.sizeChart)
			return;
			
		switch(po.sizeChart)
		{
			case 3:
				chartDiv = "bettysTopsDiv";
				break;
			case 4:
				chartDiv = "bettysBottomsDiv";
				break;
			case 5:
				chartDiv = "bettysAccDiv";
				break;
			case 6:
				chartDiv = "dudesTopsDiv";
				break;
			case 7:
				chartDiv = "dudesBottomsDiv";
				break;
			default:
				chartDiv = "dudesAccDiv";
				break;
		}
		
		HTB.getFadeUp($("scFDC"));
		showSizeChartContent(chartDiv);
	}
	
	function utilIconMouseOnOff(e){
		var t = YUE.getTarget(e);
		$("utilMessage_" + productId).innerHTML = t.alt || '';
		HTB.toggle.visibility($("utilMessage_" + productId));
	}
	
	function utilIconClick(e, po){
		var t = YUE.getTarget(e), f = po.form;
		if(YUD.hasClass(t, "utilIcon")){
			if(YUD.hasClass(t, "sizeChartImg")){
				openSizeChart(po);
			}else if(YUD.hasClass(t, "wishlistImg")){
				//HTB.getFadeUp($("wlFDC"));
				if((!po.oneSize) && (f.size.options && f.size.selectedIndex == 0)) {
					alert('Please select a size.');
					return false;
				} else if((po.template == 'v') && (f.sizelist && f.sizelist.value == '')){
					alert("Please select a style.");
					return false;
				}else{
					prepWishlist(po);
					displayProdUtil($("wlUtil_" + productId), po);
				}
			}else if(YUD.hasClass(t, "eafImg")){
				//HTB.getFadeUp($("eafFDC"));
				prepEAF(po);
				displayProdUtil($("eafUtil_" + po.productId), po);
			}else if(YUD.hasClass(t, "printImg")){
				print();
				//alert("printable version of product page");
			}
		}else{
			return true;
		}
	}
	
	this.init = function(po){
		return function(e){
			
			var sunrisePage = YUD.hasClass(document.body, "sunrise");
			
			var pn = $('productDiv_' + po.productId);
			if(!pn){ return; }
			
			pn.po = po;
			po.pn = pn;
			po.form = $('OrderItemUpdate_'+ po.productId);
			
			//add event handlers for elements in parent node (pn)
			var ss = YUD.getElementsByClassName('size', null, pn)[0], sls = YUD.getElementsByClassName('sizelist', null, pn)[0] || null, sws = YUD.getElementsByClassName('colorSwatch', null, pn), zg = YUD.getElementsByClassName('zoomGraphic', null, pn)[0], xlzg = YUD.getElementsByClassName('xlZoomGraphic', null, pn)[0]; 
			
			//size select - getVBImg, change AddToBag img src to _green version
			YUE.on(ss, 'change', function(po){ return function(e){ po.chngColor(e,po); }; }(po), false);
			
			//OrderItemUpdate form - on submit should return results of setBagon('submit')
			YUE.on(po.form, 'submit', function(e){ return false; }, false);
			
			//if sizelist select exists add on change handler to setColor
			if(sls){
				YUE.on(sls, 'change', function(po){ return function(e){ po.chngColor(e,po); }; }(po), false);
			}
			
			YUE.on($("prodUtils_" + po.productId), "mouseover", utilIconMouseOnOff, po);
			YUE.on($("prodUtils_" + po.productId), "mouseout", utilIconMouseOnOff, po);
			YUE.on($("prodUtils_" + po.productId), "click", utilIconClick, po);
			YUD.getElementsByClassName("closeProdUtil", "img", null, function(el){
				YUE.on(el, "click",  function(e){
					var t = YUE.getTarget(e);
					clearTimeout(t.parentNode.closeTO);
					closeProdUtil(t.parentNode);
				});
			});
			
			YUE.on($("swatches_" + po.productId), "mouseover", togSwatch);
			YUE.on($("swatches_" + po.productId), "mouseout", togSwatch);
			
			YUE.on($("eafSend_" + po.productId), "click", eafSend, po);
			YUE.on($("wlSubmit_" + po.productId), "click", wlSubmit, po);
			
			//pn - click - if target was a swatch, fire set color for appropriate sequence
			YUE.on(pn, 'click', po.clickHandler, false);
			
			po.getVBImg(po);
			
			po.setColor(po);
		};
	}
	YUE.on(window, 'load', this.init(this), false);
}