	var removeBadImagesRef = new Array();
	
	$(window).unload(function() {
		for(var k = 0; k < removeBadImagesRef.length; k++) {
			removeBadImagesRef[k]._parent = null;
		}
	});

	///////////////////////////////////////////////fixed method My instance
	/////////////////////////////////SjPicture
	function SjPicture(inParent, inElementId,inWidth,inHeight,transparency) {
		if (arguments[0] == 'empty') {
			return;
		}
		this.SjElement = SjElement;
		this.SjElement(inParent, inElementId);
		if (this._parent && this._parent._elementId){
			sjCreateDiv(this._parent._elementId , this._elementId);
		}else{
			sjCreateDiv(null , this._elementId);
		}
		if (typeof tsj != 'undefined'){
			this.codePath		= tsj.path;
		}else if(typeof sj != 'undefined'){
			this.codePath		= sj.path;
		}else{
			this.codePath		= '../dhtml/';
		}
	
		this.transparency = transparency || false;
		this._imageWidth = 0;
		this._imageHeight = 0;
		this._stretch = false;
		this.scale = 1;
		this.loaded = false;
		this.img = new Image();
		this.img._uId = this._elementId + '_img';
		this.img.str = ' <img';
		this.img.str += ' id=' + this.img._uId;
		this.img.str += ' name=' + this.img._uId;
		this.img.str += ' border=' + 0;
		this.img.str += ' style="position:absolute;left:0;top:0;"';
		this.img.str += '> ';
		sjSetLayerHTML(this._elementId,this.img.str);
		this._content = sjGetElement(this._elementId);
		this.imageElm = sjGetElement(this.img._uId);
		this.imageElm._parent = this;
		this.useMap='';
		this.imageElm.useMap='';
		this.img._parent = this;	
		removeBadImagesRef.push(this.img);
	}
	
	SjPicture.prototype = new SjElement('empty');
	
	SjPicture.prototype.load = function(inURL) {
		if (inURL == this.img.src) {
			if ((this.loaded == true)&&(this.img.complete==true)){//check for complete loading of image 
				this.img.onload = this.onLoad;
				this.img.style.width = this._imageWidth;
				this.img.style.height = this._imageHeight;
				this.img.onload();
			}
			return;
		}
		this.loaded = false;
		if (document.all) {
			sjGetElement(this.img._uId).outerHTML=this.img.str;
			this.imageElm = sjGetElement(this.img._uId);
			this.imageElm._parent = this;
			this.img._parent = this;
		}else{
			this.img.style.width="";
			this.img.style.height="";
		}	
		this.img.onload=null;
		this.img.onerror=null;
		this.img.onabort=null;
		this.img.onload=this.onLoad;
		this.img.onerror=this.onError;
		this.img.onabort=this.onAbort;
		this.img.src = inURL;
	    this.imageElm.src = inURL;
		this.imageElm.useMap = this.useMap;
	};
	
	
	SjPicture.prototype.onLoad = function() {
		this._parent.loaded = true;
		this._parent._imageWidth = this.width;
		this._parent._imageHeight = this.height;
		this._parent.stretch(this._parent.stretch());
		//////IE png support
		var version = parseFloat(navigator.appVersion.split("MSIE")[1]);
		var haveFilters = null;
		if ((version >= 5.5) && (version < 8)){
				try {
					haveFilters = document.body.filters;
				}catch(e){
					//alert();
				}
		}
		if ((version >= 5.5) && (version < 8) && (haveFilters != null)){
			var img = this;
			var imgName = this.src.toUpperCase()
			if (this._parent.transparency){
				var imgID = (img.id) ? "id='" + img.id + "' " : "";
				var imgName = (img.name) ? "name='" + img.name + "' " : "";
				var imgBorder = (img.border) ? "border='" + img.border + "' " : "";
				var imgStyle = "display:inline-block;" + img.style.cssText;
				var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' ";
				var imgAlt = (img.alt) ? "alt='" + img.alt + "' " : "alt='" + img.alt + "' ";
				if (img.useMap){  
					strAddMap = "<img style=\"position:relative; left:-" + img.width + "px;"
					+ "height:" + img.height + "px;width:" + img.width +"\" "
					+ "src=\"" + this._parent.codePath+"images/spacer.gif" + "\" usemap=\"" + img.useMap 
					+ "\" border=\"" + img.border + "\">"
				 }
				 var strNewHTML = "<img " + imgID + imgName + imgTitle + imgAlt + imgBorder
								 + ' src='+this._parent.codePath+"images/spacer.gif"
								 + " style=\"" + imgStyle + ";"
								 + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
								 + "(src=\'" + img.src + "\', sizingMethod='scale');"
								 + "\">";
				if (img.useMap){
					strNewHTML += strAddMap;
				}
				img.outerHTML = strNewHTML;
			 }
		}
		/////////
		this._parent.fireEvent('load');
	};
	
	SjPicture.prototype.onError = function() {
		this._parent.loaded = false;
		this._parent.fireEvent('error');
	};
	
	SjPicture.prototype.onAbort = function() {
		this._parent.loaded = false;
		this._parent.fireEvent('abort');
	};
	
	SjPicture.prototype.stretch = function(inStretch) {
		if (inStretch != null) {
			this._stretch = inStretch;
			var w = this.width();
			var h = this.height();
			if (this._stretch) {
				sjSetWidth(this.img._uId, this._width);
				sjSetHeight(this.img._uId, this._height);
			} else {
				sjSetWidth(this.img._uId, this._imageWidth);
				sjSetHeight(this.img._uId, this._imageHeight);
			}
				sjZoomMap (this.imageElm.useMap.substring(1), this.width()/w, this.height()/h);
		}
		return this._stretch;
	};
	
	SjPicture.prototype.super_width = SjPicture.prototype.width;
	SjPicture.prototype.width = function(inWidth) {
		var w = this.super_width();
		var h = this.super_height();
		var ret = this.super_width(inWidth);
		if (inWidth != null) {
				if (this._stretch) {
					sjSetWidth(this.img._uId, this._width);
					sjSetHeight(this.img._uId, this._height);
				}
				sjZoomMap (this.imageElm.useMap.substring(1), this.width()/w, this.height()/h);
		}
		return ret;
	};
	
	SjPicture.prototype.super_height = SjPicture.prototype.height;
	SjPicture.prototype.height = function(inHeight) {
		var w = this.super_width();
		var h = this.super_height();
		var ret = this.super_height(inHeight);
		if (inHeight != null) {
				if (this._stretch) {
					sjSetWidth(this.img._uId, this._width);
					sjSetHeight(this.img._uId, this._height);
				}
				sjZoomMap (this.imageElm.useMap.substring(1), this.width()/w, this.height()/h);
		}
		return ret;
	};
	
	SjPicture.prototype.map = function(inMap) {
		if (inMap!= null){
		  this.imageElm.useMap=this.useMap='#'+inMap;
		}else
		return this.imageElm.useMap;
	};
	
	SjPicture.prototype.clearMap = function() {
		  this.imageElm.useMap=this.useMap='';
	};
	
	/////////////////////////////////SjZoomNav
	function SjZoomNav(inObj,inWidth,inHeight,inPosition,inNav,transparency){
		this.SjElement = SjElement;
		if ((typeof inNav == 'undefined')) {
			inNav = 'izNav';
		}
	    if (sjGetElement(inNav)){
			this.SjElement(sjGetElement(inNav), null);
			if (this._parent){
				sjCreateDiv(sjGetElement(inNav), this._elementId);
			}else{
				sjCreateDiv(null , this._elementId);
			}
			this.elem=sjGetElement(this._elementId);
			this.elem._elementId = this._elementId;
			this._content		= sjGetElement(this._elementId);
			
			this.setSize(sjGetElement(inNav).offsetWidth || 50,sjGetElement(inNav).offsetHeight || 50);
			sjSetWidth(inNav, this.width());
			sjSetHeight(inNav, this.height());
		    this.toXY(0,0);
		}else{
			this.SjElement(inObj, null);
			if (this._parent && this._parent._elementId){
				sjCreateDiv(this._parent._elementId , this._elementId);
			}else{
				sjCreateDiv(null , this._elementId);
			}
			this.elem=sjGetElement(this._elementId);
			this.elem._elementId = this._elementId;
			this._content		= sjGetElement(this._elementId);
			
			this.setSize(inWidth || 50,inHeight || 50);
		}
	
		this.transparency = transparency;
		this.navObj = null;
	
		this.navImage = new SjPicture(this.elem,null,null,null,this.transparency);
		this.navImage.visible(false);
		sjSetBorder(this._elementId,1,'solid',"#666666");
		this.navImage.setSize(inWidth || 50,inHeight || 50);
		this.navImage.stretch(true);
		this.navImage.zIndex(this.zIndex()+1);
	
		this.dblnavImage = new SjPicture(this.elem,null,null,null,this.transparency);
		this.dblnavImage.setSize(inWidth || 50,inHeight || 50);
		this.dblnavImage.stretch(true);
		this.dblnavImage.visible(false);
	
		this.dragImage = new SjLayer(this);
		this.dragImage.zIndex(100);
		this.dragImage.visible(false);
		this.dragImage.setSize(inWidth || 50,inHeight || 50);
	
		this.borderWidth  = 2;
		this.borderColor = '#ff0000';
		var str='<img id='+this.dragImage._elementId+'_img style="left:2px;top:2px;width:'+this.dragImage.width()+'px;height:'+this.dragImage.height()+'px;">';
		sjSetLayerHTML(this.dragImage._elementId,str);
		sjGetElementStyle(this.dragImage._elementId+'_img').border='#ff0000 2px solid'; 
		this.visible(false);
		this.position = inPosition || 'absolute';
		if (this.position == 'absolute'){
			sjGetElementStyle(this._elementId).position='absolute'; 
		}else{ 
		}
		this.initialLoading	= true;
	}
	
	SjZoomNav.prototype = new SjElement();
	
	SjZoomNav.prototype.setViewer = function(inObj){
		this.navObj = inObj;
		if (this.navObj){
			this.navObj.navLayer = this;
			sjGetElement(this.dragImage._elementId+'_img').src = this.navObj.codePath+"images/spacer.gif";
			this.initHandlers();
			if ((this.navObj.navloadURL) && (this.navObj.imgServerWidth) && (this.navObj.imgServerHeight)){
				this.navObj.navDefaultScl = Math.max(Math.max(this.navObj.imgServerWidth / (this.width()-5), this.navObj.imgServerHeight / (this.height()-5)), 1.0);
				this.navObj.navloadURL +='&scl='+(this.navObj.navDefaultScl)+this.navObj.idStr;
				this.dblnavImage.load(this.navObj.navloadURL);
			}
		}
	}
	
	SjZoomNav.prototype.update = function(x,y,w,h){
		if(this.navObj){
			this.navObj.navigatorScl= Math.max(w/this.navImage.width(),h/this.navImage.height());
			var fixedX = Math.max(-x/this.navObj.navigatorScl,0);
			var fixedY = Math.max(-y/this.navObj.navigatorScl,0);
			this.dragImage.toXY(fixedX+this.navImage.left(),fixedY+this.navImage.top());
			var fixedWidth = Math.min(this.navObj.width()/this.navObj.navigatorScl, this.navImage.width());
			var fixedHeight = Math.min(this.navObj.height()/this.navObj.navigatorScl, this.navImage.height());
			this.dragImage.setSize(fixedWidth,fixedHeight);
			sjGetElementStyle(this.dragImage._elementId+'_img').width = Math.round(((this.dragImage.width()-this.borderWidth*2)<1?1:(this.dragImage.width()-this.borderWidth*2)))+"px";
			sjGetElementStyle(this.dragImage._elementId+'_img').height = Math.round(((this.dragImage.height()-this.borderWidth*2)<1?1:(this.dragImage.height()-this.borderWidth*2)))+"px";
		}
	}
	
	SjZoomNav.prototype.moving=false;
	SjZoomNav.prototype.startDrag=false;
	
	
	SjZoomNav.prototype.updateNav = function(){
		this.navImage.load(this.dblnavImage.img.src);
	}
	
	SjZoomNav.prototype.initHandlers = function(){
		var obj = this;
		var objNav = this.navObj;
		this.dblnavImage.addEventListener("load", 
			function (){
				var scl = 1;
				obj.dblnavImage.stretch(true);
				obj.dblnavImage.setSize(obj.dblnavImage.img.width*scl,obj.dblnavImage.img.height*scl);
				obj.dblnavImage.toXY((obj.width() - obj.dblnavImage.width())/2,(obj.height() - obj.dblnavImage.height())/2);
				if (obj.navImage._fadeid) {
						clearTimeout(obj.dblnavImage._fadeid);
						obj.dblnavImage._fadeid = null;
				}
				if (obj.navImage._fadeid) {
						clearTimeout(obj.navImage._fadeid);
						obj.navImage._fadeid = null;
				}
				if (!obj.initialLoading){
					obj.navImage.fadeOut(obj.navObj.turnTime/2);
					setTimeout(obj+'.updateNav()',obj.navObj.turnTime/2);
				}else{
					obj.navImage.load(obj.dblnavImage.img.src);
				}
					obj.dblnavImage.visible(true);
				return false;
			}
		);
		this.navImage.addEventListener("load", 
			function (){
				var scl = 1;
				obj.navImage.stretch(true);
				obj.navImage.setSize(obj.navImage.img.width*scl,obj.navImage.img.height*scl);
				obj.navImage.toXY((obj.width() - obj.navImage.width())/2,(obj.height() - obj.navImage.height())/2);
				obj.dragImage.setSize(obj.navImage.width(),obj.navImage.height());
				var newx =(obj.navImage.width() - obj.dragImage.width())/2;
				var newy =(obj.navImage.height() - obj.dragImage.height())/2;
				obj.dragImage.toXY(newx+obj.navImage.left(),newy+obj.navImage.top());
				sjGetElementStyle(obj.dragImage._elementId+'_img').width = Math.round(((obj.dragImage.width()-obj.borderWidth*2)<1?1:(obj.dragImage.width()-obj.borderWidth*2)))+"px";
				sjGetElementStyle(obj.dragImage._elementId+'_img').height = Math.round(((obj.dragImage.height()-obj.borderWidth*2)<1?1:(obj.dragImage.height()-obj.borderWidth*2)))+"px";
				if (obj.navImage._fadeid) {
						clearTimeout(obj.dblnavImage._fadeid);
						obj.dblnavImage._fadeid = null;
				}
				if (obj.navImage._fadeid) {
						clearTimeout(obj.navImage._fadeid);
						obj.navImage._fadeid = null;
				}
				if (!obj.initialLoading){
					obj.navImage.fadeIn(obj.navObj.turnTime/2);
					obj.navImage.visible(true);
				}else{
					obj.navImage.visible(true);
					obj.dblnavImage.visible(false);
				}
				obj.update(obj.navObj.currentX,obj.navObj.currentY,obj.navObj.backImage.width(),obj.navObj.backImage.height());
				obj.dragImage.visible(true);
				obj.initialLoading	= false;
				return false;
			}
		);
	
		this.dragImage.addEventHandler('mousedown',
			function (o,evt){
				objNav.storeImagesXY();
				ex = evt.posx;
				ey = evt.posy;
				obj.startDrag=true;
				sjSetCursor('hand');
				return false;
			}
		);
		this.dragImage.addEventHandler('mousemove',
			function (o,evt){
				if (obj.startDrag){
					obj.moving=true;
					var diffX = evt.posx - ex;
					var diffY = evt.posy - ey;
					objNav.setPosition(objNav.backImage,objNav.bx - diffX*objNav.navigatorScl,objNav.by - diffY*objNav.navigatorScl,objNav.currentScl);
					objNav.foreImage.left(objNav.currentX-objNav.bx+objNav.fx);
					objNav.foreImage.top(objNav.currentY-objNav.by+objNav.fy);
				}
				return false;
			}
		);
		this.dragImage.addEventHandler('mouseup',
			function (o,evt){
				if(obj.moving){
					obj.moving=false;
					objNav.updateForeImage();
				}else{
					if (evt.ctrlKey){
					} else {
					}
				}
				obj.startDrag=false;
				sjSetCursor('default');
				return false;
			}
		);
	
		this.navImage.addEventHandler('mousedown',
			function (o,evt){
				objNav.storeImagesXY();
				ex = evt.posx;
				ey = evt.posy;
				obj.startDrag=true;
				sjSetCursor('hand');
				return false;
			}
		);
		this.navImage.addEventHandler('mousemove',
			function (o,evt){
				if (obj.startDrag){
					obj.moving=true;
					var diffX = evt.posx - ex;
					var diffY = evt.posy - ey;
					objNav.setPosition(objNav.backImage,objNav.bx - diffX*objNav.navigatorScl,objNav.by - diffY*objNav.navigatorScl,objNav.currentScl);
					objNav.foreImage.left(objNav.currentX-objNav.bx+objNav.fx);
					objNav.foreImage.top(objNav.currentY-objNav.by+objNav.fy);
				}
				return false;
			}
		);
		this.navImage.addEventHandler('mouseup',
			function (o,evt){
				if(obj.moving){
					obj.moving=false;
					objNav.updateForeImage();
				}else{
					if (evt.ctrlKey){
					} else {
					}
				}
				obj.startDrag=false;
				sjSetCursor('default');
				return false;
			}
		);
	
	
		this.addEventHandler('mouseout',
			function (o,evt){
				if(obj.moving){
					obj.moving=false;
					objNav.updateForeImage();
				}else{
					if (evt.ctrlKey){
					} else {
					}
				}
				obj.startDrag=false;
				sjSetCursor('default');
				return false;
			}
		);
	}
	
	SjZoomNav.prototype.setBorder = function(sz,inColor) {	
		if ((inColor.indexOf("#") == -1) && ((inColor.indexOf("0x") == -1))) {
			inColor = "#"+inColor;
		}else if (inColor.indexOf("0x") != -1) {
			inColor = inColor.replace("0x","#");
		}
		this.borderColor = inColor || "#ff0000";
		this.borderWidth = parseInt(sz) || 2;
		sjGetElementStyle(this.dragImage._elementId+'_img').border=""+this.borderColor+" "+parseInt(this.borderWidth)+"px solid"; 
		sjGetElementStyle(this.dragImage._elementId+'_img').width = Math.round(((this.dragImage.width()-this.borderWidth*2)<1?1:(this.dragImage.width()-this.borderWidth*2)))+"px";
		sjGetElementStyle(this.dragImage._elementId+'_img').height = Math.round(((this.dragImage.height()-this.borderWidth*2)<1?1:(this.dragImage.height()-this.borderWidth*2)))+"px";
	}
	///////////////////////////////////////////////
	SjZoom.prototype.setWaitIconURL = function(inURL){
		if (this.waitIcon){
			this.waitIconURL = inURL || null;
			if((this.waitIconURL != null) && (this.waitIconURL != "")){		
				this.waitIcon.load(this.waitIconURL);
			}
		}
	}
	///////////////////////////////////////////////end fixed
//$.jsNamespace('com.landsend.productView');
var com;
if(com == undefined){
	com = new Object();
}
if(com.landsend == undefined){
	com.landsend = new Object();
}
if(com.landsend.productView == undefined){
	com.landsend.productView = new Object();
}


com.landsend.productView.InlineShoppingBagController = function(){	
	var prodViewNs = com.landsend.productView;
	var inlineShoppingBagView = new prodViewNs.InlineShoppingBagView(this);
	var requestPath = "/co/UpdateItem";
	var shoppingBagUrl = "https://" + window.location.host + "/co/ShoppingBag.html?refer=" + encodeURIComponent(window.location.href);
	var response = null;
	var redirectToShoppingBag = true;
	var gcConstants = com.landsend.productView.GCConstants;
	
	this.getView = function(){
		return inlineShoppingBagView;
	};
	
	var Response = function(){
		var cartTotal = null;
		var numItems = null;
		var isLoggedIn = null;
		var selections = null;
		var idPrefix = "inlineBag_";
		this.keepShoppingFunction = null;
		this.idCode = new Date().getTime();
		this.id = idPrefix + this.idCode;
		this.loaded = true;
		this.itemInBag = false;
	};
	
    var buildSelectionAddToBagString = function(selection,index,data){
    	index = index + 1;
    	if(index == 1){
    		index = "";
    	}else{
    		index = "_" + index;
    	}
    	
    	var sizeCode = "";
    	var colorCode = "";
    	
    	if (prodViewNs.GCConstants.GCProduct(selection.productNumber)) { 		
    		data.functionName='updateGiftCardItem';
    		data.productNumber = selection.productNumber;
    	}
    	else {
    		data.functionName='updateItem';
    	}
    	
    	if(selection.sku.getSize() != null){sizeCode = selection.sku.getSize().getFormattedCode();}
    	if(selection.colorCode != null || selection.colorCode != undefined){colorCode = selection.colorCode;}
    	
    	if (selection.style.getCatalogNumber().getMediaCode() != undefined && 
    			selection.style.getCatalogNumber().getMediaCode()  != null)
    		data["mediaCode" + index] = selection.style.getCatalogNumber().getMediaCode().getMediaCodeId();
    	else 
    		data["mediaCode" + index] = "";
    	data["styleNum" + index] = selection.style.getNumber();
    	data["sizeCode" + index] = sizeCode;
    	data["colorCode" + index] = colorCode;	
    	
    	data["quantity" + index] = selection.quantity;
    		
    	if(selection.itemId != null && selection.itemId != undefined){
    		data["itemKey"] = selection.itemId;
    	}else{
    		data["itemKey"] = -1;
    	}
    	
    	if(selection.monogramApplied){
    		data["monoLoc" + index] = selection.monogramLocation;
    		data["monoTypeCode" + index] = selection.monogramFont;
    		
    		var monoValue;
			if(selection.monogramType == 1){ // initial 
            	data["monoIsInitial" + index] = true;
                monoValue = selection.monogramSingleInitalText;
			}else if(selection.monogramType == 2){ // initials 
                monoValue = selection.monogramMultiInitial.join("");
                data["monoIsInitial" + index] = true;
			}else if(selection.monogramType == 3){ // word 
				monoValue = selection.monogramWordText;
			}else if(selection.monogramType == 4){// multi-word
                monoValue = selection.monogramMultiLine.join("|");
			}
	        
			data["monoValue" + index] = monoValue;
			if (selection.sku.getDefaultMonoThreadColor() == null){
				data["monoColor" + index] = "";
			} else {
				data["monoColor" + index] = selection.sku.getDefaultMonoThreadColor().getCode();
			}
    	} else {
     		data["monoLoc" + index] = "";
    		data["monoTypeCode" + index] = "";
    		data["monoValue" + index] = "";
    		data["monoColor" + index] = "";
    	}
    
    	if(selection.inseam != null){
    		if (selection.inseam == 'UNF'){
    			data["isInseamUnfinished" + index] = "true";
    		} else {
	    		data["inseamLength" + index] = selection.inseam;
	    		if(selection.cuffing != null && selection.cuffing == "cuffed"){
	    			data["isCuffed" + index] = true;
	    		}
	    	}
    	}
    	
    	if(selection.schoolNumber != undefined && selection.schoolNumber != null){
    		data["schoolOrgNum" + index] = selection.schoolNumber;
    	} else {
      		data["schoolOrgNum" + index] = "";  		
    	}
    	
    	if(selection.schoolLogoCode != undefined && selection.schoolLogoCode != null && selection.schoolNumber != undefined && selection.schoolNumber != null){
			data["schoolLogoId" + index] = selection.schoolLogoCode;
			data["schoolLogoLocCode" + index] = "LSC";
    	} else {
			data["schoolLogoId" + index] = "";
			data["schoolLogoLocCode" + index] = "";
    	}
    	
    	if(selection.dropShipDayPhone != null && selection.dropShipDayPhone != ""){
    		var dropShipDayPhone = selection.dropShipDayPhone;		
    		if (selection.dropShipDayPhoneExt != null && selection.dropShipDayPhoneExt != ""){
    			dropShipDayPhone = dropShipDayPhone + "/"  + selection.dropShipDayPhoneExt;
    		}
    		data["primContactPhone" + index] = dropShipDayPhone;
    	}  
    	
    	if(selection.dropShipAltPhone != null && selection.dropShipAltPhone != ""){
    		var dropShipAltPhone = selection.dropShipAltPhone;		
    		if (selection.dropShipAltPhoneExt != null && selection.dropShipAltPhoneExt != ""){
    			dropShipAltPhone = dropShipAltPhone + "/"  + selection.dropShipAltPhoneExt;
    		}
    		data["secContactPhone" + index] = dropShipAltPhone;
    	}  
    	
   	
    	if(selection.personalizedRecipientEmail != null && selection.personalizedRecipientEmail != ""){	
    		data["personalizedRecipientEmail" + index] = selection.personalizedRecipientEmail;
    	}  
    	else {
    		data["personalizedRecipientEmail" + index] = "";
    	}
    	
    	if(selection.personalizedTo != null && selection.personalizedTo != ""){	
    		data["personalizedTo" + index] = selection.personalizedTo;
    	}  
    	else {
    		data["personalizedTo" + index] = "";
    	}
    	
    	if(selection.personalizedMessage != null && selection.personalizedMessage != ""){	
    		data["personalizedMessage" + index] = selection.personalizedMessage;
    	}  
    	else {
    		data["personalizedMessage" + index] = "";
    	}
    	
    	if(selection.personalizedFrom != null && selection.personalizedFrom != ""){	
    		data["personalizedFrom" + index] = selection.personalizedFrom;
    	}  
    	else {
    		data["personalizedFrom" + index] = "";
    	}
    	
    	if(selection.gcAmount != null && selection.gcAmount != ""){	   	
    		data["gcAmount" + index] = parseInt(selection.gcAmount * 100);
    	}  
    	else {
    		data["gcAmount" + index] = "";
    	}    	
    };	
	
    var	processResponse = function(shoppingBag){
    	response.shoppingBag = shoppingBag;
    	
    	for(var i=0; i < response.selections.length; i++) {
    		response.selections[i].itemId = shoppingBag.updatedItems[i].key;
    	}
    	
		com.landsend.persistentBag.controller.updateBagDisplay();
 
    	if (response.selections[0].mode == "update" && !redirectToShoppingBag ) {
    		return;
    	}
    	
    	if(response.selections[0].mode != null && response.selections[0].mode != undefined && response.selections[0].mode == "update"){
    		window.location = shoppingBagUrl;
    	}
    };
    
	this.addSelectionsToBag = function(selections,keepShoppingFunction,redirectToBag){
		response = new Response();
		response.selections = selections;
		response.keepShoppingFunction = keepShoppingFunction;
		var isNewAddress = null;
		var data = {};
		
		if(redirectToBag != null){
			redirectToShoppingBag = redirectToBag;
		}
		
	    for(var i=0; i < selections.length; i++) {
	    	if (selections[i] != null) {
	    		buildSelectionAddToBagString(selections[i],i,data);
	    		
	    		if(redirectToBag == null && selections[i].style.getProduct() != null && selections[i].style.getProduct().getParentProduct() != null){
	    			redirectToShoppingBag = false;
	    		}
	    	} 
	    }
	    data.debug = ($.query.get("debug")==="true");

	    data.insecure = (location.pathname.indexOf("/co/ShoppingBag.html") == -1);
	    
		$.ajax({
			   async:false,
			   url: requestPath,
			   success:processResponse,
			   error:onError,
			   timeout:45000,
			   type:"post",
			   cache:false,
			   data:data,
			   dataType:"json"
		});
	
		return response;
	};
	
	var onError = function(error){
		// TODO: Fill in correct error modal
		response.loaded = false;
		response.itemInBag = false;
    	leutil.ui.modalHandler.show({
			content:prodViewNs.Messages.findMessage(29).text,
			cssClass:"le-modal-alert",
			dialogue:true,
			scrollable:false
		});
    	throw error;		
	};
	
	this.loadRecommendations = function(selection, response) {
		var recommendationScheme = "inline_bag_rr";
		
		try
    	{
    		var funcName = "[loadRecommendations scheme = " + recommendationScheme + "] ";
    		if (resx.certonaISBActive == false ||  !metric.certonaActive)
    		{
    			$.debug(funcName + "***************************************************************************************************");
    			$.debug(funcName + "Not making an AJAX call as we are in A/B Test Group that does not display Certona Recommendations");
    			$.debug(funcName + "***************************************************************************************************");
    		}
    		else
    		{
    			var style = selection.style.getCatalogNumber().getStyleNumber();
    			var mediaCode = selection.style.getCatalogNumber().getMediaCode();
    			var mediaCodeToUse = mediaCode.getMediaCodeId();
    			var compTypeCdToUse = mediaCode.getInternetComponentTypeCode();
	    		var customSchoolNum = $.cookie("customSchoolNumber");	    		

	    		// If we are in a custom school, we use the core full price media code, so that the recommendations
	    		// bring up the core page (school number entry is not required on the core media product page).
	    		// Styles are dual listed under the core and school media codes.
	    		if(customSchoolNum != null && customSchoolNum != "" && selection.schoolNumber != undefined && selection.schoolNumber != null)
	    		{
	    			mediaCodeToUse = com.landsend.global.PageConfigParms.CORE_FULLPRICE_MEDIA_CODE;	    
	    			compTypeCdToUse = 1;
	    		}
    			
                var catStr = style + ":" + mediaCodeToUse;
                $.debug(funcName + "Certona Product Id : " + catStr);
                var resTrackingGID = $.cookie("RES_TRACKINGID");
                $.debug(funcName + "Resonsance Session ID " + resTrackingGID);
                var resSessionID = $.cookie("RES_SESSIONID");
                $.debug(funcName + "Resonance Session ID " + resSessionID);     
                var resURL = encodeURIComponent(document.URL);
                $.debug(funcName + "Resonance URL " + resURL);  
                
				resWebServiceURL =  "/ws/r2/Resonance.aspx?appid=landsend01&userid=" + resTrackingGID + 
				        "&event=product&itemid=" +  catStr + 
				        "&scheme=" + recommendationScheme + 
				        "&number=6&InetCompTypCd=" + compTypeCdToUse + 
				        "&url=" + resURL + 
				        "&trackingid=" + resTrackingGID +
				        "&sessionid=" + resSessionID;
		  			
	    		$.debug(funcName + "Certona Web Service URL " + resWebServiceURL);

	   			$.ajax({url:resWebServiceURL,
					type:"GET",
					dataType:"html",
					async: false,
					timeout:2000,
					error:function(ajaxReq, textStatus)
					{
    					$.debug(funcName + "*******************************************************************");
    					$.debug(funcName + "Error on Certona Web Service call.");
    					$.debug(funcName + "URL: " + resWebServiceURL);
    					$.debug(funcName + "Error status : " + ajaxReq.status + ' - ' + textStatus);
    					$.debug(funcName + "*******************************************************************");
					},
					success:function(recResponse)
					{
						$.debug(funcName + "Successfully received a response from the Certona Web Service call.");
						
						recText = "<ul class=\"certona-recs horizontal-list expanded man\" id=\"inline_bag_rr\">" + recResponse + "</ul>";
						response.shoppingBag.htmlMap.inlineBag = response.shoppingBag.htmlMap.inlineBag.replace("INLINE_BAG_RR", recText);
					}
	   			});
    		}
    	}catch(error)
        {
    		// We do not want this to stop the user from ordering/modifying items, so write something to the debug window and move on.
    		$.debug(funcName + "Error when requesting recommendations from Certona ");
    		$.debug(funcName + error.code + ' ' + error.message);
        }
    };
	
	this.registerRecommendationEvents = function(mediaCode) {
		if (($.cookie('schoolNumber') != null || $.cookie('customSchoolNumber') != null)
				&& mediaCode.getInternetComponentTypeCode() == 3 ){
			$("#rec_label").text("YOU MIGHT ALSO LIKE (not Dress Code specific)");
		}				    			
		
		$('.certona-recs a').hoverIntent(function() {
            le.uxd.ui.personalization.certona.showHoverRec(this, 'large');
		}, function() {
            return false;
		});
		
		if ($('.certona-recs a').length == 0){
			$("#rec_container").hide();
		} else {
			$("#rec_container").show();	    					
		}
    };
};

com.landsend.productView.InlineShoppingBagView = function(controller){
	var inlineShoppingBagController = controller;
	
	this.setKeepShoppingButtonCallBack = function(callback){
		$(".pp-continue-shopping").bind('click',callback);
	};
};
//$.jsNamespace('com.landsend.productView');
var com;
if(com == undefined){
	com = new Object();
}
if(com.landsend == undefined){
	com.landsend = new Object();
}
if(com.landsend.productView == undefined){
	com.landsend.productView = new Object();
}


/**
 * Common container for data / functionality that is shared across all product groupings.
 */
com.landsend.productView.GlobalManager = new function(){
	
	var buyGrids = new Array(); // only used to keep track of standard buy grid only product pages
	var quickViewBuyGrids = new Array(); // only used to keep track of quick view buy grid wrapper objects
	var bundleController = null; // only used to keep track of bundle buy grid wrapper objects
	var nonCustomSchool = null;
	var productPage = null;
	
	this.setNonCustomSchool = function(school){
		nonCustomSchool = school;
	}
	
	this.getNonCustomSchool = function(){
		return nonCustomSchool
	}

	this.setBundleController = function(bundleControllerPar){
		bundleController = bundleControllerPar;
	}
	
	this.getBundleController = function(){
		return bundleController;
	}		
	
	this.addQuickViewBuyGrids = function(qvGrids){
		quickViewBuyGrids = quickViewBuyGrids.concat(qvGrids);
	}	
	
	this.getQuickViewBuyGrids = function(){
		return quickViewBuyGrids;
	}

	this.findQuickViewBuyGrid = function(productId){
		for(var y = 0;y < quickViewBuyGrids.length; y++){	
			if(quickViewBuyGrids[y].getStandardBuyGridController().getProductView().getProduct().getNumber() == productId){
				return quickViewBuyGrids[y];
			}
		}		
	}	
	
	this.addStandardBuyGrids = function(byGrids){
		buyGrids = buyGrids.concat(byGrids);
	}

	this.getStandardBuyGrids = function(){
		return buyGrids;
	}
	
	this.findStandardBuyGrid = function(productId){
		for(var y = 0;y < buyGrids.length; y++){
			if(buyGrids[y].getProductView().getProduct().getNumber() == productId){
				return buyGrids[y];
			}
		}		
	}	
	
	this.setProductPage = function(prdtPage){
		productPage = prdtPage;
	}
	
	this.getProductPage = function(){
		return productPage;
	}	
}

/**
 * Manages functionality that is specific to a single product page
 */
com.landsend.productView.ProductPage = function(productDisplayGroup){
	var thisProductPage = this;
	var productViewNs = com.landsend.productView;
	var recommendationsController;
	var bundleController = null;
	var buyGrids = new Array();		
	
	var initialize = function(){		

		if (productDisplayGroup.getProduct() != null){ // bundle page
			bundleController = new com.landsend.productView.BundleController(productDisplayGroup,thisProductPage);
		}else{ // standard product page 
			for(var i = 0;i < productDisplayGroup.getProductDisplays().length;i++){ 
				buyGrids.push(new productViewNs.StandardBuyGridController(productDisplayGroup.getProductDisplays()[i],null));
			}			
			productViewNs.GlobalManager.addStandardBuyGrids(buyGrids); // only add if this is a standardbuyGrid only product page	
			
			// Assumption: The selections coming from the query string are for the first product in the product grouping.
			buyGrids[0].makeBuyGridSelections(thisProductPage.buildSelectionFromQueryString(buyGrids[0].getProductView().getProduct()));
			
			setupExternalControllers();
			registerCallbacks();
			leutil.gomez.nameEvent("buyGridBuilt");
		}
	
		buildBreadCrumb();
	}
	
	this.getRecommendationsController = function() {
		return recommendationsController;
	}
	this.initializeRecommendations = function(product, style){
		recommendationsController.loadRecommendationsForStyle(product, style);
	}
	
	var setupExternalControllers = function(){
		recommendationsController = new productViewNs.RecommendationsController();
		// Assumption: The first product media will drive the recommendations.
		recommendationsController.init(buyGrids[0].getProductView().getProduct());
	}
	
	var registerCallbacks = function(){
		registerCallbackForAddToBag();
		registerCallbackForStyleChange();
		registerCallbackForSchoolChange();
		registerCallBackForSchoolSelectionUnset();
		
	}
	
	var addToBagCallBack = function(eventType){
		if(eventType == "update" || eventType == "add" || eventType == "removed"){
			com.landsend.persistentBag.controller.updateBagDisplay();
		}		
	}
	
	var registerCallbackForAddToBag = function(){
		for(var i = 0;i < buyGrids.length;i++){ 
			buyGrids[i].registerCallbackForShoppingBag(addToBagCallBack);
		}		
	}
	
	var registerCallbackForSchoolChange = function(){
		for(var i = 0;i < buyGrids.length;i++){ 
			buyGrids[i].registerCallbackForSchoolChange(recommendationsController.changeSchoolRecommendationTitles);
		}
	}
	
	var registerCallBackForSchoolSelectionUnset = function(selection) {
		for(var i = 0;i < buyGrids.length;i++){ 
			buyGrids[i].registerSchoolSelectionUnsetCallbacks(schoolSelectionUnset);
		}

	}	
	
	var schoolSelectionUnset = function(selection, schoolStoreNumQueryStringParam) {
		window.location = window.location.pathname + $.query.REMOVE(schoolStoreNumQueryStringParam);
	}
	
	var registerCallbackForStyleChange = function(){
		for(var i = 0;i < buyGrids.length;i++){ 
			buyGrids[i].registerCallbackForStyleChange(recommendationsController.loadRecommendationsForStyle);
		}
	}
	
	this.buildSelectionFromQueryString = function(product){
		var funcName = "[buildSelectionFromQueryString] ";
		
		// Create a brand new selection object to hold the modifications coming from the query string.
		var querySelection = new productViewNs.Selection();
		
		// Check the action query string parameter and make sure it is only order_more or modify

		var pageMode = $.query.value("action");
		if (pageMode == "order_more") {
			querySelection.mode = "add";
		}

		if (pageMode == "modify"){
			querySelection.itemId = $.query.value("itemId");
			querySelection.mode = "update";
		}
		if (pageMode == "order_more" || pageMode == "modify" || (product != null && 
								product != undefined && com.landsend.productView.GCConstants.GCProduct(product.getNumber()))){				
			// Parse and update the item number passed in (style number concatenated with media code and checkdigit ex 0347156A56).
			var querySku = $.query.value("sku_0").split(":");		    
			if (querySku[0] != null && querySku[0] != "") { 
				if (!com.landsend.productView.GCConstants.GCProduct(product.getNumber())) {
					var tempStyleStr = leutil.string.trimLeadingZeros(decodeURIComponent(querySku[0]));
					tempStyleStr = tempStyleStr.substring(0,tempStyleStr.length-3); //Pick up just the style number last three digits are media code followed by check digit.
				}
				else {
					tempStyleStr = querySku[0];
				}
				// Now figure out the style that this number corresponds to.
				var allFeatures = product.getAllFeatures();
				for (var i = 0;i < allFeatures.length; i++){		        
					var featStyle = allFeatures[i].getAssignedStyle();
					if (featStyle != null && featStyle != undefined){
						if (featStyle.getNumber() == tempStyleStr){
							querySelection.style = allFeatures[i].getAssignedStyle();
							break;
						}
					}
				}
				if (querySelection.style != null){
					$.debug(funcName+"Style number: " + querySelection.style.getNumber() + ' - ' + querySelection.style.getLongName());
				} else {
					$.debug(funcName+"Style number: NULL NULL");
				}
			}
			
			
			// Size Code
			if (querySku[1] != null && querySku[1] != "") {
				querySelection.sizeCode = decodeURIComponent(querySku[1]);
				$.debug(funcName+"Size code: " + querySelection.sizeCode);	
			}
			
			// Color code
			if (querySku[2] != null && querySku[2] != "") {
			    querySelection.colorCode = querySku[2];
			    $.debug(funcName+"Color code: " + querySelection.colorCode);
			}
		    
			// Inseam length 
			var queryInseam = $.query.value("inseamLength_0");
			if (queryInseam != null && queryInseam != "") {
			    querySelection.inseam = queryInseam;
			}
			$.debug(funcName+"Inseam: " + querySelection.inseam);
			

			// Cuffing.
			var queryCuffed = $.query.value("cuffed_0");			    
			if (queryCuffed != null && queryCuffed != "") {
			    if (parseInt(queryCuffed) === 1) {
			        queryCuffed = "cuffed";
			    } else if (parseInt(queryCuffed) === 0) {
			        queryCuffed = "uncuffed";
			    } else {
			        queryCuffed = "uncuffed";
			    }
			    querySelection.cuffing = queryCuffed;
			}
			$.debug(funcName+"Cuffed?" + querySelection.cuffing); 
		    
			// Quantity
			var queryQuantity = $.query.value("qty_0");		    
			if (queryQuantity != null && queryQuantity != "" && parseInt(queryQuantity) > 0) {
			    querySelection.quantity = parseInt(queryQuantity);
			    $.debug(funcName+"Quantity: " + querySelection.quantity);
			}			
		    
			// Monogramming basics
			var queryMonoTypeCode = $.query.value("monoTypeCode_0");		    
			if (queryMonoTypeCode != null && queryMonoTypeCode != "") {
			    querySelection.monogramApplied = true;
			    querySelection.monogramFont = queryMonoTypeCode;
			}
		    
			var queryMonoLoc = $.query.value("monoLoc_0");			    
			if (queryMonoLoc != null && queryMonoLoc != "") {
			    querySelection.monogramLocation = queryMonoLoc;
			    $.debug(funcName+"Monogram Location: " + querySelection.monogramLocation);
			}
		    
			var queryMonoValue = decodeURIComponent($.query.value("monoValue_0"));
			var queryMonoIsInitial = $.query.value("monoIsInitial_0");
			if (queryMonoValue != null && queryMonoValue != "") {
			    if (queryMonoIsInitial != null && queryMonoIsInitial != "" && queryMonoIsInitial == "1") {
			        // Three Initials
			        if (queryMonoValue.length > 1) {
			            querySelection.monogramType = 2; // Three Initials
			            querySelection.monogramMultiInitial[0] = queryMonoValue.charAt(0);
			            querySelection.monogramMultiInitial[1] = queryMonoValue.charAt(1);
			            querySelection.monogramMultiInitial[2] = queryMonoValue.charAt(2);
			            $.debug(funcName+"Multi Initials: " + querySelection.monogramMultiInitial.join(","));
			        } else {
			        	// Single Initial
			            querySelection.monogramType = 1; // Single Initial
			            querySelection.monogramSingleInitalText = queryMonoValue;
			            $.debug(funcName+"Singline Initial: " + querySelection.monogramSingleInitalText);
			        }
			    } else {
			        // Assume it's a name or word
			        querySelection.monogramType = 3; // Word
			        querySelection.monogramWordText = queryMonoValue;
			        $.debug(funcName+"Word Text: " + querySelection.monogramWordText);
			    }
			    
			    // Check for new line characters.  If they exist, it's a multi-line.
			    if (queryMonoValue.match(/\|/) != null) {
			        querySelection.monogramType = 4; // Multi-Line
			        querySelection.monogramMultiLine = queryMonoValue.split("|");
			        $.debug(funcName+"Multi Line: " + querySelection.monogramMultiLine.join(","));
			    }
			    
			    $.debug(funcName+"Monogram Type: " + querySelection.monogramType);		        
			}		    

			// School Uniform values       
			var schoolCode = $.query.value("schoolCode_0");
			var schoolLogo = $.query.value("schoolLogoCode_0");    
			
			if (schoolCode != null && schoolCode != "") {
			   querySelection.schoolNumber = schoolCode;
			}
			if (schoolCode != null && schoolCode != undefined && querySelection.monogramApplied){ 
				querySelection.schoolLogoCode = -2;
			} else if (schoolLogo != null && schoolLogo != ""){
				querySelection.schoolLogoCode = schoolLogo;
			}
		}

		return querySelection;
	}
	
	// This function builds the bread crumb from the cookies. But ONLY if the page request 
	// includes the parameter bcc=y on the query string AND there is at least 1 breadcrumb 
	// in the cookie.
	var buildBreadCrumb = function(){
	    var bcc = getQueryVariable("bcc");
	    var breadCrumbEle = document.getElementById("breadcrumbs");
	    var productAlternatesALink = document.getElementById("productAlternatesALink");
	    
	    if (bcc == "y" && breadCrumbEle != null && breadCrumbEle != undefined) {
	    	var bcString = "<a href='/'>Homepage</a> ";
		    var bcNumURLs = (getCookie("bcNumURLs") == null) ? 0 : getCookie("bcNumURLs");
		    var channel = getCookie("channel");
		    
		    if (bcNumURLs > 0) {
		    	bcString = bcString + "> ";
			    var i = 0;
			    var lastURL = bcNumURLs - 1;
			    var bcURL = null;
			    for (i = 0; i < bcNumURLs; i++) {
			       bcURL = decodeURIComponent(getCookie("bcURL_"+i));
			       var bcLinkText = decodeURIComponent(getCookie("bcLinkText_"+i));
			       bcString = bcString + "<a href=" + bcURL + ">" + bcLinkText + "</a>";
			       if (i != lastURL) {
			         bcString = bcString + "&nbsp;&gt;&nbsp;";
			       }
			    }
			    // Appended returnToMySchool div to display return to my school link in product page.
			    breadCrumbEle.innerHTML = bcString;// + "<div class=\"returnToSchool\" id=\"returnToMySchool\"></div>";

			    // collections don't have a product alternates link
			    if (productAlternatesALink) {
				    var queryOrigin = getQueryVariable("origin");
				    var productAlternateALinkText = "view similar items";
				    if(queryOrigin == "search"){
				    	productAlternateALinkText = "back to search results";
				    }else if(queryOrigin == "index"){
				    	productAlternateALinkText = "back to product category";
				    }
			    	productAlternatesALink.innerHTML = "<a href='" + bcURL + "'>" + productAlternateALinkText + "</a>"
			    }
			}
		
			if (channel !== null && channel != "") {
				doDebug("[buildBreadCrumb] s_omtr.channel = " + channel);
				s_omtr.channel = channel;
			}		
	    }
	}
	
	initialize();
}

com.landsend.productView.Selection = function(productNumber){
	this.productNumber = productNumber;
	this.mode = "add";
	this.itemId = null;
	this.style = null;
	this.styleNumber = null;
	this.primaryFeatureId = null;
	this.secondaryFeatureId = null;
	this.thirdFeatureId = null;
	this.colorCode = null;
	this.sizeCode = null;	
	this.sku = null;
	
	this.quantity = null;
	
	this.inseam = null;
	this.cuffing = null;
	
	this.monogramType = null;
	this.monogramFont = null;
	this.monogramLocation = null;
	this.monogramSingleInitalText  = null;
	this.monogramWordText = null;
	this.monogramMultiInitial = [];
	this.monogramMultiLine = [];
	this.threadColor = null;
	this.monogramApplied = false;
	
	this.schoolNumber = null;
	this.schoolLogoCode = null;
	
	//TODO: These two fields need to be cut out of the selection object, but since the add to bag uses these, I have left them in.
	//      We will need to do this when the new add to bag implementation is plugged in. 
	//      Talk to Sunitha/Scott if you have any questions.
	this.giftBox = false;
	this.giftBoxPrice = 0;
	
	this.dropShipDayPhone = null;
	this.dropShipDayPhoneExt = null;
	this.dropShipAltPhone = null;
	this.dropShipAltPhoneExt = null;
	
	this.personalizedRecipientEmail = null;
	this.personalizedTo = null;
	this.personalizedMessage = null;
	this.personalizedFrom = null;
	this.gcAmount = null;
}

com.landsend.productView.Messages = new function(){
	var Message = function(id,type,text){
		this.id = id;
		this.text = text;
		this.type = type; // 1 = error, 2 = warning, 3 = message
	}
	var message = new Array();
	message[0] = new Message(0,2,"<strong>ORDER TODAY!</strong> Estimated Ship Date ");
	message[1] = new Message(1,3,"<strong>UNAVAILABLE</strong>");	
	message[2] = new Message(2,1,"Please select a monogram type prior to continuing to step 2.");
	message[3] = new Message(3,1,"Please select a monogram style prior to continuing to step 3.");
	message[4] = new Message(4,1,"Please select a monogram location prior to continuing to step 3.");
	message[5] = new Message(5,1,"Please enter your monogram.");
	message[6] = new Message(6,1,"The monogram type you have selected requires a minimum of 2 characters. Please provide at least one more character. Or, if you want a single-initial monogram, please return to step 1 and select Single Initial");
	message[7] = new Message(7,1,"Please complete your monogram.");
	message[8] = new Message(8,1,"To add to your bag, you must first update (or cancel)  your monogram.  ");
	
	// Drop ship related error messages.
	message[9] = new Message(9,1,"Please enter a valid phone number.");
	message[10] = new Message(10, 1, "Please provide a day time phone number.");
	
	//Size related error message.
	message[13] = new Message(13,1,"Please select a size");
	message[15] = new Message(15,1,"Please select a waist measurement");
	message[16] = new Message(16,1,"We're sorry, this product is not available and cannot be added to your bag.");
	
	//Hemming related error message.
	message[14] = new Message(14,1,"Please select an inseam.");
	message[25] = new Message(25,1,"<h2>PLEASE NOTE</h2><p>Sorry, the maximum inseam length allowed with a cuff is ${minCuffingInseam} inches. (2 inches of fabric are required to make the cuff.)</p>");
	message[26] = new Message(26,3,"Sorry, the maximum inseam length allowed with a cuff is ${minCuffingInseam} inches. (2 inches of fabric are required to make the cuff.)");
	message[27] = new Message(27,3,"You must select an inseam before selecting a hemming option.");	
	
	message[18] = new Message(18,1,"<h2 class='le-modal-focus'>We're sorry.</h2><p>Due to system limitations, we cannot process requests for both a monogram and a school logo online. To order both, select your logo only and complete your order. Then call 1.800.469.2222 to add monogram.</p><p class='le-modal-controls'><a href='#' class='pp-generic-button le-modal-alternate-close'>OK</a></p>");
	message[28] = new Message(28,1,"Due to system limitations, we cannot process requests for both a monogram and a school logo online. To order both, select your logo only and complete your order. Then call 1.800.469.2222 to add monogram.");
	message[19] = new Message(19,1,"The Preferred School Number is incorrect or invalid. Please verify it and re-enter or call 1.800.469.2222 for assistance.");
	message[20] = new Message(20,1,"Please select a logo preference.");
	message[21] = new Message(21,1,"Your school's dress code requires a monogram on this item. Please complete your monogram.");
	
	message[22] = new Message(22,1,"Cookies must be enabled to fully interact with our site. To enable cookies, please adjust the security or privacy settings for your browser. <a href=\' /cd/landing/0,,newCoidInd=y:copyName=sorry_cookies,00.html \' style=\'color:#CC0000;font-weight:bold;\'>learn more</a>");
	message[23] = new Message(23,1,"<h2 class='le-modal-focus'>We're sorry.</h2><p>Monogram options may vary depending on product size range. To add a monogram to this product, you must re-select your monogram choices. We apologize for the inconvenience.</p><p class='le-modal-controls'><a href='#' class='pp-generic-button le-modal-alternate-close'>OK</a></p>");
	message[24] = new Message(24,1,"<h2 class='le-modal-focus'>We're sorry.</h2><p>Monogramming is not available for this style.</p><p class='le-modal-controls'><a href='#' class='pp-generic-button le-modal-alternate-close'>OK</a></p>");

	message[29] = new Message(29,1,"<h2 class='le-modal-focus'>We're sorry.</h2><p>We are currently experiencing technical issues with this area of our site. For immediate assistance, try Get Live Help for a chat or call 1-800-963-4816.</p><p class='le-modal-controls'><a href='#' class='pp-generic-button le-modal-alternate-close'>OK</a></p>");
	message[30] = new Message(30,2,"This image is not available in the selected color.");
	message[31] = new Message(31,1,"Please provide a recipient's email address.");
	message[32] = new Message(32,1,"$5 minimum, $500 maximum");
	message[33] = new Message(33,1,"Please provide a valid recipient's email address.");
	message[34] = new Message(34,1,"You have exceeded the limit of 3 lines.");

	
	this.findMessage = function(id){
		var messageLu = message[id];
		if(messageLu != null || messageLu != undefined){
			return new Message(messageLu.id,messageLu.type,messageLu.text);
		}
		return null;
	}
}

//$.jsNamespace('com.landsend.productView');
var com;
if(com == undefined){
	com = new Object();
}
if(com.landsend == undefined){
	com.landsend = new Object();
}
if(com.landsend.productView == undefined){
	com.landsend.productView = new Object();
}

com.landsend.productView.RecommendationsView = function(){
	var carousels = [];
	var totalTries = 0;
	
	this.redrawCarousel = function(recBoxNumber){
		var action = $.query.get("action");
		if (action != "modify") {
			var carouselDivId = "pp_product_recbox" + recBoxNumber;		
			carousels[carouselDivId] = new leutil.ui.Carousel($('#' + carouselDivId));
			if ($("#pp_product_recbox" + recBoxNumber).children(".images_container").children("a").length == 0){
				$('#pp_product_recbox' + recBoxNumber + '_heading').css('visibility', 'hidden');
			}
		}
	}
	
	this.changeRecommendationHeadingsForSchool = function(){
		changeHeading('pp_product_recbox1_heading', 'YOU MIGHT ALSO LIKE (not Dress Code specific)');
	}
	
	this.registerPopEvent = function() {
	//	$("#product_rr1").children("a").bind("click", qvLaunch);
	}
	
	var qvLaunch = function(event) {
		var href = $(this).attr("href");
		var temppos = href.indexOf("StylePage-");
		var temphtmlpos = href.indexOf(".html");
		var temp1 = null;
		var cmMerch = getCMMerchVal(href);
		if (temppos == -1) {
			temppos = href.indexOf("~");
			var prodId = href.substring(temppos+1, temphtmlpos);
			temp1 = prodId.indexOf("_");
			var productNumber = prodId.substr(0,temp1);
			com.landsend.quickViewService.getQuickView(productNumber,null,cmMerch, null, quickViewCallback);	
			//com.landsend.quickViewService.getProductForQuickView('P', productNumber, null, null, null, cmMerch);			
		}
		else {
			var styleMedia = href.substring(temppos, temphtmlpos);
			temp1 = styleMedia.indexOf("_");
			var styleNumber = styleMedia.substring(10,temp1);
			var mediaCode = styleMedia.substr(temp1+1);
			com.landsend.quickViewService.getQuickViewForStyle(styleNumber,mediaCode,cmMerch, null, quickViewCallback);
			//com.landsend.quickViewService.getProductForQuickView('S', null, null,styleNumber,mediaCode, cmMerch);
		}
		event.preventDefault();
	}
	
	var getCMMerchVal = function(hrefVal) {
		var temp1 = hrefVal.indexOf("CM_MERCH=");
		if (temp1 == -1) {
			return null;
		}
		else {
			var temp2 = hrefVal.indexOf("&", temp1);
			if (temp2 == -1) {
				return hrefVal.substr(temp1 + 9);
			}
			else {
				return hrefVal.substring(temp1 + 10, temp2);
			}
		}
	}
	
	var changeHeading = function(divId, headingText){
		$('#'+ divId).text(headingText);
	}	
}


com.landsend.productView.RecommendationsController = function(){
	var numRecommendations = 20;
	var prodViewNs = com.landsend.productView;
	var recommendationsView = null;
	
	this.init = function(product){	
		recommendationsView = new prodViewNs.RecommendationsView();
		var modifyMode = $.query.get('action');
		if (($.cookie('schoolNumber') != null || $.cookie('customSchoolNumber') != null)
				&& product.getMediacode().getInternetComponentTypeCode() == 3 ){
			recommendationsView.changeRecommendationHeadingsForSchool();
		}		
		
	}
	
	this.registerPopEvent = function() {
		recommendationsView.registerPopEvent();
	}
	
	this.changeSchoolRecommendationTitles = function(product, style){
		if (product.getMediacode().getInternetComponentTypeCode() == 3) {
			recommendationsView.changeRecommendationHeadingsForSchool();
		}
	}
	
	this.notifyStyleView = function(product, style){		
		var funcName = "[notifyStyleView on style = " + style.getNumber() + "] ";
		try{
			if (!metric.certonaActive){				
				$.debug(funcName + 'Certona is not active on the site. So doing nothing.');
				return;
			}
			var mediaCodeToUse = style.getCatalogNumber().getMediaCode().getMediaCodeId();
		    var catStr = style.getNumber() + ":" + mediaCodeToUse;
		    $.debug(funcName + "Certona Product Id : " + catStr);
	
		    var resTrackingGID = $.cookie("RES_TRACKINGID");
			$.debug(funcName + "Resonsance Tracking GID " + resTrackingGID);
			
	  		resWebServiceURL =  "/ws/r2/Resonance.aspx?appid=landsend01&userid=" + resTrackingGID + "&event=product&itemid=" +  catStr + "&scheme=product_rr1&number=0&" + resx.rrqs;
	        	  		
			$.debug(funcName + "Certona Web Service URL " + resWebServiceURL);
	
			$.ajax({url:resWebServiceURL,
					type:"GET",
					dataType:"html",
					timeout:10000,
					error:function(ajaxReq, textStatus)
					{
						$.debug(funcName + "*******************************************************************");
						$.debug(funcName + "Error on Certona Web Service call.");
						$.debug(funcName + "URL: " + resWebServiceURL);
						$.debug(funcName + "Error status : " + ajaxReq.status + ' - ' + textStatus);
						$.debug(funcName + "*******************************************************************");	
					},
					success:function(recResponse)
					{
						$.debug(funcName + "Successfully received a response from the Certona Web Service call.");
					}
			});
		}
		catch(error){
			// We do not want this to stop the user from ordering/modifying items, so write something to the debug window and move on.
    		$.debug(funcName + "Error when requesting recommendations from Certona ");
    		$.debug(funcName + error.code + ' ' + error.message);
		}
	}
	
	
	// called any time the style on the view has changed
	this.loadRecommendationsForStyle = function(product, style){
		var funcName = 'loadRecommendationsForStyle ';
		if (!metric.certonaActive){
			$.debug(funcName + 'Certona is not active on the site. So doing nothing.');
			return;
		}
		loadRecommendations(1, product, style);    //You might also like
	}
	
	var loadRecommendations = function(boxNumber, product, style){
		var recommendationScheme = "product_rr" + boxNumber;
		try
    	{
    		var funcName = "[loadRecommendations scheme = " + recommendationScheme + "] ";
    		if (resx.top1 == 0 || !metric.certonaActive)
    		{
    			$.debug(funcName + "***************************************************************************************************");
    			$.debug(funcName + "Not making an AJAX call as we are in A/B Test Group that does not display Certona Recommendations");
    			$.debug(funcName + "***************************************************************************************************");
    		}
    		else
    		{
    			var mediaCodeToUse = style.getCatalogNumber().getMediaCode().getMediaCodeId();
	    		var customSchoolNum = $.cookie("customSchoolNumber");	    		

	    		// If we are in a custom school, we use the core full price media code, so that the recommendations
	    		// bring up the core page (school number entry is not required on the core media product page).
	    		// Styles are dual listed under the core and school media codes.
	    		if(customSchoolNum != null && customSchoolNum != "")
	    		{
	    			mediaCodeToUse = com.landsend.global.PageConfigParms.CORE_FULLPRICE_MEDIA_CODE;	    			
	    		}
	    	    var catStr = style.getNumber() + ":" + mediaCodeToUse;
	    	    $.debug(funcName + "Certona Product Id : " + catStr);
	    		var resTrackingGID = $.cookie("RES_TRACKINGID");
	    		$.debug(funcName + "Resonsance Tracking GID " + resTrackingGID);
	    		var resWebServiceURL = "";
	    		
	    		var action = $.query.get("action");
		  		if (action == "modify") {
		  			$.debug(funcName + "Not requesting recommendations at this time (we are in the modify item flow), this will be notification that the user viewed this style.");
		  			resWebServiceURL =  "/ws/r2/Resonance.aspx?appid=landsend01&userid=" + resTrackingGID + "&event=product&itemid=" +  catStr + "&scheme=" + recommendationScheme + "&number=0&" + resx.rrqs;
		        }
		  		else{
		  			resWebServiceURL =  "/ws/r2/Resonance.aspx?appid=landsend01&userid=" + resTrackingGID + "&event=product&itemid=" +  catStr + "&scheme=" + recommendationScheme + "&number=" + numRecommendations + "&" + resx.rrqs;
		  		}
		  			
	    		$.debug(funcName + "Certona Web Service URL " + resWebServiceURL);

	   			$.ajax({url:resWebServiceURL,
					type:"GET",
					dataType:"html",
					timeout:10000,
					error:function(ajaxReq, textStatus)
					{
    					$.debug(funcName + "*******************************************************************");
    					$.debug(funcName + "Error on Certona Web Service call.");
    					$.debug(funcName + "URL: " + resWebServiceURL);
    					$.debug(funcName + "Error status : " + ajaxReq.status + ' - ' + textStatus);
    					$.debug(funcName + "*******************************************************************");
    					recommendationsView.redrawCarousel(boxNumber);
					},
					success:function(recResponse)
					{
						$.debug(funcName + "Successfully received a response from the Certona Web Service call.");
		    			$("#" + recommendationScheme).html(recResponse);
		    			recommendationsView.redrawCarousel(boxNumber);
		    			recommendationsView.registerPopEvent();
					}
	   			});
    		}
    	}catch(error)
        {
    		// We do not want this to stop the user from ordering/modifying items, so write something to the debug window and move on.
    		$.debug(funcName + "Error when requesting recommendations from Certona ");
    		$.debug(funcName + error.code + ' ' + error.message);
        }
    }
}

//$.jsNamespace('com.landsend.productView');
var com;
if(com == undefined){
	com = new Object();
}
if(com.landsend == undefined){
	com.landsend = new Object();
}
if(com.landsend.productView == undefined){
	com.landsend.productView = new Object();
}

com.landsend.productView.FullScreenPhotoView = function(display, styleOrPrdtNum, mode){
	var styleOrProductNumber = styleOrPrdtNum;
	var viewerMode = mode;
	var fullScreenPhotoDisplay = display;
	
	this.registerColorSelectors = function(colorCode){
		$.debug("FullScreenPhotoView.registerColorSelectors Registering selector for color code " + colorCode);
		$('#swatchImage_' + styleOrProductNumber + '_' + viewerMode + '_' + colorCode).bind('click', selectColor);
	}
	
	var selectColor = function(event){		
		var ids = this.id.split('_').slice(3);
		$.debug("FullScreenPhotoView.selectColor Selection event for color code " + ids[0]);
		fullScreenPhotoDisplay.colorSelect(ids[0]);		
		event.preventDefault();
	}	
	
	this.highLightSelectedSwatch = function(colorCode){
		$.debug("FullScreenPhotoView.highLightSelectedSwatch Highlight swatch for color code " + colorCode);
		$('#colorChooser_' + styleOrProductNumber + '_' + viewerMode + ' ul li a').attr("class", " ");
		$('#swatchImage_' + styleOrProductNumber + '_' + viewerMode + '_' + colorCode).attr("class", "pp-selected");
		window.swatchSelector.hilight(styleOrProductNumber,"","fullscreen");
	}
}

com.landsend.productView.FullScreenPhotoDisplay = function(){
	var thisFullScreenDisplay = this;
	var fullScreenView = null;
	var photoDisplay = null;
		
	var viewerMode = 'FULLSCREEN';
	var fullScreenStyleNumber = null;
	var fullScreenImageSetCollection = null;
	var fullScreenSwatchList = null;
	var fullScreenColorCodeSelection = null;
	var fullScreenImageSetPosition = 0;
	var fullScreenColorsByPriceCodeBean = null;
	var colorChangeNotificationOnExitCallback = null;
	var lastImageSetIsSwatch = true;
	
	this.launchFullScreenViewer = function(styleNumber, imageSetCollection, swatchList, colorsByPriceCodeBean, clrCode, pos, colorChangeOnExitCallback, lastImageSetIsSwatch ){
		$.debug("FullScreenPhotoDisplay.launchFullScreenViewer Color Code=" + clrCode + " Image Set position=" + pos);
		fullScreenStyleNumber = styleNumber;
		fullScreenImageSetCollection = imageSetCollection;
		fullScreenSwatchList = swatchList;		
		fullScreenColorCodeSelection = clrCode;
		fullScreenImageSetPosition = pos;
		fullScreenColorsByPriceCodeBean = colorsByPriceCodeBean;
		colorChangeNotificationOnExitCallback = colorChangeOnExitCallback;
		$.debug("FullScreenPhotoDisplay.launchFullScreenViewer calling modal.fullScreen");
		
		leutil.ui.modalHandler.show({
			content: buildFullScreenUI(styleNumber, imageSetCollection, swatchList, colorsByPriceCodeBean, clrCode, pos, lastImageSetIsSwatch),
			cssClass: "le-modal-full-screen",
			onShow: modalWindowOnShow,
			onHide: modalWindowOnHide,
			fullscreen: true
		});
	}
	
	var modalWindowOnShow = function(){
		$.debug("FullScreenPhotoDisplay.modalWindowOnShow");
		init(fullScreenStyleNumber, fullScreenImageSetCollection, fullScreenSwatchList, fullScreenColorsByPriceCodeBean, fullScreenColorCodeSelection, fullScreenImageSetPosition);		
		photoDisplay.show();
		if (fullScreenSwatchList != null && fullScreenSwatchList.length > 0) {fullScreenView.highLightSelectedSwatch(fullScreenColorCodeSelection);}
	}
	var modalWindowOnHide = function(){
		$.debug("FullScreenPhotoDisplay.modalWindowOnHide");
		if (colorChangeNotificationOnExitCallback != null) {colorChangeNotificationOnExitCallback.call(this, fullScreenColorCodeSelection);}
		photoDisplay = null; fullScreenView = null; fullScreenImageSetCollection = null; fullScreenSwatchList = null; fullScreenColorCodeSelection = null; 
		fullScreenImageSetPosition = null; colorChangeNotificationOnExitCallback = null;
	}
	
	var init = function(styleNumber, imageSetCollection, swatchList, colorsByPriceCodeBean, colorCode, imageSetPosition){
		$.debug("FullScreenPhotoDisplay.init initializing the full screen photo viewer " + styleNumber + " color " + colorCode);
		fullScreenView = new com.landsend.productView.FullScreenPhotoView(thisFullScreenDisplay, styleNumber, viewerMode);
		photoDisplay = new com.landsend.productView.PhotoDisplay();
		photoDisplay.init(styleNumber, null, imageSetCollection, swatchList, false, colorCode, imageSetPosition, viewerMode);
		if (colorsByPriceCodeBean != null) {registerEvents(colorsByPriceCodeBean);}
	}
	
	this.colorSelect = function(clrCode){
		$.debug("FullScreenPhotoDisplay.colorSelect color selection " + clrCode);
		fullScreenColorCodeSelection = clrCode;
		$.debug("FullScreenPhotoDisplay.colorSelect making viewer selections for color " + clrCode);
		photoDisplay.setPhotoViewerColorCode(clrCode);
		setTimeout(photoDisplay.updateViewerColor, 1000);
		fullScreenView.highLightSelectedSwatch(clrCode);
	}
	
	this.registerForColorChangeNotificationOnExit = function(callback){
		$.debug("FullScreenPhotoDisplay.registerForColorChangeNotificationOnExit registering for color change notification on exit ");
		colorChangeNotificationOnExitCallback = callback;
	}

	
	var registerEvents = function(colorsByPriceCodeBean){
		$.debug("FullScreenPhotoDisplay.registerEvents for fullscreen viewer.");
		for (var s = 0; s < colorsByPriceCodeBean.getRegularPriceColors().length; s++) {
			var swatch = colorsByPriceCodeBean.getRegularPriceColors()[s];
			fullScreenView.registerColorSelectors(swatch.getColor().getCode());
		}
		
		for (var s = 0; s < colorsByPriceCodeBean.getReducedPriceColors().length; s++) {
			var swatch = colorsByPriceCodeBean.getReducedPriceColors()[s];
			fullScreenView.registerColorSelectors(swatch.getColor().getCode());
		}
		
		for (var s = 0; s < colorsByPriceCodeBean.getClearancePriceColors().length; s++) {
			var swatch = colorsByPriceCodeBean.getClearancePriceColors()[s];
			fullScreenView.registerColorSelectors(swatch.getColor().getCode());
		}
	}	
	
	var buildFullScreenUI = function(styleNumber, imageSetCollection, swatchList, colorsByPriceCodeBean, colorCode, imagePos, lastImageSetIsSwatch){
		$.debug("FullScreenPhotoDisplay.buildFullScreenUI building UI for viewer " + styleNumber  + " color " + colorCode);
		var height = $(window).height()-110;			
		var width = Math.ceil(height*.67);
		if($(window).width()-330 > width){
			width = $(window).width()-330;
		}
		
		var htmlString = '';		
		htmlString = htmlString + '<div id="imageViewer_' + styleNumber + '_' + viewerMode + '" style="display:block;visibility:visible;">';
		htmlString = htmlString + '<style type="text/css">';
		htmlString = htmlString + '.pp-fullscreen-image-viewer-column{ width:'+(width+80)+'px; float:left; padding-right:20px;}';
		htmlString = htmlString + '.pp-fullscreen-image-viewer-wrapper{width:'+(width)+'px; height:'+height+'px;}';
		htmlString = htmlString + '</style>';
		htmlString = htmlString + '<div class="pp-fullscreen-image-viewer-column">';
		htmlString = htmlString + '<!-- START OF ALTERNATE IMAGES SECTION -->';
		htmlString = htmlString + '<ul class="pp-image-viewer-gallery">'
		var position = 0;
		var altImageQryStr = '?' + com.landsend.global.PageConfigParms.PRODUCT_PAGE_ALT_IMAGE_PRESET;
		var altSwatchQryStr = '?' + com.landsend.global.PageConfigParms.PRODUCT_PAGE_ALT_SWATCH_PRESET;
		for (var j=0; ((position<5) && (j<imageSetCollection.getImageSetList().length)); j++) {
			if (lastImageSetIsSwatch == true && position == 4 && imageSetCollection.getImageSetList().length > 5 && imageSetCollection.getImageSetList()[j].getSwatch() == false) {
				continue;
			}
			if (imageSetCollection.getImageSetList()[j].getProductImageList().length < 1) {
				continue;
			}
			var imgAltAttribute = "Lands' End Product Image";
			// Find the image for the passed in color, if that does not exist then default to the first image in that image set.
			var img = null;
			var isImgASwatch = false;
			var imageList = imageSetCollection.getImageSetList()[j].getProductImageList();
			for(var il=0; il < imageList.length; il++){
				if (imageList[il].getColor().getCode() == colorCode){
					img = imageList[il]; 
					isImgASwatch = imageSetCollection.getImageSetList()[j].getSwatch();
					break;
				}
			}
			if (img == null){
				img = imageSetCollection.getImageSetList()[j].getProductImageList()[0];
				isImgASwatch = imageSetCollection.getImageSetList()[j].getSwatch();
			}			
			if (imageSetCollection.getImageSetList()[j].getSwatch()) {
				imgAltAttribute = img.getColor().getName();							
			}
			htmlString = htmlString + '<li>';
			htmlString = htmlString + '<a href="#" id="altImage_' + j + '_' + styleNumber + '_' + viewerMode + '" onclick="return false;">';
			if (img.getImageServed() == true){
				if (isImgASwatch){					
					htmlString = htmlString + '<img src="' + window.location.protocol + '//s7.landsend.com' +  img.getUrl() + altSwatchQryStr +'" title="' + imgAltAttribute + '" alt="' + imgAltAttribute + '"/>';
				} else {
					htmlString = htmlString + '<img src="' + window.location.protocol + '//s7.landsend.com' +  img.getUrl() + altImageQryStr + '" title="' + imgAltAttribute + '" alt="' + imgAltAttribute + '"/>';
				}
			} else {
				htmlString = htmlString + '<img src="' + img.getUrl() + '" title="' + imgAltAttribute + '" alt="' + imgAltAttribute + '"/>';
			}
			htmlString = htmlString + '</a>';
			htmlString = htmlString + '</li>';
			position = position + 1;
			$.debug("FullScreenPhotoDisplay.buildFullScreenUI showing alternate image " + img.getUrl()); 
		}
		htmlString = htmlString + '</ul>';
		htmlString = htmlString + '<!-- END OF ALTERNATE IMAGES SECTION -->';
		htmlString = htmlString + '<div class="pp-fullscreen-image-viewer-wrapper">';
		htmlString = htmlString + '<div id="photoViewer_' + styleNumber + '_' + viewerMode + '" style="float:left;width:'+width+'px; height:'+height+'px;display:block;">';
		htmlString = htmlString + '</div>';
		htmlString = htmlString + '<div class="pp-photo-viewer-alert-wrapper">';
		htmlString = htmlString + '<div id="photoViewerAlert_' + styleNumber + '_' + viewerMode + '" class="pp-photo-viewer-alert pp-hide">';
		htmlString = htmlString + '<div id="alertText_' + styleNumber + '_' + viewerMode + '"></div>';
		htmlString = htmlString + '</div>';
		htmlString = htmlString + '</div>';
		htmlString = htmlString + '</div>';			
		htmlString = htmlString + '</div>';
		
		// Now add the color chips into the mix if the style has color swatches.
		if (swatchList != null && swatchList.length > 0 && colorsByPriceCodeBean != null) {
			htmlString = htmlString + '<h2 class="pp-selector-label">';
			htmlString = htmlString + 'Color'; 
			htmlString = htmlString + '</h2>';
			
			htmlString = htmlString + '<div id="colorChooser_' + styleNumber + '_' + viewerMode + '" class="pp-selector pp-swatch-selector" style="float:left;">';
			htmlString = htmlString + '<div class="pp-swatch-hilight"></div>';
			htmlString = htmlString + '<ul>';
			
			if (colorsByPriceCodeBean != null && colorsByPriceCodeBean.getRegularPriceColors().length > 0){				
		        htmlString = htmlString + '<ul>';
				for (var s = 0; s < colorsByPriceCodeBean.getRegularPriceColors().length; s++) {				
					var swatch = colorsByPriceCodeBean.getRegularPriceColors()[s];
					htmlString = htmlString + '<li><a id="swatchImage_' + styleNumber + '_' + viewerMode + '_' + swatch.getColor().getCode() + '" href="#" style="background-color:#; background-image:url(' + swatch.getUrl() + ');">';
					htmlString = htmlString + '<span>' + swatch.getColor().getName() + '</span>';
					htmlString = htmlString + '<span class="pp-swatch-available"></span>';												
					htmlString = htmlString + '</a></li>';
					$.debug("FullScreenPhotoDisplay.buildFullScreenUI Adding Regular price color chip " + swatch.getColor().getCode() + "(" + swatch.getColor().getName() + ")");
				}
		        htmlString = htmlString + '</ul>';
		        htmlString = htmlString + '<div class="clear-float"></div>';
			}
						
			if (colorsByPriceCodeBean != null && colorsByPriceCodeBean.getReducedPriceColors().length > 0){
				htmlString = htmlString + '<p>Reduced Price</p>';
		        htmlString = htmlString + '<ul>';
				for (var s = 0; s < colorsByPriceCodeBean.getReducedPriceColors().length; s++) {
					var swatch = colorsByPriceCodeBean.getReducedPriceColors()[s];
					htmlString = htmlString + '<li><a id="swatchImage_' + styleNumber + '_' + viewerMode + '_' + swatch.getColor().getCode() + '" href="#" style="background-color:#; background-image:url(' + swatch.getUrl() + ');">';
					htmlString = htmlString + '<span>' + swatch.getColor().getName() + '</span>';
					htmlString = htmlString + '<span class="pp-swatch-available"></span>';												
					htmlString = htmlString + '</a></li>';
					$.debug("FullScreenPhotoDisplay.buildFullScreenUI Adding Reduced price color chip " + swatch.getColor().getCode + "(" + swatch.getColor().getName() + ")");
				}
		        htmlString = htmlString + '</ul>';
		        htmlString = htmlString + '<div class="clear-float"></div>';
			}
			
			if (colorsByPriceCodeBean != null && colorsByPriceCodeBean.getClearancePriceColors().length > 0){
				htmlString = htmlString + '<p>Clearance Price</p>';
		        htmlString = htmlString + '<ul>';
				for (var s = 0; s < colorsByPriceCodeBean.getClearancePriceColors().length; s++) {
					var swatch = colorsByPriceCodeBean.getClearancePriceColors()[s];
					htmlString = htmlString + '<li><a id="swatchImage_' + styleNumber + '_' + viewerMode + '_' + swatch.getColor().getCode() + '" href="#" style="background-color:#; background-image:url(' + swatch.getUrl() + ');">';
					htmlString = htmlString + '<span>' + swatch.getColor().getName() + '</span>';
					htmlString = htmlString + '<span class="pp-swatch-available"></span>';												
					htmlString = htmlString + '</a></li>';
					$.debug("FullScreenPhotoDisplay.buildFullScreenUI Adding Clearance price color chip " + swatch.getColor().getCode + "(" + swatch.getColor().getName() + ")");
				}
		        htmlString = htmlString + '</ul>';
		        htmlString = htmlString + '<div class="clear-float"></div>';
			}	
			htmlString = htmlString + '</div>';
		}
		
		htmlString = htmlString + '<div class="pp-photo-viewer-controls-wrapper">';
		htmlString = htmlString + '<ul id="photoViewerButtons_' + styleNumber + '_' + viewerMode + '" class="pp-photo-viewer-controls">';	
		htmlString = htmlString + '<li><a id="inButton_' + styleNumber + '_' + viewerMode + '" class="pp-photo-viewer-zoom-in">Zoom In</a></li>';
		htmlString = htmlString + '<li><a id="outButton_' + styleNumber + '_' + viewerMode + '" class="pp-photo-viewer-zoom-out-inactive">Zoom Out</a></li>';
		htmlString = htmlString + '<li><a id="fullButton_' + styleNumber + '_' + viewerMode + '" class="pp-photo-viewer-reset-inactive">Reset Display</a></li>';
		htmlString = htmlString + '<li><a id="exitButton_' + styleNumber + '_' + viewerMode + '" class="pp-photo-viewer-exit le-modal-alternate-close">Exit Fullscreen</a></li>';
		htmlString = htmlString + '</ul>';
		htmlString = htmlString + '</div>';
		
		htmlString = htmlString + '</div>';	
		$.debug("FullScreenPhotoDisplay.buildFullScreenUI Completed building UI for viewer " + styleNumber  + " color " + colorCode);
		return htmlString;
	}
}

com.landsend.productView.PhotoView = function(viewerDisplay, productNum, styleNum, mode){
	
	var photoViewer = null;
	var photoViewerDisplay = viewerDisplay;
	var productNumber = productNum;
	var styleNumber = styleNum;
	var viewerMode = mode;
	var viewerKeySuffix = (productNumber != undefined && productNumber != null ? productNumber + "_" : "") + 
	                      (styleNumber != undefined && styleNumber != null ? styleNumber + "_" : "") + viewerMode;

	var s7BasePath = window.location.protocol  + '//s7.landsend.com';
	var s7BaseImagePath = s7BasePath + '/is/image/LandsEnd/';
	var sj_codebase = window.location.protocol  + "//s7.landsend.com/is-viewers/dhtml/";		

	var css = {
		imageViewer : {
	        inButtonActive              : "pp-photo-viewer-zoom-in",
	        inButtonInactive            : "pp-photo-viewer-zoom-in-inactive",
	        outButtonActive             : "pp-photo-viewer-zoom-out",
	        outButtonInactive           : "pp-photo-viewer-zoom-out-inactive",
	        fullButtonActive            : "pp-photo-viewer-reset",
	        fullButtonInactive          : "pp-photo-viewer-reset-inactive",
	        showAlert                   : "pp-photo-viewer-alert",
	        hideAlert                   : "pp-hide",
	        fullScreenButtonActive      : "pp-photo-viewer-fullscreen"
	    	}
	};
	
	this.init = function(defaultImageName, width, height){
		$.debug("PhotoView.init Initializing the photo viewe for product " + productNumber + ' style ' + styleNumber +  " with default image " + defaultImageName);
		this.show();
		$.debug("PhotoView.init Creating the s7 photo viewer product " + productNumber + ' style ' + styleNumber);  
		photoViewer = createPhotoViewer(defaultImageName, width, height, 'photoViewer_' + viewerKeySuffix);
		photoViewer.initZoomControls();
		this.hide();				
		$.debug("PhotoView.init Completed initialization for product " + productNumber + ' style ' + styleNumber);
	}
	       	
	this.registerAlternateImageSelector = function(imagePosition){
		$.debug("PhotoView.registerPhotoViewerSelector Registering photo viewer alternate image selector for image at " + imagePosition + " for product " + productNumber + ' style ' + styleNumber);
		$("#" + "altImage_" + imagePosition + '_' + viewerKeySuffix + ' img').bind('click', this.selectAlternateImage);
	}
			
	this.selectAlternateImage = function(e){
		e.preventDefault();
		var ids = this.parentNode.id.split('_');
		var imageSetNumber = ids[1];
		var styleid = ids[2];
		$.debug("PhotoView.selectAlternateImage selected alternate image at " + imageSetNumber + " for style " + styleid);
		viewerDisplay.alternateImageSelect(imageSetNumber);
	}
	
	this.show = function(){
		$.debug("PhotoView.show viewer for product " + productNumber + "_" + styleNumber);
		$("#" + "imageViewer_" + viewerKeySuffix).css('visibility', 'visible');
		$("#" + "imageViewer_" + viewerKeySuffix).css('display', 'block');
	}
	
	this.hide = function()
	{
		$.debug("PhotoView.hide viewer for viewer product " + productNumber + "_" + styleNumber + "_" + viewerMode);
		$("#" + "imageViewer_" + viewerKeySuffix).css('visibility', 'hidden');
		$("#" + "imageViewer_" + viewerKeySuffix).css('display', 'none');
	}	
	
	this.resetViewer = function(){
		$.debug("PhotoView.resetviewer for product " + productNumber + "_" + styleNumber);
		photoViewer.reset();
	}
	
	this.showViewerImage = function(imageName, width, height, imageServed){
		$.debug("PhotoView.showViewerImage for product " + productNumber + "_" + styleNumber + " image '" + imageName + "' width/height" + width + "/" + height);
		if (imageServed === true){
			photoViewer.changeImage(s7BasePath + imageName, width, height);
		} else {
			photoViewer.changeImage(imageName, width, height);
		}
		
	}
	
	this.showAlternateImage = function(styleid, imageSetNumber, imageName, imageServedFromS7, altImageText, isImageASwatch){
		$.debug("PhotoView.showAlternateImage for viewer image set number " + imageSetNumber + " image name " + imageName);
		var altImageThumb = $('#altImage_' + imageSetNumber + '_' + viewerKeySuffix + ' img');		
		if (altImageText == null){
			altImageText = altImageThumb.attr("alt");
		}
		if (imageServedFromS7 === true){
			if (isImageASwatch){				
				var qryStr = '?' + com.landsend.global.PageConfigParms.PRODUCT_PAGE_ALT_SWATCH_COLUMN_LAYOUT_PRESET;
			} else {
				var qryStr = '?' + com.landsend.global.PageConfigParms.PRODUCT_PAGE_ALT_IMAGE_COLUMN_LAYOUT_PRESET;
			}
			if (altImageThumb.hasClass("default"))
			{
				if (isImageASwatch){				
					var qryStr = '?' + com.landsend.global.PageConfigParms.PRODUCT_PAGE_ALT_SWATCH_PRESET;
				} else {
					var qryStr = '?' + com.landsend.global.PageConfigParms.PRODUCT_PAGE_ALT_IMAGE_PRESET;
				}
			}
			altImageThumb.attr({src: s7BasePath + imageName + qryStr, alt: altImageText, title: altImageText});
		} else {
			altImageThumb.attr({src: imageName, alt: altImageText, title: altImageText});
		}
		
	}
	
	this.showLegacyImage = function(imageName, height, imageServedFromS7){
 		if(imageServedFromS7 == true){
 			$.debug("PhotoView.showLegacyImage for product " + productNumber + "_" + styleNumber + " image name '" + (s7BasePath + imageName) + "' height " + height + " imageServedFrom s7 " + imageServedFromS7);
			$('#' + "legacyImage_" + viewerKeySuffix).attr({ src: s7BasePath + imageName +"?hei=" + height});
		}else{
			$.debug("PhotoView.showLegacyImage for product " + productNumber + "_" + styleNumber + " image name '" + (imageName) + "' height " + height + " imageServedFrom s7 " + imageServedFromS7);
			$('#' + "legacyImage_" + viewerKeySuffix).attr({ src: imageName +"?hei="+height});
		}
	}
	
	this.showColorAlert = function(colorName)
	{
		$.debug("PhotoView.showColorAlert showing color alert for product " + productNumber + "_" + styleNumber + " color code of " + colorName);
		photoViewer.showColorAlert(colorName);
	}
	
	var createPhotoViewer = function(imageName, width, height, inViewId) {
		$.debug("PhotoView.createPhotoViewer creating photo viewer for image '" + imageName + "' width/height " + width + "/" + height + " inside div " + inViewId);
		$.debug("PhotoView.createPhotoViewer InViewId exists ? " + $("#" + inViewId).length);
		var s7zoom = new SjZViewer(window.location.protocol + "//s7.landsend.com/is/image/LandsEnd/", imageName + "?op_sharpen=1",  null, null, null, null, null, null, inViewId, null, null);

		s7zoom.setZoomStep(1);
		s7zoom.setMaxZoom(100);
		s7zoom.instructionsDisplayed = true;
		s7zoom.displayingSwatch = false;
		s7zoom.scale = 1;
 
		s7zoom.onEvent.onImageZoomedOut = function(x) {
			
			s7zoom.zoomInButton.className = css.imageViewer.inButtonActive;
			if (x == 1) {
				s7zoom.zoomOutButton.className = css.imageViewer.outButtonInactive;
				s7zoom.fullButton.className = css.imageViewer.fullButtonInactive;
			}
			s7zoom.scale = x;
		};
 
		s7zoom.onEvent.onImageZoomedIn = function(x) {
			if (x != 1) {
				s7zoom.zoomOutButton.className = css.imageViewer.outButtonActive;
				s7zoom.fullButton.className = css.imageViewer.fullButtonActive;
				if (x > 3 && s7zoom.displayingSwatch == false) {
					s7zoom.zoomInButton.className = css.imageViewer.inButtonInactive;
				} else if (x > 1 && s7zoom.displayingSwatch == true) {
					s7zoom.zoomInButton.className = css.imageViewer.inButtonInactive;
				}
			}
			if (s7zoom.instructionsDisplayed === false){
				s7zoom.showInstructionAlert();
				s7zoom.instructionsDisplayed = true;
			}
			s7zoom.scale = x;
		};
 
		s7zoom.onEvent.onImageResetted = function (x) {
			s7zoom.zoomOutButton.className = css.imageViewer.outButtonInactive;
			s7zoom.zoomInButton.className = css.imageViewer.inButtonActive;
			s7zoom.fullButton.className = css.imageViewer.fullButtonInactive;
			s7zoom.scale = x;
		};
 
		s7zoom.changeImage = function(url, w, h) {
			s7zoom.hideAlert();
			url=url+"?op_sharpen=1";
			s7zoom.setImage(url, false, w, h);
			if (w <= 350) {
				s7zoom.displayingSwatch = true; 
			} else {
				s7zoom.displayingSwatch = false;
			}
		};
 
		s7zoom.showColorAlert = function(colorName) {
			if (colorName.length > 1) {
				s7zoom.alertText.innerHTML = "We're sorry, this photograph is not color changeable to " + colorName+".";
			} else {
				s7zoom.alertText.innerHTML = "We're sorry, this photograph is not color changeable to the selected color.";
			}
			s7zoom.photoViewerAlert.className = css.imageViewer.showAlert + ' photoViewerAlert';
			
			var alertObj = $("#" + s7zoom.photoViewerAlert.id);
			var alertObjParent = $("#" +s7zoom.photoViewerAlert.id).parent();
			var left = Math.round((alertObjParent.width()  - alertObj.width() )/ 2) + "px";
			var top = Math.round((alertObjParent.height()- alertObj.height() )/ 2) + "px";
			s7zoom.photoViewerAlert.style.left = left;
			s7zoom.photoViewerAlert.style.top = top;
			setTimeout(s7zoom.hideAlert, 3000);

		};
 
		s7zoom.showInstructionAlert = function() {
			s7zoom.alertText.innerHTML = "Click and drag to move image.";
			s7zoom.photoViewerAlert.className = css.imageViewer.showAlert;
			setTimeout(s7zoom.hideAlert, 5000);
		};
 
		s7zoom.hideAlert = function() {
			s7zoom.photoViewerAlert.className = css.imageViewer.hideAlert;
		};
 
		s7zoom.initZoomControls = function() {			
			$.debug("PhotoView.createPhotoViewer.initZoomControls initializing zoom controls for viewer for product " + viewerKeySuffix );
			s7zoom.zoomOutButton = document.getElementById('outButton_' + viewerKeySuffix);
			s7zoom.zoomInButton = document.getElementById('inButton_' + viewerKeySuffix);
			s7zoom.fullButton = document.getElementById('fullButton_' + viewerKeySuffix);
			s7zoom.fullScreenButton = document.getElementById('fullScreenButton_' + viewerKeySuffix);
			s7zoom.photoViewerAlert = document.getElementById("photoViewerAlert_" + viewerKeySuffix);
			s7zoom.alertText = document.getElementById("alertText_" + viewerKeySuffix);			
  
			s7zoom.zoomInButton.className = css.imageViewer.inButtonActive;
			s7zoom.zoomOutButton.className = css.imageViewer.outButtonInactive;
			s7zoom.fullButton.className = css.imageViewer.fullButtonInactive;
			
			s7zoom.zoomOutButton.onclick = function() {
				if (s7zoom.zoomOutButton.className == css.imageViewer.outButtonActive) {
					s7zoom.zoomOut();
				}
			};
			
			s7zoom.zoomInButton.onclick = function() {
				if (s7zoom.zoomInButton.className == css.imageViewer.inButtonActive) {
					s7zoom.zoomIn();
				}
			};
			
			s7zoom.fullButton.onclick = function() {
				if (s7zoom.fullButton.className == css.imageViewer.fullButtonActive) {
					s7zoom.reset();
				}
			};
			
			if (s7zoom.fullScreenButton != null && s7zoom.fullScreenButton != undefined){
				s7zoom.fullScreenButton.onclick = function(){
					viewerDisplay.selectFullScreenButton();
				}
			}
		};
		$.debug("PhotoView.createPhotoViewer COMPLETED creating photo viewer for image '" + imageName + "' width/height " + width + "/" + height + " inside div " + inViewId);
		return s7zoom;
	}
} //End photoViewerView




com.landsend.productView.PhotoDisplay = function(){
	// The Photo Viewer selection object that holds on to the image set and color code that the user is currently on.
	var PhotoViewerSelection = function(){
		this.productNumber = null;
		this.styleNumber = null;
		this.imageSetCollection = null;
		this.swatchList = null;
		this.selectedImageSetPosition = 0;	
		this.colorCode = null;
		this.hasOnlyLegacyImages = null;
		this.viewerMode = null;
	}
	
	var thisPhotoDisplay = this;
	
	var fullScreenButtonCallback = null;
	
	var viewerSelection = null;    // Used to hold the photo viewer selection for each style within the product.
	
	var photoView = null;
	
	this.init = function(productNumber, styleNumber, imageSetCollection, swatchList, hasOnlyLegacyImages, selectedColorCode, imagePosition, viewerMode, lastImageSetIsSwatch){
		var funcName = "PhotoDisplay.init ";
		if (viewerMode == undefined || viewerMode == null) { viewerMode = 'EMB';}
		viewerKeySuffix = (productNumber != undefined && productNumber != null ? productNumber + "_" : "") + 
                          (styleNumber != undefined && styleNumber != null ? styleNumber + "_" : "") + viewerMode;

		
		$.debug(funcName + "Initializing viewer for product " + productNumber + " style " + styleNumber + " selectedColorCode " + selectedColorCode + " imagePosition " + imagePosition);
		photoView = new com.landsend.productView.PhotoView(thisPhotoDisplay, productNumber, styleNumber, viewerMode);
		
		var selectedImageSetPosition = 0;		
		var imageObj = null;		
		var colorToUse = null;
		
		// First find the color that the initial image needs to be in.
		if (selectedColorCode != null && selectedColorCode != undefined)
		{ 
			colorToUse = selectedColorCode; 
		} else {		
			if (swatchList != null && swatchList.length > 0){
				var colorToUse = swatchList[0].getColor().getCode();			
			}
		}
		$.debug(funcName + " Trying to find image in color " + colorToUse);
		
		// Picking the first color in the swatch list for the style as the intial color for the product viewer only if there are swatches available.
		// Otherwise we will use the first image from the image list. 		
		if (colorToUse != null){
			if (imagePosition != null && imagePosition != undefined){				
				imageObj = imageSetCollection.getImageSetList()[imagePosition].getColorImage(colorToUse);
				if (imageObj == null){
					imageObj = imageSetCollection.getImageSetList()[imagePosition].getProductImageList()[0];					
				}
				selectedImageSetPosition = imagePosition;
			} else {				
				if (imageSetCollection.getImageSetByColor(colorToUse).getSwatch() == false){
					imageObj = imageSetCollection.getImageSetByColor(colorToUse).getColorImage(colorToUse);			
					selectedImageSetPosition = imageSetCollection.getImageSetNumberByColor(colorToUse);
				}
			}
		}		
		if (imageObj == null){ //case where there are no images in any of the image sets (excluding the swatch) defined for the style in the color code.
			imageObj = imageSetCollection.getImageSetList()[0].getProductImageList()[0];
			selectedImageSetPosition = 0;
		}
		$.debug(funcName + "Initializing PhotoViewer View for product " + productNumber + " style " + styleNumber);
		if (hasOnlyLegacyImages){
			photoView.showLegacyImage(imageObj.getUrl(), imageObj.getHeight(), imageObj.getImageServed());
		} else {
			photoView.init(imageObj.getFileName(), imageObj.getWidth(), imageObj.getHeight());
		}
		
		$.debug(funcName + "Building photo viewer selecton object for product " + productNumber + " style " + styleNumber);		
		viewerSelection = new PhotoViewerSelection();
		viewerSelection.productNumber = productNumber;
		viewerSelection.styleNumber = styleNumber;
		viewerSelection.selectedImageSetPosition = selectedImageSetPosition;
		viewerSelection.imageSetCollection = imageSetCollection;
		viewerSelection.swatchList = swatchList;
		viewerSelection.colorCode = colorToUse; 
		viewerSelection.hasOnlyLegacyImages = hasOnlyLegacyImages;
		viewerSelection.viewerMode = viewerMode;

		registerEvents();
		$.debug(funcName + " Initializing complete for product " + productNumber + " style " + styleNumber);
	}
	
	
	this.registerForFullScreenEvent = function(callbackFunction){
		$.debug("PhotoDisplay.registerForFullScreenEvent registering call back for full button click.");
		fullScreenButtonCallback = callbackFunction;
	}
	
	
	var registerEvents = function(){	
		var funcName = "PhotoDisplay.registerEvents ";

		$.debug(funcName + "Regsitering events on viewer controls for product " + viewerSelection.productNumber + ' style ' + viewerSelection.styleNumber);
		var imageSetList = viewerSelection.imageSetCollection.getImageSetList();
		for(var p=0; p < imageSetList.length; p++){
			photoView.registerAlternateImageSelector(p);
		}
		$.debug(funcName + "Registering events complete product " + viewerSelection.productNumber + ' style ' + viewerSelection.styleNumber);		
	}
		
	this.show = function(){
		photoView.show();
	}
	
	this.hide = function(){
		photoView.hide();
	}	
	
	this.alternateImageSelect = function(selectedImageSetPosition) {
		var funcName = "PhotoDisplay.alternateImageSelect ";
		$.debug(funcName + "Selecting alternate image for  product " + viewerSelection.productNumber + ' style ' + viewerSelection.styleNumber + " image set position " + selectedImageSetPosition);
		viewerSelection.selectedImageSetPosition = selectedImageSetPosition;		
        
        var imageSet = viewerSelection.imageSetCollection.getImageSetList()[selectedImageSetPosition];

        var viewerImage = null;
        if (viewerSelection.swatchList != null && viewerSelection.swatchList.length > 0){
        	viewerImage = imageSet.getColorImage(viewerSelection.colorCode);
        } else {
        	viewerImage = imageSet.getProductImageList()[0];
        }
        if (viewerSelection.hasOnlyLegacyImages) {
        	$.debug(funcName + "Style has only legacy images");
            if (viewerImage == null) {
            	viewerImage = viewerSelection.imageSetCollection.getImageSetList()[0].getProductImageList()[0];	            	
            	photoView.showLegacyImage(viewerImage.getUrl(), viewerImage.getHeight(), viewerImage.getImageServed());
            } else {
            	photoView.showLegacyImage(viewerImage.getUrl(), viewerImage.getHeight(), viewerImage.getImageServed());	            	
            }
            return;
        } 
		try {
	        if (viewerImage != null) {
	        	photoView.showViewerImage(viewerImage.getUrl(), viewerImage.getWidth(), viewerImage.getHeight(), viewerImage.getImageServed());
	        } else {
	        	photoView.showViewerImage(imageSet.getProductImageList()[0].getUrl(), imageSet.getProductImageList()[0].getWidth(), imageSet.getProductImageList()[0].getHeight(), imageSet.getProductImageList()[0].getImageServed());
	        	$.debug(funcName + "Alternate image not available in requested color, so showing a color alert message");
	        	photoView.showColorAlert(thisPhotoDisplay.getColorByCode(viewerSelection.colorCode).getName());
	        }      
	        $.debug(funcName + "Reset viewer so it goes back to original sized image");
	        photoView.resetViewer();	        
	    } catch(e) {
	    	alert("exception caught"+e+"no image viewer?");
	    	$.debug(funcName + "Error choosing alternate image " + e);
	    }
	    return false;
    }

	this.updateViewerColor = function () {
		var funcName = "PhotoDisplay.updateViewerColor ";
		var clrCode = viewerSelection.colorCode;

    	$.debug(funcName + "Switching image to another color - " + clrCode);
        var imageSet = viewerSelection.imageSetCollection.getImageSetList()[viewerSelection.selectedImageSetPosition];
        var viewerImage = imageSet.getColorImage(clrCode);
        var imageChanged = false;

        // If the image in the selected color/image set position does not exist, then switch to the first image in that image set.
        if (viewerImage == null) {
        	if (viewerSelection.imageSetCollection.getImageSetByColor(clrCode).getSwatch() == false){
        		viewerImage = viewerSelection.imageSetCollection.getImageSetByColor(clrCode).getColorImage(clrCode);			
        		imageChanged = true;
        	} else {
        		viewerImage = viewerSelection.imageSetCollection.getImageSetList()[viewerSelection.selectedImageSetPosition].getProductImageList()[0];
        		imageChanged = true;
        	}
        }
        if (!viewerSelection.hasOnlyLegacyImages){
            if (viewerImage != null) {
            	photoView.showViewerImage(viewerImage.getUrl(), viewerImage.getWidth(), viewerImage.getHeight(), viewerImage.getImageServed());
            	if (imageChanged == true){
            		photoView.resetViewer();
            		photoView.showColorAlert(thisPhotoDisplay.getColorByCode(viewerSelection.colorCode).getName());
            	}	            	
            } else {
            	photoView.showColorAlert(thisPhotoDisplay.getColorByCode(viewerSelection.colorCode).getName());
            }
        } else if (viewerSelection.hasOnlyLegacyImages && viewerImage != null) {
        	photoView.showLegacyImage(viewerImage.getUrl(), viewerImage.getHeight(), viewerImage.getImageServed());
        }
        
        //Now update the alternate image colors.
        var numImageSets = viewerSelection.imageSetCollection.getImageSetList().length;
        for (var i=0; i < numImageSets; i++) {	        	
        	var altImage = viewerSelection.imageSetCollection.getImageSetList()[i].getColorImage(clrCode);
        	// If an alternate image is not available in a particular color, then pick up the first image in that imageset.
        	if (altImage == null){
        		altImage  = viewerSelection.imageSetCollection.getImageSetList()[i].getProductImageList()[0];
        	}
        	if ( i == 4 && numImageSets > 5 && altImage.getImageServed() == false) {
				continue;
			}	
        	if (viewerSelection.imageSetCollection.getImageSetList()[i].length < 1) {
        		continue;
        	}
        	if (altImage != null) {
        		var altImageText = null;
        		if (viewerSelection.imageSetCollection.getImageSetList()[i].getSwatch() == true){
        			altImageText = thisPhotoDisplay.getColorByCode(viewerSelection.colorCode).getName();
        		}
        		photoView.showAlternateImage(viewerSelection.productNumber + "_" + viewerSelection.styleNumber + "_" + viewerSelection.viewerMode, i, altImage.getUrl(), altImage.getImageServed(), altImageText, viewerSelection.imageSetCollection.getImageSetList()[i].getSwatch());
        	}
        }	
		$.debug(funcName + "Switching image to another color - " + clrCode + "completed.");
		
		
	}
	
	this.selectFullScreenButton = function(){
		$.debug("PhotoDisplay.selectFullScreenButton Full screen button clicked, pass control to the callback.");
		if (fullScreenButtonCallback != null){
			fullScreenButtonCallback.call(thisPhotoDisplay, viewerSelection.productNumber, viewerSelection.styleNumber, viewerSelection.imageSetCollection, viewerSelection.swatchList, viewerSelection.colorCode, viewerSelection.selectedImageSetPosition);
		}
	}
	
	this.setPhotoViewerColorCode = function(colorCode){
		$.debug("PhotoDisplay.setPhotoViewerColorCode setting the color code on the photo viewer selection object to " + colorCode);
		viewerSelection.colorCode = colorCode;
	}
	
	this.getColorByCode = function(colorCode){
		var colorObj = null;
		for(var i=0; i < viewerSelection.swatchList.length; i++){
			if (viewerSelection.swatchList[i].getColor().getCode() == colorCode){
				colorObj = viewerSelection.swatchList[i].getColor();
				break;
			}
		}
		return colorObj;
	}
} //End PhotoDisplay.

//$.jsNamespace('com.landsend.productView');
var com;
if(com == undefined){
	com = new Object();
}
if(com.landsend == undefined){
	com.landsend = new Object();
}
if(com.landsend.productView == undefined){
	com.landsend.productView = new Object();
}


com.landsend.productView.StandardBuyGridView = function(buyGridController,productId){
	var thisStandardBuyGridView = this;
	var prodViewNs = com.landsend.productView;
	var buyGridController = buyGridController;
	var productId = productId;
	
	this.promoView = new function(){
		var promoTextContainer = "promotionTextContainer";
		
		this.displayPromoText = function(promos){
			$("#" + buildCompoundKey(promoTextContainer)).html("");
			var html = "";
			if(promos != null && promos != undefined){
				for(var i = 0;i < promos.length;i++){ 
					html = html + '<div class="pp-promotion">' + promos[i].getText() + '</div>';
				}
				$("#" + buildCompoundKey(promoTextContainer)).html(html);
			}
			
		}
	}
	
	this.addToBagView = new function(){
		var addToBagButton = "addToBagButton";
		var cancelUpdateButton = "cancelUpdateButton";
		var productBuyGrid = "productGrid";
		
		var addToBag = function(event){
			buyGridController.shoppingBagController.addToBag();
			event.preventDefault();
		}
		
		var hoverOverAddToBag = function(event){
			var errors = buyGridController.shoppingBagController.errorChecker(false);
			showToolTip($(this),errors[0]);	
			event.preventDefault();
		}
		
		var hoverOutAddToBag = function(event){
			hideToolTip($(this));
			event.preventDefault();
		}

		var checkAddToBagState = function(event){
			buyGridController.shoppingBagController.checkAddToBagState();  
		}
		
		var cancelUpdateBag = function(event){
			buyGridController.cancelUpdateBag();
			return false;
		}
		
		this.registerEvents = function(){
			$("#" + buildCompoundKey(addToBagButton)).bind('click',addToBag);
			$("#" + buildCompoundKey(addToBagButton)).bind('mouseenter focus',hoverOverAddToBag);
			$("#" + buildCompoundKey(addToBagButton)).bind('mouseleave blur',hoverOutAddToBag);		
			$("#" + buildCompoundKey(productBuyGrid)).bind('click',checkAddToBagState);
			$("#" + buildCompoundKey(productBuyGrid)).bind('change',checkAddToBagState);
			$("#" + buildCompoundKey(productBuyGrid)).bind('keyup',checkAddToBagState);
		}
		
		this.enableAddToBag = function(isUpdateMode){
			if(isUpdateMode){
				$("#" + buildCompoundKey(addToBagButton)).addClass("pp-update-item-available");
			}else{
				$("#" + buildCompoundKey(addToBagButton)).addClass("pp-add-to-bag-available");
			}
		}
		
		this.disableAddToBag = function(isUpdateMode){
			if(isUpdateMode){
				$("#" + buildCompoundKey(addToBagButton)).removeClass("pp-update-item-available");
			}else{
				$("#" + buildCompoundKey(addToBagButton)).removeClass("pp-add-to-bag-available");
			}
		}
	
		this.setUpdateMode = function(isBundlePage){
			$("#" + buildCompoundKey(addToBagButton)).html("<span>Update Item</span>");
			$("#" + buildCompoundKey(addToBagButton)).removeClass("pp-add-to-bag-available");
			$("#" + buildCompoundKey(addToBagButton)).removeClass("pp-add-to-bag");
			$("#" + buildCompoundKey(addToBagButton)).addClass("pp-update-item");			
			
			if ($("#" + buildCompoundKey(cancelUpdateButton)).length == 0) {
				if (isBundlePage){
					$('<a id="'+buildCompoundKey(cancelUpdateButton)+'" href="#" class="pp-cancel-update-item le-modal-alternate-close"><span>Cancel Update Bundle</span></a>').insertAfter($("#" + buildCompoundKey(addToBagButton)));
					$('#' + buildCompoundKey(cancelUpdateButton)).bind('click', cancelUpdateBag);
				} else {
					$('<a id="'+buildCompoundKey(cancelUpdateButton)+'" href="https://' + window.location.host + '/co/ShoppingBag.html?refer=' + encodeURIComponent(window.location.href) + '" class="pp-cancel-update-item"><span>Cancel Update</span></a>').insertAfter($("#" + buildCompoundKey(addToBagButton)));					
				}
			}
		}
		
		this.showInlineBag = function(key){$("#" + key).removeClass("pp-hide");}
		
		this.showProcessingHandler = function() {
			window.leutil.ui.processingHandlerInline.show($("#" + buildCompoundKey(addToBagButton)),{left:-22,top:6,image:"spinner_blue_16x16.gif"});
		}
		
		this.hideProcessingHandler = function() {
			window.leutil.ui.processingHandlerInline.hide($("#" + buildCompoundKey(addToBagButton)));			
		}
	}
	
	this.schoolUniformView = new function(){
		var parentSchoolUniformContainer = "parentSchoolUniformContainer";
		var schoolUniformLearnMorePageLink = "schoolUniformLearnMorePage";
		var findSchoolUniformButton = "findSchoolUniformButton";
		var forgotSchoolCodeButton = "forgotSchoolCode";
		var changeSchoolButton = "changeSchoolButton";
		var schoolUniformNumberField = "schoolUniformNumberField";
		var schoolUniformLogoChooser = "schoolUniformLogoChooser";
		var schoolUniformPageContainer = "schoolUniformPage";
		var schoolUniformFinderContainer = "schoolUniformFinder";
		var schoolNumberContainer = "schoolNumberBanner";
		var schoolNameContainer = "schoolNameBanner";
		var schoolUniformLogoContainer = "schoolUniformLogo"
		var schoolUniformDressCodeContainer = "schoolUniformDressCode";
		var schoolUniformMissingLogoMessage = "schoolUniformMissingLogoMessage";
		var logoNumberTextContainer = "schoolUniformLogoNumberText";
		var schoolUniformLogoPreviewArea = "schoolUniformLogoPreviewArea";		
		var preferredSchoolCheckbox = "preferredSchoolCheckbox";
		var preferredSchoolCheckboxContainer = "preferredSchoolCheckboxContainer";
		var logoImage = "logoImage";
		var schoolLogoList = "schoolLogoList";
		var schoolUniformBanner = "schoolUniformBanner";
		var schoolUniformFinderFinder = "schoolUniformFinderFinder";
		var schoolUniformLogoParent = "schoolUniformLogoContainer";
		
		this.registerEvents = function(){
			$("#" + buildCompoundKey(preferredSchoolCheckbox)).bind('change',selectSchoolUniform);
			$("#" + buildCompoundKey(schoolUniformLearnMorePageLink)).bind('click',selectSchoolPopup);
			$("#" + buildCompoundKey(findSchoolUniformButton)).bind('click',selectFindSchool);
			$("#" + buildCompoundKey(findSchoolUniformButton)).bind('mouseover',hoverOver);	
			$("#" + buildCompoundKey(findSchoolUniformButton)).bind('mouseout',hoverOut);			
			$("#" + buildCompoundKey(forgotSchoolCodeButton)).bind('click',selectSchoolSearchPopup);
			$("#" + buildCompoundKey(schoolUniformNumberField)).bind('keyup',schoolNumberKeyUp);
			$("#" + buildCompoundKey(changeSchoolButton)).bind('click',selectChangeSchool);
		}

		var hoverOver = function(){
			var errors = buyGridController.valueAddedServicesController.schoolUniformController.errorChecker(false);
			showToolTip($(this),errors[0]);
		}
		
		var hoverOut = function(){
			hideToolTip($(this));
		}		
		
		var schoolNumberKeyUp = function(event){
			var pos = $("#" + this.id).getCursorPosition();
			if(cursorKeyCheck(event)){return;}
			buyGridController.valueAddedServicesController.schoolUniformController.onSchoolNumberChange($("#" + buildCompoundKey(schoolUniformNumberField)).attr("value"));
			event.preventDefault();
			$("#" + this.id).setCursorPosition(pos);
		}
		
		var selectSchoolUniform = function(event){
			buyGridController.valueAddedServicesController.schoolUniformController.selectSchoolUniform(this.checked);
			if(this.checked){
				$("#" + buildCompoundKey(preferredSchoolCheckboxContainer)).addClass("pp-checkbox-selected");
			}
			else{
				$("#" + buildCompoundKey(preferredSchoolCheckboxContainer)).removeClass("pp-checkbox-selected");
			}
		}
		
	    var selectSchoolPopup = function(event) {
	        LE_popup(this.href);
	        event.preventDefault();
	    };	
	
	    var selectSchoolSearchPopup = function(event) {
	        //var win = window.open ("/pp/SchoolSearch.html", "SchoolSearch","resizable=yes,status=yes,scrollbars=no,toolbar=no,height=550,width=550");
	        //win.focus();
	    	com.landsend.school.SchoolLookupService.launchSchoolSearchDialog();
	        event.preventDefault();
	    };	    
	    
	    var selectFindSchool = function(event){
	    	buyGridController.valueAddedServicesController.schoolUniformController.selectFindSchool($("#" + buildCompoundKey(schoolUniformNumberField)).attr("value"));
	    	event.preventDefault();
	    }
	    
	    var selectChangeSchool = function(event){
	    	buyGridController.valueAddedServicesController.schoolUniformController.selectChangeSchool();
	    	event.preventDefault();
	    }
	    
	    var selectLogo = function(event){
	    	buyGridController.valueAddedServicesController.schoolUniformController.selectLogo(this.value);
	    	event.preventDefault();
	    }
	    
	    this.setupLogoSelection = function(logos,required,allowable){
	    	var id = schoolLogoList + "_" + productId;
	    	var html = "";
	    	
			if(allowable){
				html = html + "<option value=''>Select</option>";
				html = html + "<option value='-1'>----------------</option>";
			}
			if(! required){
				html = html + "<option value='-2'>Do not add a logo to this item / $0.00</option>";
			}
			
			for(var i = 0;i < logos.length;i++){ 
				html = html + "<option value='" + logos[i].code +"'>" + logos[i].name +" / $" + logos[i].price.toFixed(2) + "</option>";		
			}		
			
			if($("#" + buildCompoundKey(schoolUniformLogoChooser)).find("select").length == 0){
	    		html = "<select id='"+id+"' name='schoolLogoDropList'>" + html + "</select>";
	    		$("#" + buildCompoundKey(schoolUniformLogoChooser)).html(html);
	    		$("#" + id).bind('change',selectLogo);
	    	}
			else{
				$("#" + buildCompoundKey(schoolUniformLogoChooser)).find("select").html(html);
			}	
			leutil.ui.selectHandler.update($("#" + id));
	    }
	    
	    this.setupSchoolUniformDressCode = function(url){
	    	var html = "For Dress Code details, please call <b>1.800.469.2222.</b>";
	    	if(url != null){
	    		html = "<a href='"+url+"' target='blank'>View Dress Code Guidelines PDF</a>";
	    	}
	    	$("#" + buildCompoundKey(schoolUniformDressCodeContainer)).html(html);
	    }

	    
		this.setSchoolUniformLogoImageUrl = function(url){
			if(url != null){
				$("#" + buildCompoundKey(logoImage)).attr("src",url);
				$("#" + buildCompoundKey(logoImage)).removeClass("pp-hide");
			}else{
				$("#" + buildCompoundKey(logoImage)).attr("src","");
				$("#" + buildCompoundKey(logoImage)).addClass("pp-hide");
			}
		}

		this.checkSchoolUniform = function(showIt){
			if(showIt){$("#" + buildCompoundKey(preferredSchoolCheckbox)).attr("checked",true);}
			else{$("#" + buildCompoundKey(preferredSchoolCheckbox)).attr("checked",false);}
		}				
		
		this.setLogoNumberText = function(value){$("#" + buildCompoundKey(logoNumberTextContainer)).html("Preview: Logo Number " + value);}
	    this.setSchoolUniformNumberField = function(value){$("#" + buildCompoundKey(schoolUniformNumberField)).attr("value",value);}
	    this.setSchoolNumber = function(value){$("#" + schoolNumberContainer).html(value);}
	    this.setSchoolName = function(value){$("#" + schoolNameContainer).html("Welcome "+value+" Families");}
		this.showSchoolUniformWidget = function(){
			$("#" + buildCompoundKey(schoolUniformPageContainer)).removeClass("pp-hide");	
			leutil.ui.selectHandler.update($("#" + buildCompoundKey(schoolLogoList)));			
		}	
		this.setLogo = function(code){
			if (code != null) $("#" + buildCompoundKey(schoolLogoList)).val(code);
			leutil.ui.selectHandler.update($("#" + buildCompoundKey(schoolLogoList)));
		}
		
		this.hideSchoolUniformWidget = function(){$("#" + buildCompoundKey(schoolUniformPageContainer)).addClass("pp-hide");}	    
		this.showSchoolUniformFinder = function(){
			$("#" + buildCompoundKey(schoolUniformFinderContainer)).removeClass("pp-hide");
			this.hideChangeSchoolButton();	
		}		
		this.hideSchoolUniformFinder = function(){
			$("#" + buildCompoundKey(schoolUniformFinderContainer)).addClass("pp-hide");
			this.showChangeSchoolButton();
		}		
		
		this.showChangeSchoolButton = function(){$("#" + buildCompoundKey(changeSchoolButton)).removeClass("pp-hide");}
		this.hideChangeSchoolButton = function(){$("#" + buildCompoundKey(changeSchoolButton)).addClass("pp-hide");}
		this.showParentSchoolUniformContainer = function(){$("#" + buildCompoundKey(parentSchoolUniformContainer)).removeClass("pp-hide");}
		this.hideParentSchoolUniformContainer = function(){$("#" + buildCompoundKey(parentSchoolUniformContainer)).addClass("pp-hide");}
		this.showSchoolUniformLogoSelector = function(){
			$("#" + buildCompoundKey(schoolUniformLogoContainer)).removeClass("pp-hide");
			leutil.ui.selectHandler.update($("#" + buildCompoundKey(schoolLogoList)));
		}		
		this.hideSchoolUniformLogoSelector = function(){$("#" + buildCompoundKey(schoolUniformLogoContainer)).addClass("pp-hide");}			
		this.showSchoolUniformMissingLogoMessage = function(){$("#" + buildCompoundKey(schoolUniformMissingLogoMessage)).removeClass("pp-hide");}		
		this.hideSchoolUniformMissingLogoMessage = function(){$("#" + buildCompoundKey(schoolUniformMissingLogoMessage)).addClass("pp-hide");}		
		this.showSchoolUniformLogoPreviewArea = function(){$("#" + buildCompoundKey(schoolUniformLogoPreviewArea)).show();}		
		this.hideSchoolUniformLogoPreviewArea = function(){$("#" + buildCompoundKey(schoolUniformLogoPreviewArea)).hide();}			
		this.showPeferredSchoolCheckboxContainer = function(){$("#" + buildCompoundKey(preferredSchoolCheckboxContainer)).show();}	
		this.hidePeferredSchoolCheckboxContainer = function(){$("#" + buildCompoundKey(preferredSchoolCheckboxContainer)).hide();}	
		this.showSchoolUniformBanner = function(){$("#" + schoolUniformBanner).removeClass("pp-hide");}	
		this.hideSchoolUniformBanner = function(){$("#" + schoolUniformBanner).addClass("pp-hide");}	
		this.showErrorIconSchoolNumber = function(){$("#" + buildCompoundKey(schoolUniformFinderFinder)).addClass("pp-selector-error");}	
		this.hideErrorIconSchoolNumber = function(){$("#" + buildCompoundKey(schoolUniformFinderFinder)).removeClass("pp-selector-error");}	
		this.showErrorIconSchoolUniformLogo = function(){$("#" + buildCompoundKey(schoolUniformLogoParent)).addClass("pp-selector-error");}	
		this.hideErrorIconSchoolUniformLogo = function(){$("#" + buildCompoundKey(schoolUniformLogoParent)).removeClass("pp-selector-error");}			
	}
	
	this.productView = new function() {
		var skuAvailabiityTextKeyPrefix = "skuAvailabiityText";
		var priceKeyPrefixText = "productPrice";
		var itemNumberPrefixText = "itemNumber";
		var descriptionPrefixText = "productName";
		
		this.showText = function(id) {
			if ( id == "I") {
				$("#" + buildCompoundKey(skuAvailabiityTextKeyPrefix)).html("UNAVAILABLE");
				$("#" + buildCompoundKey(skuAvailabiityTextKeyPrefix)).parents(".pp-selector").addClass("pp-selector-unavailable").removeClass("pp-selector-backordered");
			}
			if ( id == "B") {
				$("#" + buildCompoundKey(skuAvailabiityTextKeyPrefix)).html("BACKORDERED");
				$("#" + buildCompoundKey(skuAvailabiityTextKeyPrefix)).parents(".pp-selector").removeClass("pp-selector-unavailable").addClass("pp-selector-backordered");
			}
			if ( id == "A") {
				$("#" + buildCompoundKey(skuAvailabiityTextKeyPrefix)).html("IN STOCK");
				$("#" + buildCompoundKey(skuAvailabiityTextKeyPrefix)).parents(".pp-selector").removeClass("pp-selector-unavailable").removeClass("pp-selector-backordered");
			}
			if ( id == "1") { //This condition occurs when the user has not selected a size and is hovering out of a size. It should reset to
				              // Select Size
				$("#" + buildCompoundKey(skuAvailabiityTextKeyPrefix)).html("");
				$("#" + buildCompoundKey(skuAvailabiityTextKeyPrefix)).parents(".pp-selector").removeClass("pp-selector-unavailable").removeClass("pp-selector-backordered");
			}
		}
		
		this.resetPrice = function() { $("#" + buildCompoundKey(priceKeyPrefixText)).html("");	}
		
		this.showPrice =  function(originalPrice, price) {
			if (originalPrice == null) {
				$("#" + buildCompoundKey(priceKeyPrefixText)).html("$ " + price.toFixed(2));
			}
			else {
				$("#" + buildCompoundKey(priceKeyPrefixText)).html("<span class='pp-was-price'>$ " + originalPrice.toFixed(2) + "</span>" +
																			"<span> NOW $ " + price.toFixed(2) + "</span>");
			}
		}
		
		this.changeItemNumber = function(styleNumber, mediaCode, checkDigit, longName) {
			if (styleNumber != null && mediaCode !=null && checkDigit != null) {
				var paddedStyleNumber = leutil.string.lpad(styleNumber+"", 6);
				var displayCatalogNumber = paddedStyleNumber.substring(0,5) + "-" + paddedStyleNumber.substring(5) + mediaCode + checkDigit;
				$("#" + buildCompoundKey(descriptionPrefixText)).html(longName);
				$("#" + buildCompoundKey(itemNumberPrefixText)).html(displayCatalogNumber);
			}
		}
		
	}
	
	this.monogramView = new function(){
		var temp = buyGridController;
		var monogramController = buyGridController.valueAddedServicesController.monogramController; 
		
		var maxWordInputBoxSize = 15;
		var monoHeaderStepLinks = "monoHeaderStepLinks";
		var monogramChooserKeyPrefix = "monogramChooser";
		var monogramContainerKeyPrefix = "monogramContainer";
		var monogramCheckBoxKeyPrefix = "monogramCheckBox";
		var monogramPriceKeyPrefix = "vasPrice";
		var monogramTypeOptionKeyPrefix = "monogramTypeOption";
		var monogramMonoTypeKeyPrefix = "monoType";
		var monogramFontOptionKeyPrefix = "monogramFontOption";
		var monogramFontSelectorKeyPrefix = "monogramFontSelector";
		var monogramLocationOptionKeyPrefix = "monogramLocationOption"
		var monogramLocationSelectorKeyPrefix = "monogramLocationSelector";
		var monogramLocationHeaderKeyPrefix = "monogramLocationHeader";
		var monogramThreadColorKeyPrefix = "monogramThreadColor";
		var singleInitialSelectorKeyPrefix = "singleInitialSelector";
		var initialsSelectorKeyPrefix = "initialsSelector";
		var wordSelectorKeyPrefix = "wordSelector";
		var multiLineSelectorKeyPrefix = "multiLineSelector";		
		var step1ContainerKeyPrefix  = "monogramStep_0";
		var step2ContainerKeyPrefix = "monogramStep_1"
		var step3ContainerKeyPrefix = "monogramStep_2"
		var navStep1ContainerKeyPrefix  = "monogramNavStep_0";
		var navStep2ContainerKeyPrefix = "monogramNavStep_1";
		var navStep3ContainerKeyPrefix = "monogramNavStep_2";			
		var toStep3ButtonKeyPrefix = "monogramStep3NextButton_2";
		var toStep2ButtonKeyPrefix = "monogramStep2NextButton_1";
		var applyMonogramButtonKeyPrefix = "monogramApplyButton_3";
		var monogramTypeChoicePrefix = "monoTypeChoice";
		var monogramFontChoicePrefix = "monoFontChoice";
		var monogramLocationChoicePrefix = "monoLocationChoice";
		var monogramTypeSelector = "monoTypeSelector";
		var monoFontSelector = "monoFontSelector";
		var monoLocationSelector = "monoLocationSelector";
		var initialsSelectorMiddle = "initialsSelectorMiddle";
		var initialsSelectorFirst = "initialsSelectorFirst";
		var initialsSelectorLast = "initialsSelectorLast";
		var wordSelector = "wordSelector";
		var monogramWordHintContainerKeyPrefix = "monogramWordHint";
		var monogramMultiLineHintContainerKeyPrefix = "monogramMultiLineHint";
		var previewContainerKeyPrefix = "monogramPreviewWindow";
		var monogramPreviewWindowInitialKeyPrefix = "monogramPreviewWindowInitial";
		var monogramPreviewWindowThreeInitialsKeyPrefix = "monogramPreviewWindowThreeInitials";
		var monogramPreviewWindowWordKeyPrefix = "monogramPreviewWindowWord";
		var monogramPreviewWindowMultiLineKeyPrefix = "monogramPreviewWindowMultiLine";		
		var monogramSingleInitialInputContainerKeyPrefix = "monogramSingleInitial";		
		var monogramInitialsInputContainerKeyPrefix = "monogramInitials";
		var monogramWordInputContainerKeyPrefix = "monogramWord";
		var monogramMultiLineContainerKeyPrefix = "monogramMultiLine";
		var monogramMultiLineSelectorContainerKeyPrefix = "monogramMultiLineSelector";
		var monogramRecapContainer = "monogramRecap";
		var monogramRecapTextTypeContainer = "monogramRecapTextType";
		var monogramRecapTextContentContainer = "monogramRecapTextContent";
		var monogramRecapFontContentContainer = "monogramRecapStyleContent";
		var monogramRecapLocationContentContainer = "monogramRecapLocationContent";
		var monogramRecapThreadContentContainer = "monogramRecapThreadContent";
		var updateMonogramButton = "updateMonogramButton";
		var removeMonogramButton = "removeMonogramButton";
		var cancelMonogramButton = "cancelMonogramButton";
		var specialRequestsMonogramButton = "specialRequestsMonogramButton";
		var learnMoreMonogramButton = "learnMoreMonogramButton";
		var selectMonogram = function(){monogramController.selectMonogram(this.checked);}
		var selectMonogramType = function(event){monogramController.selectMonogramType(this.id.split('_')[2]);event.preventDefault();}
		var selectMonogramFont = function(event){monogramController.selectMonogramFont(this.id.split('_')[2]);event.preventDefault();}		
		var selectMonogramLocation = function(event){monogramController.selectMonogramLocation(this.id.split('_')[2]);event.preventDefault();}
		var selectStepOne = function(event){monogramController.selectStepOne();event.preventDefault();}
		var selectStepTwo = function(event){monogramController.selectStepTwo();event.preventDefault();}
		var selectStepThree = function(event){monogramController.selectStepThree();event.preventDefault();}
		
		var hoverOver = function(){
			var goingTostep = Number($(this).attr("id").split('_')[1]);
			var errors = monogramController.errorChecker(false,goingTostep);
			showToolTip($(this),errors[0]);
		}
		
		var hoverOut = function(){
			hideToolTip($(this));
		}
		
		var selectInitial = function(event){	
	 		monogramController.selectInitial(this.value.slice(0,1));		
		}
		var selectInitials = function(event){	
			monogramController.selectInitials(this.value.slice(0,1),Number(this.id.split('_').slice(2,3)[0]));
		}
		var selectWord = function(event){
			var pos = $("#" + this.id).getCursorPosition();
			if(cursorKeyCheck(event)){return;}
			monogramController.selectWord(this.value);
			$("#" + this.id).setCursorPosition(pos);
		}
		var selectMultiLine = function(event){
			var pos = $("#" + this.id).getCursorPosition();
			if(cursorKeyCheck(event)){return;}
			monogramController.selectMultiLine(this.value,Number(this.id.split('_').slice(2,3)[0]));
			$("#" + this.id).setCursorPosition(pos);
		}
		
		var selectApplyUpdateOrMonogram = function(event){
			monogramController.selectApplyUpdateOrMonogram();
			event.preventDefault();
		}
		
		var selectUpdateMonogram = function(event){
			monogramController.selectUpdateMonogram();
			event.preventDefault();
		}
		
		var selectRemoveMonogram = function(event){
			monogramController.selectMonogram(false);
			event.preventDefault();		
		}
		
		var selectSpecialRequests = function(event) {
	        LE_popup(this.href);
	        event.preventDefault();
	    }	
	    
		var selectLearnMore = function(event){
	        LE_popup(this.href);
	        event.preventDefault();	    	
	    }
		
		this.registerEvents = function(){
			$("#" + buildCompoundKey(monogramCheckBoxKeyPrefix)).bind('change',selectMonogram);
			$("#" + buildCompoundKey(toStep2ButtonKeyPrefix)).bind('click',selectStepTwo);
			$("#" + buildCompoundKey(toStep3ButtonKeyPrefix)).bind('click',selectStepThree);
			$("#" + buildCompoundKey(toStep2ButtonKeyPrefix)).bind('mouseover',hoverOver);
			$("#" + buildCompoundKey(toStep3ButtonKeyPrefix)).bind('mouseover',hoverOver);	
			$("#" + buildCompoundKey(toStep2ButtonKeyPrefix)).bind('mouseout',hoverOut);
			$("#" + buildCompoundKey(toStep3ButtonKeyPrefix)).bind('mouseout',hoverOut);				
			$("#" + buildCompoundKey(navStep1ContainerKeyPrefix)).bind('click',selectStepOne);
			$("#" + buildCompoundKey(navStep2ContainerKeyPrefix)).bind('click',selectStepTwo);
			$("#" + buildCompoundKey(navStep3ContainerKeyPrefix)).bind('click',selectStepThree);
			$("#" + buildCompoundKey(navStep1ContainerKeyPrefix)).bind('mouseover',hoverOver);
			$("#" + buildCompoundKey(navStep2ContainerKeyPrefix)).bind('mouseover',hoverOver);
			$("#" + buildCompoundKey(navStep3ContainerKeyPrefix)).bind('mouseover',hoverOver);	
			$("#" + buildCompoundKey(navStep1ContainerKeyPrefix)).bind('mouseout',hoverOut);
			$("#" + buildCompoundKey(navStep2ContainerKeyPrefix)).bind('mouseout',hoverOut);
			$("#" + buildCompoundKey(navStep3ContainerKeyPrefix)).bind('mouseout',hoverOut);			
			$("#" + buildCompoundKey(monogramSingleInitialInputContainerKeyPrefix)).bind('keyup',selectInitial);
			$("#" + buildCompoundKey(monogramInitialsInputContainerKeyPrefix)+"_0").bind('keyup',selectInitials);
			$("#" + buildCompoundKey(monogramInitialsInputContainerKeyPrefix)+"_1").bind('keyup',selectInitials);
			$("#" + buildCompoundKey(monogramInitialsInputContainerKeyPrefix)+"_2").bind('keyup',selectInitials);
			$("#" + buildCompoundKey(monogramWordInputContainerKeyPrefix)).bind('keyup',selectWord);
			$("#" + buildCompoundKey(applyMonogramButtonKeyPrefix)).bind('click',selectApplyUpdateOrMonogram);		
			$("#" + buildCompoundKey(applyMonogramButtonKeyPrefix)).bind('mouseover',hoverOver);	
			$("#" + buildCompoundKey(applyMonogramButtonKeyPrefix)).bind('mouseout',hoverOut);	
			$("#" + buildCompoundKey(updateMonogramButton)).bind('click',selectUpdateMonogram);
			$("#" + buildCompoundKey(removeMonogramButton)).bind('click',selectRemoveMonogram);
			$("#" + buildCompoundKey(cancelMonogramButton+"_0")).bind('click',selectRemoveMonogram);
			$("#" + buildCompoundKey(cancelMonogramButton+"_1")).bind('click',selectRemoveMonogram);
			$("#" + buildCompoundKey(cancelMonogramButton+"_2")).bind('click',selectRemoveMonogram);
			$("#" + buildCompoundKey(specialRequestsMonogramButton+"_0")).bind('click',selectSpecialRequests);
			$("#" + buildCompoundKey(specialRequestsMonogramButton+"_1")).bind('click',selectSpecialRequests);
			$("#" + buildCompoundKey(specialRequestsMonogramButton+"_2")).bind('click',selectSpecialRequests);
			$("#" + buildCompoundKey(specialRequestsMonogramButton+"_3")).bind('click',selectSpecialRequests);
			$("#" + buildCompoundKey(learnMoreMonogramButton)).bind('click',selectLearnMore);
		}
		
		this.setupWordInputView = function(maxLength){
			var displaySize = maxWordInputBoxSize;
			if(maxLength <= displaySize){
				displaySize = maxLength;
			}
			$("#" + buildCompoundKey(monogramWordInputContainerKeyPrefix)).attr("value","");
			$("#" + buildCompoundKey(monogramWordInputContainerKeyPrefix)).attr("maxlength",maxLength);
			$("#" + buildCompoundKey(monogramWordInputContainerKeyPrefix)).attr("size",displaySize);
		}
		
		this.setupMultiWordInputView = function(numberOfLines,maxLength){
			$("#" + buildCompoundKey(monogramMultiLineSelectorContainerKeyPrefix)).html("");
			var html = "";
			var displaySize = maxWordInputBoxSize;
			if(maxLength <= displaySize){
				displaySize = maxLength;
			}
			for(var i = 0;i < numberOfLines;i++){ 
				var id = monogramMultiLineContainerKeyPrefix + "_" + productId + "_" + i;	
				var id2 = wordSelector + "_" + productId + "_" + i;
				var label = null;
				if(i == 0){
					label = "<label class='pp-selector-label' for='monogram-line-text-"+ (i + 1) +"'>Enter Text <span>Line "+ (i + 1) +"</span></label>";
				}else{
					label = "<label class='pp-selector-label' for='monogram-line-text-"+ (i + 1) +"'><span> Enter Text Line "+ (i + 1) +"</span></label>";
				}			
				html = html + "<li><div id='" + id2 + "' class='pp-selector pp-textfield-selector pp-textfield-stacked-selector pp-monogram-word-selector'>" + label + 
				"<input id='" + id + "' type='text' value='' size='" + displaySize + "' maxlength='" + maxLength + "' /></div></li>";							
			}
			$("#" + buildCompoundKey(monogramMultiLineSelectorContainerKeyPrefix)).html(html);
			for(var i = 0;i < numberOfLines;i++){ 
				var id = monogramMultiLineContainerKeyPrefix + "_" + productId + "_" + i;
				$("#"+id).bind('keyup',selectMultiLine);	
			}					
		}
		
		this.setupMonogramTypeView = function(types){
			$("#" + buildCompoundKey(monogramTypeOptionKeyPrefix)).html("");
			$("#" + buildCompoundKey(monogramTypeChoicePrefix)).html("");
			for(var i = 0;i < types.length;i++){ 
				var id = monogramMonoTypeKeyPrefix + "_" + productId + "_" + types[i].getNumber();
				$("<li><a href='#' id='"+ id + "' class='pp-available' >"+types[i].getName()+"</a></li>").appendTo("#" + buildCompoundKey(monogramTypeOptionKeyPrefix));
				$("#"+id).bind('click',selectMonogramType);
			}
		}
	
		this.setupMonogramFontView = function(fonts){
			$("#" + buildCompoundKey(monogramFontSelectorKeyPrefix)).html("");
			$("#" + buildCompoundKey(monogramFontChoicePrefix)).html("");
			for(var i = 0;i < fonts.length;i++){ 
				var id = monogramFontOptionKeyPrefix + "_" + productId + "_" + fonts[i].getCode();
				$("<li class='pp-monogram-style-"+fonts[i].getCode()+"'><a href='#' class='pp-available' id='" + id + "'>" + fonts[i].getName() + "</a></li>").appendTo("#" + buildCompoundKey(monogramFontSelectorKeyPrefix));
				$("#"+id).click(selectMonogramFont);
			}			
		}

		this.setupMonogramLocationView = function(locations){
			$("#" + buildCompoundKey(monogramLocationSelectorKeyPrefix)).html("");
			$("#" + buildCompoundKey(monogramLocationChoicePrefix)).html("");
			if(locations.length > 1){
				for(var i = 0;i < locations.length;i++){ 
					var id = monogramLocationOptionKeyPrefix + "_" + productId + "_" + locations[i].getCode();
					$("<li><a id='" + id + "' href='#' class='pp-available' >" + locations[i].getName() +"</a></li>").appendTo("#" + buildCompoundKey(monogramLocationSelectorKeyPrefix));
					$("#"+id).click(selectMonogramLocation);
				}	
				$("#" + buildCompoundKey(monogramLocationHeaderKeyPrefix)).html("Monogramming Location <span id='"+buildCompoundKey(monogramLocationChoicePrefix)+"'></span>");
			}else if(locations.length > 0){
				$("#" + buildCompoundKey(monogramLocationHeaderKeyPrefix)).html("Monogramming Location <span id='"+buildCompoundKey(monogramLocationChoicePrefix)+"'>" + locations[0].getName() + "</span>"); 
			}			
		}

		this.showErrorIconMonoInitalsFirst = function(){$("#" + buildCompoundKey(initialsSelectorFirst)).addClass("pp-selector-error");}	
		this.hideErrorIconMonoInitalsFirst = function(){$("#" + buildCompoundKey(initialsSelectorFirst)).removeClass("pp-selector-error");}
		this.showErrorIconMonoInitalsMiddle = function(){$("#" + buildCompoundKey(initialsSelectorMiddle)).addClass("pp-selector-error");}	
		this.hideErrorIconMonoInitalsMiddle = function(){$("#" + buildCompoundKey(initialsSelectorMiddle)).removeClass("pp-selector-error");}
		this.showErrorIconMonoInitalsLast = function(){$("#" + buildCompoundKey(initialsSelectorLast)).addClass("pp-selector-error");}	
		this.hideErrorIconMonoInitalsLast = function(){$("#" + buildCompoundKey(initialsSelectorLast)).removeClass("pp-selector-error");}
		this.showErrorIconMonoWord = function(){$("#" + buildCompoundKey(wordSelectorKeyPrefix)).addClass("pp-selector-error");}	
		this.hideErrorIconMonoWord = function(){$("#" + buildCompoundKey(wordSelectorKeyPrefix)).removeClass("pp-selector-error");}		
		this.showErrorIconMonoMultiWord = function(){$("#" + buildCompoundKey(wordSelector,0)).addClass("pp-selector-error");}	
		this.hideErrorIconMonoMultiWord = function(){$("#" + buildCompoundKey(wordSelector,0)).removeClass("pp-selector-error");}			
		this.showErrorIconMonoSingleInitial = function(){$("#" + buildCompoundKey(singleInitialSelectorKeyPrefix)).addClass("pp-selector-error");}	
		this.hideErrorIconMonoSingleInitial = function(){$("#" + buildCompoundKey(singleInitialSelectorKeyPrefix)).removeClass("pp-selector-error");}	
		this.showErrorIconMonoFont = function(){$("#" + buildCompoundKey(monoFontSelector)).addClass("pp-selector-error");}	
		this.hideErrorIconMonoFont = function(){$("#" + buildCompoundKey(monoFontSelector)).removeClass("pp-selector-error");}	
		this.showErrorIconMonoLocation = function(){$("#" + buildCompoundKey(monoLocationSelector)).addClass("pp-selector-error");}	
		this.hideErrorIconMonoLocation = function(){$("#" + buildCompoundKey(monoLocationSelector)).removeClass("pp-selector-error");}	
		this.showErrorIconMonoType = function(){$("#" + buildCompoundKey(monogramTypeSelector)).addClass("pp-selector-error");}	
		this.hideErrorIconMonoType = function(){$("#" + buildCompoundKey(monogramTypeSelector)).removeClass("pp-selector-error");}	
		this.showMonogramRecapContainer = function(){$("#" + buildCompoundKey(monogramRecapContainer)).removeClass("pp-hide");}		
		this.hideMonogramRecapContainer = function(){$("#" + buildCompoundKey(monogramRecapContainer)).addClass("pp-hide");}			
		this.clearAllMonoTextInput = function(){$("#" + buildCompoundKey(step3ContainerKeyPrefix) + " input").attr("value","");}
		this.showMonogramContainer = function(){
			$("#" + buildCompoundKey(monogramContainerKeyPrefix)).removeClass("pp-hide");
			$("#" + buildCompoundKey(monogramChooserKeyPrefix)).addClass("pp-checkbox-selected");
		}		
		this.hideMonogramContainer = function(){
			$("#" + buildCompoundKey(monogramContainerKeyPrefix)).addClass("pp-hide");
			$("#" + buildCompoundKey(monogramChooserKeyPrefix)).removeClass("pp-checkbox-selected");
		}		
		this.showMonogramPreviewWindowInitial = function(){$("#" + buildCompoundKey(monogramPreviewWindowInitialKeyPrefix)).removeClass("pp-hide");}		
		this.hideMonogramPreviewWindowInitial = function(){$("#" + buildCompoundKey(monogramPreviewWindowInitialKeyPrefix)).addClass("pp-hide");}		
		this.showMonogramPreviewWindowThreeInitials = function(){$("#" + buildCompoundKey(monogramPreviewWindowThreeInitialsKeyPrefix)).removeClass("pp-hide");}		
		this.hideMonogramPreviewWindowThreeInitials = function(){$("#" + buildCompoundKey(monogramPreviewWindowThreeInitialsKeyPrefix)).addClass("pp-hide");}	
		this.showMonogramPreviewWindowWord = function(){$("#" + buildCompoundKey(monogramPreviewWindowWordKeyPrefix)).removeClass("pp-hide");}		
		this.hideMonogramPreviewWindowWord = function(){$("#" + buildCompoundKey(monogramPreviewWindowWordKeyPrefix)).addClass("pp-hide");}	
		this.showMonogramPreviewWindowMultiLine = function(){$("#" + buildCompoundKey(monogramPreviewWindowMultiLineKeyPrefix)).removeClass("pp-hide");}		
		this.hideMonogramPreviewWindowMultiLine = function(){$("#" + buildCompoundKey(monogramPreviewWindowMultiLineKeyPrefix)).addClass("pp-hide");}					
		this.setMonogramPrice = function(price){
			var displayPrice = price; 
			if (parseInt(price) == 0) {
				displayPrice = "Free";
				$("#" + buildCompoundKey(monogramPriceKeyPrefix)).html("Monogramming "+displayPrice);
			}
			else {
				if (parseInt(price) != price){displayPrice = price.toFixed(2);}
				$("#" + buildCompoundKey(monogramPriceKeyPrefix)).html("Monogramming $"+displayPrice);
			}			
		}	
		this.showMonogramVas = function(){$("#" + buildCompoundKey(monogramChooserKeyPrefix)).removeClass("pp-hide");}
		this.hideMonogramVas = function(){$("#" + buildCompoundKey(monogramChooserKeyPrefix)).addClass("pp-hide");}
		this.showStep1 = function(){
			$("#" + buildCompoundKey(step1ContainerKeyPrefix)).removeClass("pp-hide");
			$("#" + buildCompoundKey(navStep1ContainerKeyPrefix)).addClass("pp-step-selected");		
		}		
		this.hideStep1 = function(){
			$("#" + buildCompoundKey(step1ContainerKeyPrefix)).addClass("pp-hide");
			$("#" + buildCompoundKey(navStep1ContainerKeyPrefix)).removeClass("pp-step-selected");		
		}	
		this.showStep2 = function(){
			$("#" + buildCompoundKey(step2ContainerKeyPrefix)).removeClass("pp-hide");
			$("#" + buildCompoundKey(navStep2ContainerKeyPrefix)).addClass("pp-step-selected");		
		}		
		this.hideStep2 = function(){
			$("#" + buildCompoundKey(step2ContainerKeyPrefix)).addClass("pp-hide");
			$("#" + buildCompoundKey(navStep2ContainerKeyPrefix)).removeClass("pp-step-selected");		
		}	
		this.showStep3 = function(type){
			$("#" + buildCompoundKey(step3ContainerKeyPrefix)).removeClass("pp-hide");
			$("#" + buildCompoundKey(navStep3ContainerKeyPrefix)).addClass("pp-step-selected");		
			
			if(type == 1){ // initial 
				$("#" + buildCompoundKey(monogramSingleInitialInputContainerKeyPrefix)).focus();
			}else if(type == 2){ // initials 
				$("#" + buildCompoundKey(monogramInitialsInputContainerKeyPrefix)+"_0").focus();
			}if(type == 3){ // word 
				$("#" + buildCompoundKey(monogramWordInputContainerKeyPrefix)).focus();
			}else if(type == 4){// multi-word
				$("#" + buildCompoundKey(monogramMultiLineContainerKeyPrefix,0)).focus();
			}			
			
		}		
		this.hideStep3 = function(){
			$("#" + buildCompoundKey(step3ContainerKeyPrefix)).addClass("pp-hide");
			$("#" + buildCompoundKey(navStep3ContainerKeyPrefix)).removeClass("pp-step-selected");		
		}	
		this.setapplyMonogramButtonDesc = function(value){
			if(value){
				$("#" + buildCompoundKey(applyMonogramButtonKeyPrefix)).html("UPDATE MONOGRAM");
			}else{
				$("#" + buildCompoundKey(applyMonogramButtonKeyPrefix)).html("APPLY MONOGRAM");
			}
		}	
		
		this.showMonoHeaderStepLinks = function(){$("#" + buildCompoundKey(monoHeaderStepLinks)).removeClass("pp-hide");}		
		this.hideMonoHeaderStepLinks = function(){$("#" + buildCompoundKey(monoHeaderStepLinks)).addClass("pp-hide");}	
		this.showPreviewContainer = function(){$("#" + buildCompoundKey(previewContainerKeyPrefix)).removeClass("pp-hide");}		
		this.hidePreviewContainer = function(){$("#" + buildCompoundKey(previewContainerKeyPrefix)).addClass("pp-hide");}		
		this.showSingleInitialSelector = function(){$("#" + buildCompoundKey(singleInitialSelectorKeyPrefix)).removeClass("pp-hide");}		
		this.hideSingleInitialSelector = function(){$("#" + buildCompoundKey(singleInitialSelectorKeyPrefix)).addClass("pp-hide");}		
		this.showInitialsSelector = function(){$("#" + buildCompoundKey(initialsSelectorKeyPrefix)).removeClass("pp-hide");}		
		this.hideInitialsSelector = function(){$("#" + buildCompoundKey(initialsSelectorKeyPrefix)).addClass("pp-hide");}		
		this.showWordSelector = function(){$("#" + buildCompoundKey(wordSelectorKeyPrefix)).removeClass("pp-hide");}		
		this.hideWordSelector = function(){$("#" + buildCompoundKey(wordSelectorKeyPrefix)).addClass("pp-hide");}	
		this.showMultiLineSelector = function(){$("#" + buildCompoundKey(multiLineSelectorKeyPrefix)).removeClass("pp-hide");}		
		this.hideMultiLineSelector = function(){$("#" + buildCompoundKey(multiLineSelectorKeyPrefix)).addClass("pp-hide");}			
		this.checkMonogramType = function(types,typeId){
			var selectedText = "";
			for(var i = 0;i < types.length;i++){ 
				if(types[i].getNumber() == typeId){					
					$("#" + buildCompoundKey(monogramMonoTypeKeyPrefix,types[i].getNumber())).addClass("pp-available-selected");
					selectedText = $("#" + buildCompoundKey(monogramMonoTypeKeyPrefix,types[i].getNumber())).html();
				}else{
					$("#" + buildCompoundKey(monogramMonoTypeKeyPrefix,types[i].getNumber())).removeClass("pp-available-selected");
				}
			}
			$("#" + buildCompoundKey(monogramTypeChoicePrefix)).html(selectedText);
		}
		this.checkMonogramLocation = function(locations,locationCode,locationText){
			for(var i = 0;i < locations.length;i++){ 
				if(locations[i].getCode() == locationCode){
					$("#" + buildCompoundKey(monogramLocationOptionKeyPrefix,locations[i].getCode())).addClass("pp-available-selected");
				}else{
					$("#" + buildCompoundKey(monogramLocationOptionKeyPrefix,locations[i].getCode())).removeClass("pp-available-selected");
				}
			}	
			$("#" + buildCompoundKey(monogramLocationChoicePrefix)).html(locationText);
		}
		this.checkMonogramFont = function(fontList,fontCode){	
			var selectedText = "";
			for(var i = 0;i < fontList.length;i++){ 
				if(fontList[i].getCode() == fontCode){
					$("#" + buildCompoundKey(monogramFontOptionKeyPrefix,fontList[i].getCode())).addClass("pp-available-selected");
					selectedText = $("#" + buildCompoundKey(monogramFontOptionKeyPrefix,fontList[i].getCode())).html();
				}else{
					$("#" + buildCompoundKey(monogramFontOptionKeyPrefix,fontList[i].getCode())).removeClass("pp-available-selected");
				}
			}
			$("#" + buildCompoundKey(monogramFontChoicePrefix)).html(selectedText);
		}
		this.setMonogramSingleInitial = function(value){$("#" + buildCompoundKey(monogramSingleInitialInputContainerKeyPrefix)).attr("value",value);}
		this.setMonogramWord = function(value){$("#" + buildCompoundKey(monogramWordInputContainerKeyPrefix)).attr("value",value);}
		this.setMonogramSingleInitials = function(value,lineNumber){$("#" + buildCompoundKey(monogramInitialsInputContainerKeyPrefix,lineNumber)).attr("value",value);}
		this.setMultiLine = function(value,lineNumber){$("#" + buildCompoundKey(monogramMultiLineContainerKeyPrefix,lineNumber)).attr("value",value);}
		this.checkMonogram = function(showIt){
			if(showIt){$("#" + buildCompoundKey(monogramCheckBoxKeyPrefix)).attr("checked",true);}
			else{$("#" + buildCompoundKey(monogramCheckBoxKeyPrefix)).attr("checked",false);}
		}		
		this.displayMaxNumberCharacters = function(type,maxLength){
			if(type == 3){ // word 
				$("#" + buildCompoundKey(monogramWordHintContainerKeyPrefix)).html("Up to " + maxLength + " characters");	
			}else if(type == 4){ // multi-Line	
				$("#" + buildCompoundKey(monogramMultiLineHintContainerKeyPrefix)).html("Up to " + maxLength + " characters per line");	
			}			
		}
		this.showPreview = function(type,url,position){
			if(type == 1){ // initial 
				$("#" + buildCompoundKey(monogramPreviewWindowInitialKeyPrefix) + " img")[1].src = url;
			}else if(type == 2){ // initials 
				$("#" + buildCompoundKey(monogramPreviewWindowThreeInitialsKeyPrefix) + " img")[position + 1].src = url;
			}if(type == 3){ // word 
				$("#" + buildCompoundKey(monogramPreviewWindowWordKeyPrefix) + " img")[1].src = url;
			}else if(type == 4){// multi-word
				$("#" + buildCompoundKey(monogramPreviewWindowMultiLineKeyPrefix) + " img")[1].src = url;
			}
		}	
		this.setMonogramRecapTextType = function(value){$("#" + buildCompoundKey(monogramRecapTextTypeContainer)).html(value);}
		this.setMonogramRecapTextContent = function(monogramMultiLine){
			var recapText = "";
			if(monogramMultiLine != null && typeof monogramMultiLine == "object" && monogramMultiLine instanceof Array){
				if(monogramMultiLine != undefined && monogramMultiLine[0] != undefined && monogramMultiLine[0] != null && monogramMultiLine[0].length > 0){
					recapText = recapText + "<br/>" + monogramMultiLine[0];
				}
				if(monogramMultiLine != undefined && monogramMultiLine[1] != undefined && monogramMultiLine[1] != null && monogramMultiLine[1].length > 0){
					recapText = recapText + "<br/>" + monogramMultiLine[1];
				}
				if(monogramMultiLine != undefined && monogramMultiLine[2] != undefined && monogramMultiLine[2] != null && monogramMultiLine[2].length > 0){
					recapText = recapText + "<br/>" + monogramMultiLine[2];
				}				
				$("#" + buildCompoundKey(monogramRecapTextContentContainer)).html(recapText);
			}else{
				$("#" + buildCompoundKey(monogramRecapTextContentContainer)).html(monogramMultiLine);
			}
		}
		this.setMonogramRecapFontContent = function(value){$("#" + buildCompoundKey(monogramRecapFontContentContainer)).html(value);}
		this.setMonogramRecapLocationContent = function(value){$("#" + buildCompoundKey(monogramRecapLocationContentContainer)).html(value);}
		this.setMonogramRecapThreadContent = function(value){$("#" + buildCompoundKey(monogramRecapThreadContentContainer)).html(value);}			
		this.setMonogramThreadColor = function(value){$("#" + buildCompoundKey(monogramThreadColorKeyPrefix)).html(value);}	
		this.showErrorIconMonogram = function(){$("#" + buildCompoundKey(monogramChooserKeyPrefix)).addClass("pp-selector-error");}	
		this.hideErrorIconMonogram = function(){$("#" + buildCompoundKey(monogramChooserKeyPrefix)).removeClass("pp-selector-error");}	
	}
	
	this.hemmingView = new function(){
		var cuffingIdKeyPrefix = "cuffingId";		
		var sizeRecommendationKeyPrefix = "sizeRecommendation";
		var sizeCuffingKeyPrefix = "sizeCuffing";
		var sizeInseamKeyPrefix = "sizeInseam";
		var sizeWaistKeyPrefix = "sizeWaist";
		var inseamChooserKeyPrefix = "inseamChooser";
		var cuffingChooserKeyPrefix = "cuffingChooser";
		var sizeCuffingSelectionKeyPrefix = "sizeCuffingSelection";
		var uncuffableMessageKeyPrefix = "sizeCuffingUncuffableMessage";

		this.showErrorHemmingSelection = function(){$("#" + buildCompoundKey(sizeInseamKeyPrefix)).addClass("pp-selector-error");}
		
		this.hideErrorHemmingSelection = function(){$("#" + buildCompoundKey(sizeInseamKeyPrefix)).removeClass("pp-selector-error");}
		
		this.makeInseamSelectionVisible = function(){$("#" + buildCompoundKey(sizeInseamKeyPrefix)).show();};
		
		this.hideInseamSelection = function(){$("#" + buildCompoundKey(sizeInseamKeyPrefix)).hide();}; ;
		
		this.makeInseamSelectable = function(){
			$("#" + buildCompoundKey(inseamChooserKeyPrefix)).attr("disabled",false);
			leutil.ui.selectHandler.update($("#" + buildCompoundKey(inseamChooserKeyPrefix)));
		}
		
		this.makeInseamNotSelectable = function(){
			$("#" + buildCompoundKey(inseamChooserKeyPrefix)).attr("disabled",true);
			leutil.ui.selectHandler.update($("#" + buildCompoundKey(inseamChooserKeyPrefix)));
		}	
		
		this.makeCuffingSelectable = function(){	
			$("#" + buildCompoundKey(cuffingIdKeyPrefix,"cuffed")).attr("class", "pp-available").unbind("mouseover").unbind("mouseout");
			$("#" + buildCompoundKey(uncuffableMessageKeyPrefix)).addClass("pp-hide");
		}
		
		this.makeCuffingNotSelectable = function(message){		
			if(!$("#" + buildCompoundKey(cuffingIdKeyPrefix,"cuffed")).hasClass("pp-unavailable")){
				$("#" + buildCompoundKey(cuffingIdKeyPrefix,"cuffed")).attr("class", "pp-unavailable").unbind("mouseover").unbind("mouseout");
				$("#" + buildCompoundKey(cuffingIdKeyPrefix,"cuffed")).bind("mouseover",function(){
					showTooltip($(this),message);		
				});
				$("#" + buildCompoundKey(cuffingIdKeyPrefix,"cuffed")).bind("mouseout",function(){
					hideToolTip($(this));
				});		
				buyGridController.hemmingController.cuffingSelect("uncuffed");
			}
		}			
		
		this.makeCuffingOptionsNotSelected = function(message) {
			$("#" + buildCompoundKey(cuffingIdKeyPrefix,"cuffed")).attr("class", "pp-available").unbind("mouseover").unbind("mouseout");
			$("#" + buildCompoundKey(cuffingIdKeyPrefix,"cuffed")).bind("mouseover",function(){
				showToolTip($(this),message);
			});
			$("#" + buildCompoundKey(cuffingIdKeyPrefix,"cuffed")).bind("mouseout",function(){
				hideToolTip($(this));
			});	
			$("#" + buildCompoundKey(cuffingIdKeyPrefix,"uncuffed")).bind("mouseover",function(){
				showToolTip($(this),message);
			});
			$("#" + buildCompoundKey(cuffingIdKeyPrefix,"uncuffed")).bind("mouseout",function(){
				hideToolTip($(this));
			});	
			$("#" + buildCompoundKey(cuffingIdKeyPrefix,"uncuffed")).attr("class", "pp-unavailable");
			$("#" + buildCompoundKey(cuffingIdKeyPrefix,"cuffed")).attr("class", "pp-unavailable");			
			$("#" + buildCompoundKey(sizeCuffingSelectionKeyPrefix)).html("");	
		}

		this.makeCuffingOptionsAvailable = function() {
			$("#" + buildCompoundKey(cuffingIdKeyPrefix,"cuffed")).attr("class", "pp-available").unbind("mouseover").unbind("mouseout");
			$("#" + buildCompoundKey(cuffingIdKeyPrefix,"uncuffed")).attr("class", "pp-available-selected").unbind("mouseover").unbind("mouseout");
			$("#" + buildCompoundKey(cuffingIdKeyPrefix,"cuffed")).attr("class", "pp-available");
			$("#" + buildCompoundKey(sizeCuffingSelectionKeyPrefix)).html("Uncuffed");	
			$("#" + buildCompoundKey(uncuffableMessageKeyPrefix)).addClass("pp-hide");
		}
		
		this.buildInseamList = function(inseamList){
			$("#" + buildCompoundKey(inseamChooserKeyPrefix)).attr("innerHTML","");
			
			var value = "";
			var text = 'Select';
			var option = '<option value="' + value + '">' + text + '</option>';
	        $("#inseamChooser_" +  productId).append(option);
			value = "UNF";
			text = 'unfinished';	        
			option = '<option value="' + value + '">' + text + '</option>';
			$("#" + buildCompoundKey(inseamChooserKeyPrefix)).append(option);
	        for(var i = 0;i < inseamList.length;i++){ 
	        	value = inseamList[i];
				text = inseamList[i];
				option = '<option value="' + value + '">' + text + '</option>';
				$("#" + buildCompoundKey(inseamChooserKeyPrefix)).append(option);
	        }        
	        $("#" + buildCompoundKey(inseamChooserKeyPrefix)).bind('change', this.selectInseam);
	        
	        leutil.ui.selectHandler.update($("#" + buildCompoundKey(inseamChooserKeyPrefix)));
		}
		
		this.clearInseamList = function(){
			$("#" + buildCompoundKey(inseamChooserKeyPrefix)).attr("innerHTML","");
			var value = "UNF";
			var text = 'unfinished';	        
			var option = '<option value="' + value + '">' + text + '</option>';
			$("#" + buildCompoundKey(inseamChooserKeyPrefix)).append(option);
			
			leutil.ui.selectHandler.update($("#" + buildCompoundKey(inseamChooserKeyPrefix)));
		}
		
		this.selectInseam = function(){
			buyGridController.hemmingController.inseamSelect(this.value);
		}
		
		this.selectCuffing = function(event){
			var ids = this.id.split('_').slice(2);
			buyGridController.hemmingController.cuffingSelect(ids[0]);
			event.preventDefault();
		}
		
		this.registerCuffingSelectors = function(){
			$("#" + buildCompoundKey(cuffingIdKeyPrefix,"uncuffed")).bind('click',this.selectCuffing);
			$("#" + buildCompoundKey(cuffingIdKeyPrefix,"cuffed")).bind('click',this.selectCuffing);
		}
		
		this.displayInseamCode = function(inseamId){
			if (inseamId != null) $("#" + buildCompoundKey(inseamChooserKeyPrefix)).val(inseamId.replace(/\-/,"."));
			leutil.ui.selectHandler.update($("#" + buildCompoundKey(inseamChooserKeyPrefix)));
		}
		
		this.displayCuffingCode = function(cuffingId, isCuffingValid){
			var text;			
			if (cuffingId == "uncuffed") {
				text = "Uncuffed";
				$("#" + buildCompoundKey(cuffingIdKeyPrefix,"uncuffed")).attr("class", "pp-available-selected");
				if (isCuffingValid) {
					$("#" + buildCompoundKey(cuffingIdKeyPrefix,"cuffed")).attr("class", "pp-available");
				}
				else {
					$("#" + buildCompoundKey(cuffingIdKeyPrefix,"cuffed")).attr("class", "pp-unavailable");
				}
			}
			else {
				text = "Cuffed";
				$("#" + buildCompoundKey(cuffingIdKeyPrefix,"cuffed")).attr("class", "pp-available-selected");
				$("#" + buildCompoundKey(cuffingIdKeyPrefix,"uncuffed")).attr("class", "pp-available");				
			}

		$("#" + buildCompoundKey(sizeCuffingSelectionKeyPrefix)).html(text);
		}	
		
		this.displayUncuffableMessage = function(message){
			$("#" + buildCompoundKey(uncuffableMessageKeyPrefix)).html(message).removeClass("pp-hide");
		}
		
		this.hideCuffingElements = function(){
			$("#" + buildCompoundKey(sizeCuffingKeyPrefix)).hide();
		}
		
		this.showCuffingElements = function(){
			$("#" + buildCompoundKey(sizeCuffingKeyPrefix)).show();
		}
		
		this.hideInseamElements = function(){
			$("#" + buildCompoundKey(inseamChooserKeyPrefix)).hide();
		}
		
		this.showInseamElements = function(){
			$("#" + buildCompoundKey(inseamChooserKeyPrefix)).show();
		}
		
		this.showSizeElements = function(styleId){
			$("#" + buildCompoundKey(sizeRecommendationKeyPrefix,styleId)).show();
			$("#" + buildCompoundKey(sizeWaistKeyPrefix,styleId)).show();	
		}
		
		this.hideSizeElements = function(styleId){
			$("#" + buildCompoundKey(sizeRecommendationKeyPrefix,styleId)).hide();
			$("#" + buildCompoundKey(sizeWaistKeyPrefix,styleId)).hide();	
		}					
	}
	
	this.sizeView = new function(){
		var sizeIdKeyPrefix = "sizeId";
		var sizeNameLinkKeyPrefix = "sizeNameLink";
		var sizeChooserKeyPrefix = "sizeChooser";
		var sizeChoiceKeyPrefix = "sizeChoice";
		var sizeChartKeyPrefix = "sizeChart";
		var savedHoverState = null;
		var currentSelectionId = null;

		this.showErrorSizeSelection = function(styleId){$("#" + buildCompoundKey(sizeChooserKeyPrefix,styleId)).addClass("pp-selector-error");}
		
		this.hideErrorSizeSelection = function(styleId){$("#" + buildCompoundKey(sizeChooserKeyPrefix,styleId)).removeClass("pp-selector-error");}
		
		var getSizeElemet = function(styleId,sizeCode){
			var element = $("#" + buildCompoundKey(sizeIdKeyPrefix,styleId,sizeCode))[0];
			return element;
		}
		
		var setCurrectSelection = function(styleNumber, sizeCode) {
			currentSelectionId = buildCompoundKey(sizeIdKeyPrefix,styleNumber, sizeCode);
		}
				
		this.selectSize = function(event){
			var ids = this.id.split('_').slice(3);
			buyGridController.sizeColorController.sizeSelect(ids[0]);
			var localstyleId = this.id.split('_').slice(2);
//			setCurrectSelection(localstyleId[0], ids[0]);
//			currentSelectionId = buildCompoundKey(sizeIdKeyPrefix,localstyleId[0], ids[0]);
			thisStandardBuyGridView.colorView.highLightSelectedSwatch(localstyleId);			
			event.preventDefault();
		}
		
		this.hoverOverSize = function(event){
			var ids = this.id.split('_').slice(3);
			var preHoverCurrentSelection = currentSelectionId;

			if (currentSelectionId != null) {
				savedHoverState = $("#" + currentSelectionId).attr("class");
			}

			var message = buyGridController.sizeColorController.sizehoverOver(ids[0]);
			showToolTip($(this),message);
			
			currentSelectionId = preHoverCurrentSelection;
			if (currentSelectionId != null){
				$("#" + currentSelectionId).attr("class", savedHoverState);
			}	

			event.preventDefault();
		}
		
		this.hoverOutSize = function(event){
			var styleId = buyGridController.sizeColorController.sizehoverOut();	
			hideToolTip($(this));
			
			if (currentSelectionId == null) {
				thisStandardBuyGridView.productView.showText(1);
				$("#" + buildCompoundKey(sizeChoiceKeyPrefix,styleId)).html("");
			}

			event.preventDefault();
		}
		
		this.registerSizeSelectors = function(styleId,sizeCodeId){
			$("#" + buildCompoundKey(sizeNameLinkKeyPrefix,styleId,sizeCodeId)).bind('click',this.selectSize); // accessibility
			$("#" + buildCompoundKey(sizeIdKeyPrefix,styleId,sizeCodeId)).bind('click',this.selectSize);
			$("#" + buildCompoundKey(sizeIdKeyPrefix,styleId)).bind('click',this.selectSize); // called for select option	

			if(window.leutil.ui.browser.isiPad()){
				$("#" + buildCompoundKey(sizeIdKeyPrefix,styleId,sizeCodeId)).bind('mousedown',this.hoverOverSize);
				
				$("#" + buildCompoundKey(sizeIdKeyPrefix,styleId)).bind('mousedown',this.hoverOverSize); // called for select option		
			}
			else{
				$("#" + buildCompoundKey(sizeIdKeyPrefix,styleId,sizeCodeId)).bind('mouseenter focus',this.hoverOverSize);
				$("#" + buildCompoundKey(sizeIdKeyPrefix,styleId,sizeCodeId)).bind('mouseleave blur',this.hoverOutSize);
				
				$("#" + buildCompoundKey(sizeIdKeyPrefix,styleId)).bind('mouseenter focus',this.hoverOverSize); // called for select option
				$("#" + buildCompoundKey(sizeIdKeyPrefix,styleId)).bind('mouseenter blur',this.hoverOverSize); // called for select option			
			}
		
			
		}	
		
		this.registerSizeChartSelector = function(styleId){
			$("#" + buildCompoundKey(sizeChartKeyPrefix,styleId)).bind('click', showSizeChartPopup);
		}
		
		this.registerInseamHemmingInfoSelector = function(){
			$('#inseamHemmingInformation_' + productId).bind('click', showInseamHemmingPopup);
		}
		
		this.sizeNotSelectedNotAvailable = function(styleId,sizeCode){
			var sizeElement = getSizeElemet(styleId,sizeCode);
			sizeElement.className = "pp-unavailable";		
		}
		
		this.sizeNotSelectedBackOrdered = function(styleId,sizeCode){
			var sizeElement = getSizeElemet(styleId,sizeCode);
			sizeElement.className = "pp-backorder";
		}
		
		this.sizeNotSelected = function(styleId,sizeCode){
			var sizeElement = getSizeElemet(styleId,sizeCode);
			sizeElement.className = "pp-available";
		}
		
		this.sizeSelectedBackOrdered = function(styleId,sizeCode){
			var sizeElement = getSizeElemet(styleId,sizeCode);
			setCurrectSelection(styleId, sizeCode);
			sizeElement.className = "pp-backorder-selected";
		}
		
		this.sizeSelectedNotAvailable = function(styleId,sizeCode){
			var sizeElement = getSizeElemet(styleId,sizeCode);
			setCurrectSelection(styleId, sizeCode);
			sizeElement.className = "pp-unavailable-selected";	
		}
		
		this.sizeSelected = function(styleId,sizeCode){
			var sizeElement = getSizeElemet(styleId,sizeCode);
			setCurrectSelection(styleId, sizeCode);
			sizeElement.className = "pp-available-selected";
		}

		this.hideStyleLevelElements = function(styleId){
			$("#" + buildCompoundKey(sizeChooserKeyPrefix,styleId)).hide();
			$("#" + buildCompoundKey(sizeChartKeyPrefix,styleId)).hide();
		}
		
		this.showStyleLevelElements = function(styleId){
			$("#" + buildCompoundKey(sizeChooserKeyPrefix,styleId)).show();
			$("#" + buildCompoundKey(sizeChartKeyPrefix,styleId)).show();
		}
		
		this.showSizeChoice = function(styleId, sizeDescription) {
			$("#" + buildCompoundKey(sizeChoiceKeyPrefix,styleId)).html(sizeDescription);			
		}
		
		var showSizeChartPopup = function(event){
			LE_popup(this.href);
			event.preventDefault();
		}
		
		var showInseamHemmingPopup = function(event){
			LE_popup(this.href);
			event.preventDefault();
		}
	}
	
	this.colorView = new function(){
		var colorChooserKeyPrefix = "colorChooser";
		var swatchImageKeyPrefix = "swatchImage";
		var colorChoiceKeyPrefix = "colorChoice";
		var orderSwatchKeyPrefix = "orderSwatch";

		this.selectColor = function(event){
			var ids = this.id.split('_').slice(3);
			buyGridController.sizeColorController.colorSelect(ids[0]);
			ids = this.id.split('_').slice(2);
			thisStandardBuyGridView.colorView.highLightSelectedSwatch(ids[0]);
			event.preventDefault();
		}
		
		this.hoverOutColor = function(event){
			var ids = this.id.split('_').slice(3);
			buyGridController.sizeColorController.colorhoverOut();
			hideToolTip($(this));
			event.preventDefault();
		}
		
		this.hoverOverColor = function(event){
			var ids = this.id.split('_').slice(3);
			var message = buyGridController.sizeColorController.colorhoverOver(ids[0]);
			showToolTip($(this),message);	
			event.preventDefault();
		}		
		
		this.selectOrderSwatch = function(event){
			var location = this.href + "&refer=" + encodeURIComponent(window.location.href);
			window.location.href = location;
			event.preventDefault();
			
		}
		
		this.registerEvents = function(styleId){
			$("#" + buildCompoundKey(orderSwatchKeyPrefix,styleId)).bind('click',this.selectOrderSwatch);	
		}
		
		this.registerColorSelectors = function(styleId,colorCodeId){
			$("#" + buildCompoundKey(swatchImageKeyPrefix,styleId,colorCodeId)).bind('click',this.selectColor);
			$("#" + buildCompoundKey(swatchImageKeyPrefix,styleId,colorCodeId)).bind('mouseenter focus',this.hoverOverColor);
			$("#" + buildCompoundKey(swatchImageKeyPrefix,styleId,colorCodeId)).bind('mouseleave blur',this.hoverOutColor);
		}
		
		this.colorNotSelectedNotAvailable = function(styleId,colorCode){$("#" + buildCompoundKey(swatchImageKeyPrefix,styleId,colorCode)).attr("class", "pp-unavailable");}
		this.colorNotSelectedBackOrdered = function(styleId,colorCode){$("#" + buildCompoundKey(swatchImageKeyPrefix,styleId,colorCode)).attr("class", "pp-backorder");}
		this.colorNotSelected = function(styleId,colorCode){$("#" + buildCompoundKey(swatchImageKeyPrefix,styleId,colorCode)).attr("class", "");}
		this.colorSelectedBackOrdered = function(styleId,colorCode){$("#" + buildCompoundKey(swatchImageKeyPrefix,styleId,colorCode)).attr("class", "pp-selected pp-backorder");				}	
		this.colorSelectedNotAvailable = function(styleId,colorCode){$("#" + buildCompoundKey(swatchImageKeyPrefix,styleId,colorCode)).attr("class", "pp-selected pp-unavailable");}
		
		this.colorSelected = function(styleId,colorCode){
			$("#" + buildCompoundKey(swatchImageKeyPrefix,styleId,colorCode)).attr("class", "pp-selected");
		}
	
		this.hideStyleLevelElements = function(styleId){
			$("#" + buildCompoundKey(colorChooserKeyPrefix,styleId)).hide();
			$("#" + buildCompoundKey(orderSwatchKeyPrefix,styleId)).hide();
		}
		
		this.showStyleLevelElements = function(styleId){
			$("#" + buildCompoundKey(colorChooserKeyPrefix,styleId)).show();
			$("#" + buildCompoundKey(orderSwatchKeyPrefix,styleId)).show();
		}
		
		this.showColorChoice = function(styleId, colorText) {
			$("#" + buildCompoundKey(colorChoiceKeyPrefix,styleId)).html(colorText);			
		}
		
		this.highLightSelectedSwatch = function(styleId) {
			window.swatchSelector.hilight(productId,styleId);
		}

	}
	
	this.featureTypeView = new function(){
		var featureKeyPrefix = "feature";
		var featureGroupKeyPrefix = "featureTypeSelector";
		var subFeatureTextKeyPrefix = "subFeatureTypeSelectionText";
		
		this.selectFeature = function(event){
			var ids = this.id.split('_').slice(2);
			buyGridController.featureTypeController.selectFeature(ids[0],ids[1],ids[2]);
			event.preventDefault();
		}
		
		this.registerFeatureTypeSelectors = function(primaryFeatureId,secondaryFeatureId,thirdFeatureId){$("#" + buildCompoundKey(featureKeyPrefix,primaryFeatureId,secondaryFeatureId,thirdFeatureId)).bind('click',this.selectFeature);}
		
		this.hightLightFeature = function(primaryFeatureId,secondaryFeatureId,thirdFeatureId, styleId){
			if (secondaryFeatureId == null) {
				$("#" + buildCompoundKey(featureKeyPrefix,primaryFeatureId,secondaryFeatureId,thirdFeatureId)).addClass("selected");
				thisStandardBuyGridView.colorView.highLightSelectedSwatch(styleId)
			}
			else {
				$("#" + buildCompoundKey(featureKeyPrefix,primaryFeatureId,secondaryFeatureId,thirdFeatureId)).addClass("pp-available-selected");				 
			}

		}
		this.unselectFeature = function(primaryFeatureId,secondaryFeatureId,thirdFeatureId){
			if (secondaryFeatureId == null) {
				$("#" + buildCompoundKey(featureKeyPrefix,primaryFeatureId,secondaryFeatureId,thirdFeatureId)).removeClass("selected");
			}
			else {
				$("#" + buildCompoundKey(featureKeyPrefix,primaryFeatureId,secondaryFeatureId,thirdFeatureId)).removeClass("pp-available-selected");
			}
		}
		
		this.showFeatureText= function (secondFeatureText,  thirdFeatureText) {
			if (thirdFeatureText != null) {
				$("#" + buildCompoundKey(subFeatureTextKeyPrefix,"3")).html(thirdFeatureText);
				
			}
			$("#" + buildCompoundKey(subFeatureTextKeyPrefix,"2")).html(secondFeatureText);
		}
		
		this.showFeatureGroup = function(primaryFeatureId,secondaryFeatureId){$("#" + buildCompoundKey(featureGroupKeyPrefix,primaryFeatureId,secondaryFeatureId)).show();}
		this.hideFeatureGroup = function(primaryFeatureId,secondaryFeatureId){$("#" + buildCompoundKey(featureGroupKeyPrefix,primaryFeatureId,secondaryFeatureId)).hide();}
	}
		
	this.dropShipView = new function(){
		this.registerEvents = function(){
			$("#dayTimePhone_" + productId + " #daytime-phone").bind('keyup', selectPhone);
			$("#dayTimePhoneEXT_" + productId + " #daytime-phone-extension").bind('keyup', selectExtension);
			$("#alternativePhone_" + productId + " #alternative-phone").bind('keyup',selectPhone);
			$("#alternativePhoneEXT_" + productId + " #alternative-phone-extension").bind('keyup', selectExtension);	
			$('#whiteGloveDeliveryinformation_' + productId).bind('click', showLearnMorePopup);
		}	
		
		var selectPhone = function(event){
			var pos = $("#" + this.id).getCursorPosition();
			if(cursorKeyCheck(event)){return;}
			var alternatePhoneSelect = false;
			if (this.id == 'alternative-phone'){
				alternatePhoneSelect = true;
			}
			buyGridController.dropShipController.phoneSelect(this.value, alternatePhoneSelect);
			$("#" + this.id).setCursorPosition(pos);
		}
		
		var selectExtension = function(event){
			var pos = $("#" + this.id).getCursorPosition();
			if(cursorKeyCheck(event)){return;}
			var alternateExtensionSelect = false;
			if (this.id == 'alternative-phone-extension'){
				alternateExtensionSelect = true;
			}
			buyGridController.dropShipController.extensionSelect(this.value, alternateExtensionSelect);
			$("#" + this.id).setCursorPosition(pos);
		}
		
		this.displayPhoneNumber = function(phoneNumber, alternatePhoneNumber){
			if (alternatePhoneNumber){
				$("#alternativePhone_" + productId + " #alternative-phone").val(phoneNumber);
			} else {
				$("#dayTimePhone_" + productId + " #daytime-phone").val(phoneNumber);
			}
		}
		
		this.displayExtensionNumber = function(extensionNumber, alternateExtensionNumber){
			if (alternateExtensionNumber){
				$("#alternativePhoneEXT_" + productId + " #alternative-phone-extension").val(extensionNumber);
			} else {
				$("#dayTimePhoneEXT_" + productId + " #daytime-phone-extension").val(extensionNumber);
			}
		}
		
		this.showErrorIconDayPhone = function(){$("#dayTimePhone_" + productId).addClass("pp-selector-error");}	
		this.showErrorIconDayExtension = function(){$("#dayTimePhoneEXT_" + productId).addClass("pp-selector-error");}
		this.showErrorIconAltPhone = function(){$("#alternativePhone_" + productId).addClass("pp-selector-error");}	
		this.showErrorIconAltExtension = function(){$("#alternativePhoneEXT_" + productId).addClass("pp-selector-error");}
		
		this.hideErrorIconDayPhone = function(){$("#dayTimePhone_" + productId).removeClass("pp-selector-error");}	
		this.hideErrorIconDayExtension = function(){$("#dayTimePhoneEXT_" + productId).removelass("pp-selector-error");}
		this.hideErrorIconAltPhone = function(){$("#alternativePhone_" + productId).removeClass("pp-selector-error");}	
		this.hideErrorIconAltExtension = function(){$("#alternativePhoneEXT_" + productId).removeClass("pp-selector-error");}
		
		var showLearnMorePopup = function(event){
			LE_popup(this.href);
			event.preventDefault();
		}
	}
	

	this.quantityView = new function(){		
		this.registerQuantitySelector = function(){
			var qtysel = ($('#quantity_' +  productId + " select"));
			$('#quantity_' +  productId + " select").bind('change', this.selectQuantity);
		}
		
		this.selectQuantity = function(){
			buyGridController.quantityController.quantitySelect(this.value);
		}
		
		this.displayQuantity = function(qty){
			$('#quantity_' +  productId + " select").val(qty);
			leutil.ui.selectHandler.update($('#quantity_' +  productId + " select"));
		}
		
		this.buildQauntityOptionToList = function(){
			for(var qtyValue = 1; qtyValue < 13; qtyValue++){
				var option = '<option value="' + qtyValue + '">' + qtyValue + '</option>';
				$('#quantity_' +  productId + " select").append(option);
			}
		    // used to trigger redraw of faux select box
		    leutil.ui.selectHandler.update($('#quantity_' +  productId + " select"));
	    }
	}		
	
	var showToolTip = function(element,message){
		if((message == null || message == undefined) && element != null){
			hideToolTip(element);
		}
		if(message == null || message == undefined){
			return;
		}
		if(!message.type){
			leutil.ui.tooltipHandler.show({
				button: element,
				text: message
			});
		}else if(message.type == 1){
			leutil.ui.tooltipHandler.show({
				button: element,
				type: "error",
				text: message.text
			});
		}else if(message.type == 2){
			leutil.ui.tooltipHandler.show({
				button: element,
				type: "warning",
				text: message.text
			});
		}else if(message.type == 3){
			leutil.ui.tooltipHandler.show({
				button: element,
				text: message.text
			});
		}		
	}
	
	var hideToolTip = function(element){
		leutil.ui.tooltipHandler.hide(element);
	}
	
	var cursorKeyCheck = function(event){
		if(event.keyCode == 37 || event.keyCode == 39){
			return true;
		}
		return false;
	}
	
	// used to build a compound key based on provided key values. Always prefixes the product id.
	var buildCompoundKey = function(keyPrefix,key1,key2,key3){
		var key = "";
		if(key1 != null && key2 != null && key3 != null){
			key = "_" + key1 + "_" + key2 + "_" + key3;
		}else if(key1 != null && key2 != null){
			key = "_" + key1 + "_" + key2;
		}else if(key1 != null){
			key = "_" + key1;
		}	
		key = "_" + productId + key;
		if(keyPrefix != null || keyPrefix != undefined){
			key = keyPrefix + key;
		}
		return key;
	}	
}

//$.jsNamespace('com.landsend.productView');
var com;
if(com == undefined){
	com = new Object();
}
if(com.landsend == undefined){
	com.landsend = new Object();
}
if(com.landsend.productView == undefined){
	com.landsend.productView = new Object();
}


com.landsend.productView.StandardBuyGridController = function(productView, webAnalyticsParam){
	var thisStandardBuyGrid = this;
	var prodViewNs = com.landsend.productView;
	var productView = productView;
	var globalManager = prodViewNs.GlobalManager; // shortcut reference
	var product = productView.getProduct(); // shortcut reference
	var requestedFeature = productView.getRequestedFeature();
	var styles = product.getRootFeature().getAllStylesAtOrBelow(); // shortcut reference
	var allFeatures = product.getAllFeatures(); // shortcut reference
	var selection = new prodViewNs.Selection(product.getNumber());
	var standardBuyGridView = null;//new prodViewNs.StandardBuyGridView(this,product.getNumber());
	var styleChangeCallbacks = new Array();
	var schoolChangeCallbacks = new Array();
	var shoppingBagCallbacks = new Array();
	var schoolSelectionUnsetCallbacks = new Array();
	var cancelUpdateBagCallbacks = new Array();
	var colorChangeCallbacks = new Array();
	var debugContext = ""; // used to track style # / color code / size code / sku #
	var buyGridContext = null; //Used to track the context in which this buy grid is launched i.e QuickView or ProductPage.
	
	this.giftCardExtensionController = null;
	
	this.productView = productView;
	
	this.getProductView = function(){
		return productView;
	}
	
	var init = function(){

		debug("[init] intializing buy grid......");
		if (product.isGCProduct()) {
			thisStandardBuyGrid.giftCardExtensionController = new com.landsend.productView.GiftCardExtensionController(productView, selection, webAnalyticsParam);
			thisStandardBuyGrid.giftCardExtensionController.init();
			
		}
		standardBuyGridView = new prodViewNs.StandardBuyGridView(thisStandardBuyGrid,product.getNumber());
		thisStandardBuyGrid.promoController.init();
		buyGridContext = "PP";
		if (webAnalyticsParam != undefined && webAnalyticsParam != null) {
			webAnalyticsParam.init(thisStandardBuyGrid);
			buyGridContext = "QV";
		}

		it = product.getParentProduct();
		if(product.getParentProduct() != null && (s_omtr.evar15 == undefined || s_omtr.evar15 == null || s_omtr.evar15 == "")){
			s_omtr.evar15 = "SPR";
		}else if(s_omtr.evar15 == undefined || s_omtr.evar15 == null || s_omtr.evar15 == "") {
			s_omtr.evar15 = "PP";
		}			
		// Photoviewer initialization needs to happen before the default selections are set on it.
		thisStandardBuyGrid.productPhotoViewerController.init();


		thisStandardBuyGrid.quantityController.init();		
		thisStandardBuyGrid.setupDefaultSelections();
		registerEvents();
		
		thisStandardBuyGrid.valueAddedServicesController.monogramController.init();
		thisStandardBuyGrid.valueAddedServicesController.schoolUniformController.init();
	}
	
	var registerEvents = function(){
		debug("[registerEvents] registering events in standard buy grid......");
		thisStandardBuyGrid.featureTypeController.registerEvents();
		thisStandardBuyGrid.sizeColorController.registerEvents();
		thisStandardBuyGrid.hemmingController.registerEvents();
		thisStandardBuyGrid.valueAddedServicesController.monogramController.registerEvents();
		thisStandardBuyGrid.valueAddedServicesController.schoolUniformController.registerEvents();
		thisStandardBuyGrid.dropShipController.registerEvents();
		thisStandardBuyGrid.quantityController.registerEvents();
    	thisStandardBuyGrid.shoppingBagController.registerEvents();
	}
	
	this.setupDefaultSelections = function(){
		    debug("[setupDefaultSelections] setting up defaults in standard buy grid......");
			if (requestedFeature != undefined && requestedFeature != null) {
				selection.style = requestedFeature.getFirstStyle();
			}
			else {
				selection.style = product.getRootFeature().getFirstStyle(); // set just for updateSelectionBasedOnSelectedStyle method call
			}
			debug("[setupDefaultSelections] style selected ...." + selection.style.getNumber());
			thisStandardBuyGrid.featureTypeController.updateSelectionBasedOnSelectedStyle(); // get default features for default style
			selection.style = null; // default back to null, will be set by selectFeature method call
			thisStandardBuyGrid.featureTypeController.selectFeature(selection.primaryFeatureId,selection.secondaryFeatureId,selection.thirdFeatureId); // initialize style on view
			thisStandardBuyGrid.sizeColorController.colorSelect(null); // setup default color is there is one
			if (selection.style != null && selection.style.getInseamable()) {
				thisStandardBuyGrid.hemmingController.inseamSelect(null);
				thisStandardBuyGrid.hemmingController.cuffingSelect(null);	
			}
			thisStandardBuyGrid.quantityController.quantitySelect(1);
			
			thisStandardBuyGrid.dropShipController.resetDropShipData();
			thisStandardBuyGrid.valueAddedServicesController.monogramController.selectMonogram(false);
		
			thisStandardBuyGrid.shoppingBagController.checkAddToBagState();

	}
	
	// called any time the style on the view has changed
	var styleChange = function(){
		updateDebugContext();
		debug("[style Change].... ");
		broadcastStyleChangeEvent();
		(product.isGCProduct()) ? thisStandardBuyGrid.giftCardExtensionController.giftCardImageController.styleChangeViewer(selection.style):thisStandardBuyGrid.productPhotoViewerController.styleChangeViewer();
		thisStandardBuyGrid.sizeColorController.compareSelectionToSku(); // try to find a SKU with just style and possibility color
		thisStandardBuyGrid.sizeColorController.styleChangeSizeColor(); // show the color color chip group for the new style
		thisStandardBuyGrid.hemmingController.styleChangeHemming();	
		thisStandardBuyGrid.hemmingController.skuChangeHemming();	
		thisStandardBuyGrid.valueAddedServicesController.monogramController.styleChangeMonogram();
		thisStandardBuyGrid.promoController.styleChangePromo();

		if (selection.productNumber != null && !prodViewNs.GCConstants.GCProduct(selection.productNumber)) {
			thisStandardBuyGrid.webAnalyticsController.sendStyleChangeEvents();
		}
	}

	var broadcastStyleChangeEvent = function(){
		debug("[broadcastStyleChangeEvent].... ");
		if (styleChangeCallbacks != null) {
			for(var k =0; k < styleChangeCallbacks.length; k++){
				styleChangeCallbacks[k].call(thisStandardBuyGrid, product, selection.style);
			}
		}
	}

	var broadcastSchoolChangeEvent = function(){
		debug("[broadcastSchoolChangeEvent].... ");
		if (schoolChangeCallbacks != null) {
			for(var k =0; k < schoolChangeCallbacks.length; k++){
				schoolChangeCallbacks[k].call(thisStandardBuyGrid, product, selection.style);
			}
		}
	}
	
	
	var broadcastColorChangeEvent = function(){
		debug("[broadcastColorChangeEvent]...... ");
		if (colorChangeCallbacks != null){
			for(var c=0; c < colorChangeCallbacks.length; c++){
				colorChangeCallbacks[c].call(thisStandardBuyGrid, product, selection.colorCode);
			}
		}
	}
	
	var broadcastCancelUpdateEvent = function(){
		debug("[broadcastColorChangeEvent]...... ");
		if (cancelUpdateBagCallbacks != null){
			for(var c=0; c < cancelUpdateBagCallbacks.length; c++){
				cancelUpdateBagCallbacks[c].call(thisStandardBuyGrid, product, selection.colorCode);
			}
		}
	}
	
	this.setRequestedView = function(viewId) {	
		debug("[setRequestedView].... ");
		 var featureBasedOnViewId = product.findBestFeatureMatch(viewId, null, null);
		 if (featureBasedOnViewId  != undefined && featureBasedOnViewId != null) {
			 requestedFeature = featureBasedOnViewId;
			 //init();
			 thisStandardBuyGrid.featureTypeController.selectFeature(featureBasedOnViewId.getFeatureNumber(), null, null);
		 }
	}
	
	this.registerSchoolSelectionUnsetCallbacks = function(callback) {
		debug("[registerSchoolSelectionUnsetCallbacks]..... ");
		schoolSelectionUnsetCallbacks.push(callback);
	}
	
	this.registerCallbackForColorChange = function(callback){
		debug("[registerCallbackForColorChange]..... ");
		colorChangeCallbacks.push(callback);
	}
	
	this.registerCallbackForShoppingBag = function(callback){
		debug("[registerCallbackForShoppingBag].... ");
		shoppingBagCallbacks.push(callback);
	}	
	
	this.registerCallbackForCancelUpdateBag = function(callback){
		debug("[registerCallbackForCancelUpdateBag].... ");
		cancelUpdateBagCallbacks.push(callback);
	}
	
	this.registerCallbackForSchoolChange = function(callback){
		debug("[registerCallbackForSchoolChange].... ");
		schoolChangeCallbacks.push(callback);
	}
	
	this.registerCallbackForStyleChange = function(callback){
		debug("[registerCallbackForStyleChange].... ");
		styleChangeCallbacks.push(callback);
	}
	
	
	// Called any time the color selection of the product changes.
	var previousColorCodeForColorChange = null;
	var previousStyleCodeForColorChange = null;
	var colorChange = function(colorCode){
		if(previousStyleCodeForColorChange != selection.style || previousColorCodeForColorChange != colorCode){
			updateDebugContext();
			debug("[colorChange].... ");
			thisStandardBuyGrid.productPhotoViewerController.setPhotoViewerColorCode(colorCode);
			setTimeout(thisStandardBuyGrid.productPhotoViewerController.updateViewerColor, 1000);
		}
		broadcastColorChangeEvent();
		thisStandardBuyGrid.valueAddedServicesController.monogramController.skuChangeMonogram();
		
		if(! thisStandardBuyGrid.sizeColorController.getColorHoverActive()){
			thisStandardBuyGrid.valueAddedServicesController.schoolUniformController.setupCustomSchoolLogos();
		}			
		
		previousColorCodeForColorChange = colorCode;
		previousStyleCodeForColorChange = selection.style;
	}	
	
	// called any time the SKU on the view has changed
	var skuChange = function(){
		updateDebugContext();
		debug("[skuChange].... ");
		thisStandardBuyGrid.hemmingController.skuChangeHemming();
		thisStandardBuyGrid.valueAddedServicesController.monogramController.skuChangeMonogram();
	}

	this.resetBuyGrid = function(){
		debug("[resetBuyGrid].... ");
		selection = new prodViewNs.Selection(product.getNumber());
		if (thisStandardBuyGrid.giftCardExtensionController != undefined && thisStandardBuyGrid.giftCardExtensionController != null) {
			thisStandardBuyGrid.giftCardExtensionController.resetSelectionObject(selection);
		}
		thisStandardBuyGrid.setupDefaultSelections();		
		
		if(globalManager.getNonCustomSchool() != null){
			thisStandardBuyGrid.valueAddedServicesController.schoolUniformController.processSchoolLookup(globalManager.getNonCustomSchool());
		}else{ // check for possible custom school
			thisStandardBuyGrid.valueAddedServicesController.schoolUniformController.init();
		}
	}
	
	this.cancelUpdateBag = function(){
		broadcastCancelUpdateEvent();
	}
	
	var updateDebugContext = function(){
		debugContext = "";
		debugContext = debugContext + "(";
		if(selection.style != null && selection.style.getNumber() != null){
			debugContext = debugContext + selection.style.getNumber();
		}
		debugContext = debugContext + "/";
		if(selection.colorCode != null){
			debugContext = debugContext + selection.colorCode;
		}	
		debugContext = debugContext + "/";
		if(selection.sizeCode != null){
			debugContext = debugContext + selection.sizeCode;
		}	
		debugContext = debugContext + "/";
		if(selection.sku != null && selection.sku.getNumber() != null){
			debugContext = debugContext + selection.sku.getNumber();
		}			
		debugContext = debugContext + ")";
	}
	
	var debug = function(logStatement){
		$.debug(logStatement + debugContext);
	}
	
	this.promoController = new function(){
		var view = null;
		
		this.init = function(){
			view = standardBuyGridView.promoView;
		}
		
		this.styleChangePromo = function(){
			view.displayPromoText(selection.style.getFeatureTreeLeaf().getPromoText());
		}
	}
	
	this.shoppingBagController = new function(){
		debug("[shoppingBagController].... ");
		var inlineBagController = new prodViewNs.InlineShoppingBagController();
		var response = null;
		var modal = null;
		var redirectToShoppingBag = null;
		
		this.redirectToShoppingBag = function(flag){
			redirectToShoppingBag = flag;
		}
		
		var keepShoppingAction = function(){
			debug("[keepShoppingAction].... ");		
			modal.trigger("hide");
		}
		var inlineShoppingClose = function(){
			debug("[inlineShoppingClose].... ");
			if(buyGridContext === "PP"){
				thisStandardBuyGrid.webAnalyticsController.bypassSendStyleEvent(true);
				var ref = response.selections[0];
				thisStandardBuyGrid.resetBuyGrid();
			    if (product.getParentProduct() != null) { 
			    	var itemIdHolder = ref.itemId;
			    	ref.itemId = null;
					thisStandardBuyGrid.makeBuyGridSelections(ref);
					ref.itemId = itemIdHolder;
				}
				thisStandardBuyGrid.webAnalyticsController.bypassSendStyleEvent(false);
				
				// We use this trick to give this method call its own thread of execution that should fire right after this close method. 
				// This approach solves problem related to recursive method calls placed by UI JavaScript components. 
				if(product.getParentProduct() != null && response.shoppingBag != null){	
					setTimeout(function(){broadcastShoppingBagEvent("closeInlineBag",response.selections[0],response.shoppingBag);},1);
				}
			}
		}
		
		this.setToUpdateMode = function(){
			debug("[setToUpdateMode].... ");	
			standardBuyGridView.addToBagView.setUpdateMode(product.getParentProduct() != null);
		}
				
		
		this.registerEvents = function(){
			debug("[shoppingBagController - registerEvents].... ");	
			standardBuyGridView.addToBagView.registerEvents();
		}
		
		this.errorChecker = function(displayIndicator){
			debug("[shoppingBagController - errorChecker].... ");
			var errors = new Array();
			if(! $.cookie.test()){
				errors.push(prodViewNs.Messages.findMessage(22));
			}

			thisStandardBuyGrid.sizeColorController.errorChecker(displayIndicator,errors);
			thisStandardBuyGrid.hemmingController.errorChecker(displayIndicator,errors);			
			
			var monoCurrentStep = thisStandardBuyGrid.valueAddedServicesController.monogramController.getCurrentStep();
			if(thisStandardBuyGrid.valueAddedServicesController.monogramController.isMonogramApplied()){
				thisStandardBuyGrid.valueAddedServicesController.monogramController.errorChecker(displayIndicator,monoCurrentStep,errors);
				if(monoCurrentStep < 3){
					thisStandardBuyGrid.valueAddedServicesController.monogramController.errorChecker(displayIndicator,monoCurrentStep+1,errors);
				}
				if(errors.length == 0 && ! selection.monogramApplied){
					errors.push(prodViewNs.Messages.findMessage(7));
				}
			}
			thisStandardBuyGrid.valueAddedServicesController.errorChecker(displayIndicator,errors);	
			thisStandardBuyGrid.valueAddedServicesController.schoolUniformController.errorChecker(displayIndicator,errors,true);			
			thisStandardBuyGrid.dropShipController.errorChecker(displayIndicator,errors);
			if (product.isGCProduct()) thisStandardBuyGrid.giftCardExtensionController.errorChecker(displayIndicator,errors);
			
			return errors;
		}	
		
		this.checkAddToBagState = function(){
			debug("[checkAddToBagState].... ");
			var errors = this.errorChecker(false);
			var updateMode = (selection.mode == "update");
			if(errors.length > 0){
				standardBuyGridView.addToBagView.disableAddToBag(updateMode);
			}else{
				standardBuyGridView.addToBagView.enableAddToBag(updateMode);
			}
		}
		
		var broadcastShoppingBagEvent = function(eventType,selectionFromResponse,shoppingBag){
			debug("[broadcastShoppingBagEvent].... ");
			if (shoppingBagCallbacks != null) {
				for(var k =0; k < shoppingBagCallbacks.length; k++){
					shoppingBagCallbacks[k].call(null,eventType,thisStandardBuyGrid, selectionFromResponse,shoppingBag);
				}
			}
		}		
		
		this.removeItemFromBag = function(itemId,successCallback,errorCallback){

			var removeUrl = "/co/RemoveItem";
			
			var posCallBack = function(response){
				successCallback.call(null,response);
				broadcastShoppingBagEvent("removed");
				com.landsend.persistentBag.controller.updateBagDisplay();
			}

			$.ajax({url:removeUrl,
				async:false,
				type:"POST",
				dataType:"json",
				data: {functionName:'removeItem', itemKey:itemId, removeType:"removeItem", insecure: (location.pathname.indexOf("/co/ShoppingBag.html") == -1), debug:($.query.get("debug")==="true")},
				timeout:10000,
				error:errorCallback,
				success:posCallBack,
				cache:false
			});					
		}
		
		this.addToBag = function(){
			debug("[addToBag].... ");
			var errors = this.errorChecker(true);
			if(errors.length > 0){
				debug("[addToBag] - errors - " + errors.length);
				return;
			}
			
//			standardBuyGridView.addToBagView.showProcessingHandler();
			response = null;
			var selections = new Array();
			selections[0] = selection;
			response = inlineBagController.addSelectionsToBag(selections,keepShoppingAction,redirectToShoppingBag);

			if(selections[0].mode == "update" && response.shoppingBag != null){
				broadcastShoppingBagEvent("update",response.selections[0],response.shoppingBag);
			}else if(selections[0].mode == "add" && response.shoppingBag != null){
				setTimeout(function(){broadcastShoppingBagEvent("add",response.selections[0],response.shoppingBag);},1000);
			}			
			
			if(product.getParentProduct() != null) {
				completeAddToBag(completeAddToBag); //We have to keep this call here as it needs to be completed before we reset buyGrid
				thisStandardBuyGrid.webAnalyticsController.bypassSendStyleEvent(true);
				var ref = response.selections[0];
				thisStandardBuyGrid.resetBuyGrid();
			    if (buyGridContext === "PP" && product.getParentProduct() != null) { 
			    	var itemIdHolder = ref.itemId;
			    	ref.itemId = null;
					thisStandardBuyGrid.makeBuyGridSelections(ref);
					ref.itemId = itemIdHolder;
				}			    
			    thisStandardBuyGrid.webAnalyticsController.bypassSendStyleEvent(false);
			}
			else {
				completeAddToBag(completeAddToBag);
			}		
			
//			standardBuyGridView.addToBagView.hideProcessingHandler();	
		}
		
		var completeAddToBag = function(){
			if(response.loaded){
				debug("[addToBag].... response loaded");
				leutil.ui.modalHandler.hideAll();
				if(selection.mode == "add"){
					inlineBagController.loadRecommendations(selection, response);					

					standardBuyGridView.addToBagView.showInlineBag(response.id);
					modal = leutil.ui.modalHandler.show({
						content:response.shoppingBag.htmlMap.inlineBag,
						cssClass:"pp-add-to-bag-modal",
						width:600,
						onHide:inlineShoppingClose
					});
					
					if (typeof printBagContainer != 'undefined' && printBagContainer == "C") {
						$("#add-to-bag-test").show();
					} else {
						$("#add-to-bag-control").show();				
					}
				}
				inlineBagController.registerRecommendationEvents(selection.style.getCatalogNumber().getMediaCode());
				inlineBagController.getView().setKeepShoppingButtonCallBack(keepShoppingAction);
				thisStandardBuyGrid.webAnalyticsController.sendAddToBagMetric(response);
			}
		}
	}
	
	this.valueAddedServicesController = new function(){
		var thisVasController = this;
		
		/**
		 * This method is called when-ever a value added service is added/selected or removed at a high level.
		 */
		var valueAddedServiceChange = function(){
			debug("[valueAddedServiceChange] - mono logo check");
			var errors = thisVasController.errorChecker();
			for(var i = 0;i < errors.length;i++){
				if(errors[i].id == 18){  // check for both a monogram and logo
					leutil.ui.modalHandler.show({
						content:errors[i].text,
						cssClass:"le-modal-alert",
						dialogue:true,
						scrollable:false
					});
				}
			}
			
			if(! thisVasController.monogramController.isMonogramApplied() && selection.schoolLogoCode != null){ 
				standardBuyGridView.monogramView.hideMonogramVas();
			}else if(!selection.style.getMonogramable()){
				standardBuyGridView.monogramView.hideMonogramVas();
			}else{
				standardBuyGridView.monogramView.showMonogramVas();
			}

			if(product.getSchoolProduct() != null && product.getSchoolProduct().getSchoolProductColors() != null && product.getSchoolProduct().getSchoolProductColors()[selection.colorCode] != null){
				var schoolProductColor = product.getSchoolProduct().getSchoolProductColors()[selection.colorCode];
				if(schoolProductColor.monoRequired || schoolProductColor.monoAllowed){
					standardBuyGridView.monogramView.showMonogramVas();
				}	
			}
		}
		
		this.errorChecker = function(displayIndicator,errors){
			debug("[valueAddedServiceChange errorChecker]");
			if(errors == undefined){
				errors = new Array();
			}

			if(this.monogramController.isMonogramApplied() && selection.schoolLogoCode != null){
				errors.push(prodViewNs.Messages.findMessage(28));
			}
			
			if(product.getSchoolProduct() != null && product.getSchoolProduct().getSchoolProductColors() != null && product.getSchoolProduct().getSchoolProductColors()[selection.colorCode] != null && product.getSchoolProduct().getSchoolProductColors()[selection.colorCode].getMonogramAllowed() && product.getSchoolProduct().getSchoolProductColors()[selection.colorCode].getMonogramRequired()){
				if(displayIndicator){standardBuyGridView.monogramView.showErrorIconMonogram();}		
				errors.push(prodViewNs.Messages.findMessage(21));
			}
			
			return errors;
		}
		
		this.schoolUniformController = new function(){
			var schoolCookieName = "schoolNumber";
			var customSchoolCookieName = "customSchoolNumber";
			var schoolStoreNumQueryStringParam = "schoolStoreNum";
			var thisSchoolUniformController = this;
			var inFlightSchoolNumber = null;
			var invalid = false;
			var nonCustomSchool = null;
			var noLogoItem = false;
			
			this.init = function(){
				debug("[schoolUniformController - init]");
				standardBuyGridView.schoolUniformView.checkSchoolUniform(false);
				if(selection.style.isSchoolUniform()){
					debug("[schoolUniformController - init] custom school");
					standardBuyGridView.schoolUniformView.setSchoolUniformNumberField("");
					if(product.getSchool() != null){
						setupCustomSchool();
						this.setupCustomSchoolLogos();
				    	var schoolNum = $.query.get(schoolStoreNumQueryStringParam);
				    	debug("[schoolUniformController - init] schoolNum - " + schoolNum);
				    	$.cookie(schoolCookieName,null,{path: '/'});
				    	if(schoolNum != null && schoolNum != undefined && schoolNum != "" ){   		
			        		$.cookie(customSchoolCookieName,schoolNum,{path: '/'});
			        		selection.schoolNumber = schoolNum;
				    	}
					}else{
						debug("[schoolUniformController - init] non-custom school");
						var savedCode = $.cookie(schoolCookieName);
						debug("[schoolUniformController - init] savedCode - " + savedCode);
						$.cookie(customSchoolCookieName,null,{path: '/'});
			    		if(savedCode != null && savedCode != undefined && savedCode != ""){
			    			this.selectFindSchool(savedCode);    	
			    			selection.schoolNumber = savedCode;
			        	}				
					}
				}
			}

			this.errorChecker = function(displayIndicator,errors,addToBag){
				debug("[schoolUniformController - errorChecker]");
				if(errors == undefined){
					errors = new Array();
				}
				if(!selection.style.isSchoolUniform()){
					return errors;
				}
				if(addToBag == null || addToBag == undefined){
					addToBag = false;
				}
	
				debug("[schoolUniformController - errorChecker] check for invalid school finder state");
				if(nonCustomSchool == null && (product.getSchoolProduct() == null || inFlightSchoolNumber == "")){
					if(invalid){ 
						debug("[schoolUniformController - errorChecker] confirm pushed, but code was invalid (null or bad return from ajax)");
						if(displayIndicator){standardBuyGridView.schoolUniformView.showErrorIconSchoolNumber();}
						errors.push(prodViewNs.Messages.findMessage(19));
					}else if(inFlightSchoolNumber != null && inFlightSchoolNumber.length == 0){ 
						debug("[schoolUniformController - errorChecker] no school number entered, but school search check box selected");
						if(displayIndicator){standardBuyGridView.schoolUniformView.showErrorIconSchoolNumber();}
						errors.push(prodViewNs.Messages.findMessage(19))				
					}else if(addToBag && ! invalid && inFlightSchoolNumber != null && inFlightSchoolNumber.length > 0){  
						debug("[schoolUniformController - errorChecker] school number entered but confirm not pressed");
						if(displayIndicator){standardBuyGridView.schoolUniformView.showErrorIconSchoolNumber();}
						errors.push(prodViewNs.Messages.findMessage(19));
					}
				}
				debug("[schoolUniformController - errorChecker] check to make sure a logo is applied if user has not indicated one or opted out ");
				if(addToBag && ! noLogoItem && selection.schoolLogoCode == null && product.getSchoolProduct() != null && product.getSchoolProduct().getSchoolProductColors() != null && product.getSchoolProduct().getSchoolProductColors()[selection.colorCode] != null && product.getSchoolProduct().getSchoolProductColors()[selection.colorCode].getLogos().length > 0){
					if(displayIndicator){standardBuyGridView.schoolUniformView.showErrorIconSchoolUniformLogo();}		
					errors.push(prodViewNs.Messages.findMessage(20));
				}else if(addToBag && ! noLogoItem && selection.schoolLogoCode == null && nonCustomSchool != null && nonCustomSchool.logoList.length > 0){
					if(displayIndicator){standardBuyGridView.schoolUniformView.showErrorIconSchoolUniformLogo();}
					errors.push(prodViewNs.Messages.findMessage(20));
				}					
				
				return errors;
			}
			
			this.onSchoolNumberChange = function(value){
				debug("[schoolUniformController - onSchoolNumberChange] - " + value);
				invalid = false;
				if(value == null || value == undefined){
					value = "";
				}else if(value == "" || value.length < 1){
					standardBuyGridView.schoolUniformView.hideErrorIconSchoolNumber();
				}else if(! value.match("^[0-9]*$")){
					value = inFlightSchoolNumber;
				}
				standardBuyGridView.schoolUniformView.setSchoolUniformNumberField(value);
				inFlightSchoolNumber = value;
			}
			
			this.selectSchoolUniform = function(isSchoolUniform){
				debug("[schoolUniformController - selectSchoolUniform] - " + isSchoolUniform);
				if(isSchoolUniform){
					standardBuyGridView.schoolUniformView.checkSchoolUniform(true);
					standardBuyGridView.schoolUniformView.showParentSchoolUniformContainer();
					if(nonCustomSchool != null || product.getSchool() != null){
						debug("[schoolUniformController - selectSchoolUniform] Custom School");
						standardBuyGridView.schoolUniformView.hideSchoolUniformFinder();
						standardBuyGridView.schoolUniformView.showSchoolUniformWidget();
						inFlightSchoolNumber = null;
					}else{
						debug("[schoolUniformController - selectSchoolUniform] Non Custom School");
						standardBuyGridView.schoolUniformView.showSchoolUniformFinder();
						standardBuyGridView.schoolUniformView.hideSchoolUniformWidget();
						inFlightSchoolNumber = "";
					}
				}else{
					if(product.getSchool() != null){
						debug("[schoolUniformController - selectSchoolUniform] Custom School");
		        		$.cookie(customSchoolCookieName,null,{path: '/'});
		        		$.cookie(schoolCookieName,null,{path: '/'});
		        		selection.schoolNumber = null;
		        		selection.schoolLogoCode = null;
					}else{
						debug("[schoolUniformController - selectSchoolUniform] Non Custom School");
						standardBuyGridView.schoolUniformView.hideChangeSchoolButton();
						standardBuyGridView.schoolUniformView.checkSchoolUniform(false);
						standardBuyGridView.schoolUniformView.hideParentSchoolUniformContainer();
						$.cookie(schoolCookieName,null,{path: '/'});
						selection.schoolNumber = null;
						selection.schoolLogoCode = null;
						noLogoItem = false;
						nonCustomSchool = null;
						invalid = false;
						globalManager.setNonCustomSchool(null);						
					}	
					inFlightSchoolNumber = null;
					if (schoolSelectionUnsetCallbacks != null && schoolSelectionUnsetCallbacks != undefined &&
							schoolSelectionUnsetCallbacks.length > 0) {
						for(var k =0; k < schoolSelectionUnsetCallbacks.length; k++){
							schoolSelectionUnsetCallbacks[k].call(thisSchoolUniformController, selection, schoolStoreNumQueryStringParam);
						}
					}					
				}
				standardBuyGridView.schoolUniformView.setSchoolUniformNumberField("");
			}
			
			this.registerEvents = function(){
				debug("[schoolUniformController - registerEvents]");
				standardBuyGridView.schoolUniformView.registerEvents();
			}		
			
			var setupCustomSchool = function(){
				debug("[schoolUniformController - setupCustomSchool]");
				standardBuyGridView.schoolUniformView.hideChangeSchoolButton();
	    	    thisSchoolUniformController.selectSchoolUniform(true);
	    	    thisSchoolUniformController.setupCustomSchoolLogos();
	        	standardBuyGridView.schoolUniformView.showSchoolUniformWidget();
	        	standardBuyGridView.schoolUniformView.hideSchoolUniformFinder();			
	        	standardBuyGridView.schoolUniformView.setSchoolNumber(product.getSchool().getCode());
	        	standardBuyGridView.schoolUniformView.setSchoolName(product.getSchool().getName()); 
	        	selection.schoolNumber = product.getSchool().getCode();
			}
			
			this.setupCustomSchoolLogos = function(){
				debug("[schoolUniformController - setupCustomSchoolLogos]");
				if(product.getSchoolProduct() == null){
					return;
				}
				standardBuyGridView.schoolUniformView.hideSchoolUniformLogoPreviewArea();	
				var schoolProductColor = product.getSchoolProduct().getSchoolProductColors()[selection.colorCode];
				var allowable = false;
				if (schoolProductColor.getLogos().length > 0 && (schoolProductColor.getLogos().length != 1 || schoolProductColor.getLogoAllowed())){
					allowable = true;
				}
				debug("[schoolUniformController - setupCustomSchoolLogos] allowable - " + allowable);
				standardBuyGridView.schoolUniformView.setupLogoSelection(schoolProductColor.getLogos(),schoolProductColor.getLogoRequired(),allowable);
	            if(schoolProductColor.getLogoRequired() && schoolProductColor.getLogos().length == 1) {
	            	this.selectLogo(schoolProductColor.getLogos()[0].getCode());
	    		}	
	            debug("[schoolUniformController - setupCustomSchoolLogos] # of Logos - " + schoolProductColor.getLogos().length);
	            if(schoolProductColor.getLogos().length > 0){
	            	standardBuyGridView.schoolUniformView.showSchoolUniformLogoSelector();
	            }else{
	            	standardBuyGridView.schoolUniformView.hideSchoolUniformLogoSelector();
	            }
	            
	            // try and match logo as user clicks through colors
	            debug("[schoolUniformController - setupCustomSchoolLogos] selection.schoolLogoCode - " + selection.schoolLogoCode);
	            if(selection.schoolLogoCode != null){
	            	var found = false;
	    			for(var i = 0;i < schoolProductColor.getLogos().length;i++){ 
	    				if(schoolProductColor.getLogos()[i].code == selection.schoolLogoCode){
	    					found = true;
	    					this.selectLogo(selection.schoolLogoCode);
	    				}
	    			}
	    			if(! found){
	    				selection.schoolLogoCode = null;
	    			}
	            }
			}
			
			this.selectChangeSchool = function(){
				debug("[schoolUniformController - selectChangeSchool]");
				// TODO: fill this guy in
				$.cookie(schoolCookieName,null,{path: '/'});
				noLogoItem = false;
				nonCustomSchool = null;
				invalid = false;
				inFlightSchoolNumber = "";
				globalManager.setNonCustomSchool(null);
				standardBuyGridView.schoolUniformView.setSchoolUniformNumberField("");
				standardBuyGridView.schoolUniformView.hideErrorIconSchoolNumber();
	        	standardBuyGridView.schoolUniformView.hideSchoolUniformWidget();
	        	standardBuyGridView.schoolUniformView.showSchoolUniformFinder();
	        	standardBuyGridView.schoolUniformView.setSchoolNumber("");
	        	standardBuyGridView.schoolUniformView.setSchoolName("");  
	        	standardBuyGridView.schoolUniformView.hideSchoolUniformBanner();	
	        	standardBuyGridView.schoolUniformView.showPeferredSchoolCheckboxContainer();
			}
			
			this.selectFindSchool = function(schoolNumber){
				debug("[schoolUniformController - selectFindSchool] " + schoolNumber);
				if(typeof schoolNumber == "number"){
					schoolNumber = new String(schoolNumber);
				}
				schoolNumber = $.trim(schoolNumber);
				if(schoolNumber !== "" && schoolNumber.match("^[0-9]*$")){
					nonCustomSchool = null;
					standardBuyGridView.schoolUniformView.hideErrorIconSchoolNumber();
					selection.schoolNumber = schoolNumber;
		            var schoolID = schoolNumber.substring(0,schoolNumber.length-1);
		            var checkDigit = schoolNumber.substring(schoolNumber.length-1);
		            debug("[codeEntry] schoolID=" + schoolID + " checkDigit=" + checkDigit);
					DWREngine.setAsync(false);				
					debug("[codeEntry] before findSchoolBySchoolNumber");
		        	JSchoolFacade.findSchoolBySchoolNumber(schoolID, checkDigit,{
		        		callback:thisSchoolUniformController.processSchoolLookup,
		        		timeout:10000,
		        		errorHandler:processSchoolUniformAjaxError
		        	});	   
		        	debug("[codeEntry] after findSchoolBySchoolNumber");
		        	DWREngine.setAsync(true);		
		        	
				}else{
					debug("[schoolUniformController - selectFindSchool] invalid school code");
					invalid = true;
					thisSchoolUniformController.errorChecker(true);
					$.cookie(schoolCookieName,null,{path: '/'});
				}
				standardBuyGridView.schoolUniformView.setSchoolUniformNumberField(schoolNumber);
			}
			
			this.processSchoolLookup = function(school){
				debug("[schoolUniformController - processSchoolLookup] " + school);
		        if (school !== null && typeof school == "object") {
		        	inFlightSchoolNumber = null;
		        	standardBuyGridView.schoolUniformView.setSchoolUniformNumberField("");
		        	debug("[buildLogoList] name=" + school.name + " code=" + school.code + " length=" + school.logoList.length);
		        	nonCustomSchool = school;
		        }else{
		        	nonCustomSchool = null;
		        	invalid = true;
		        	thisSchoolUniformController.errorChecker(true);
		            return;
		        }
		        
		        if(school.productionSchoolStore != null && typeof (school.productionSchoolStore) == "object") {
		        	debug("[schoolUniformController - processSchoolLookup] custom school then jump to school landing page");
		        	$.cookie(schoolCookieName,null,{path: '/'});
		        	$.cookie(customSchoolCookieName,selection.schoolNumber,{path: '/'});
		        	window.location = "/ix/school-uniforms/index.html?tab=13&seq=1&page=1&pageSize=12&store=le&schoolStoreNum="+selection.schoolNumber;
		        	return;
		        } 
		        
	        	var savedCode = $.cookie(customSchoolCookieName);
	        	if(savedCode != null && savedCode != "") {
	        		debug("[schoolUniformController - processSchoolLookup] searching a non custom school in custom product page redirect to non custom product page ");
	        		$.cookie(customSchoolCookieName,null,{path: '/'});
	        		$.cookie(schoolCookieName,selection.schoolNumber,{path: '/'});
	        		window.location = window.location.pathname + $.query.REMOVE(schoolStoreNumQueryStringParam);
	        		return;
	        	}
	        	broadcastSchoolChangeEvent();
	        	globalManager.setNonCustomSchool(school);
	        	selection.schoolNumber = school.code;
	        	debug("[schoolUniformController - processSchoolLookup] school code " + school.code);
	        	$.cookie(schoolCookieName,selection.schoolNumber,{path: '/'});
	        	
	    	    if(school.logoList.length > 0){standardBuyGridView.schoolUniformView.showSchoolUniformLogoSelector();
	    	    }else{standardBuyGridView.schoolUniformView.hideSchoolUniformLogoSelector();}        	
	        	
	    	    var dressCodeUrl = "/pdfs/school/"+selection.schoolNumber+".pdf";
	    	    debug("[schoolUniformController - processSchoolLookup] pdf check");
	    	    if(leutil.net.URLExists(dressCodeUrl)){
	    	    	standardBuyGridView.schoolUniformView.setupSchoolUniformDressCode(dressCodeUrl);
	    	    }else{
	    	    	standardBuyGridView.schoolUniformView.setupSchoolUniformDressCode(null);
	    	    }
	    	    
	    	    thisSchoolUniformController.selectSchoolUniform(true);
	    	    standardBuyGridView.schoolUniformView.setupLogoSelection(school.logoList,false,true);
	        	standardBuyGridView.schoolUniformView.showSchoolUniformWidget();
	        	standardBuyGridView.schoolUniformView.hideSchoolUniformFinder();
	        	//Show the school banner only if we are within a custom school. Non custom schools will not have a banner displayed. 
	        	if(school.productionSchoolStore != null && typeof (school.productionSchoolStore) == "object") {
	        		standardBuyGridView.schoolUniformView.setSchoolNumber(selection.schoolNumber);
	        		standardBuyGridView.schoolUniformView.setSchoolName(school.name); 	        	
	        		standardBuyGridView.schoolUniformView.showSchoolUniformBanner();
	        	}
	        	standardBuyGridView.schoolUniformView.hideSchoolUniformLogoPreviewArea();
			}
			
			this.selectLogo = function(logoCode){
				debug("[schoolUniformController - selectLogo] logoCode - " + logoCode);
				if(logoCode == null || logoCode == undefined || logoCode.length < 1 || logoCode == "-1"){
					selection.schoolLogoCode = null;		
					standardBuyGridView.schoolUniformView.hideSchoolUniformLogoPreviewArea();	
					standardBuyGridView.schoolUniformView.setLogo("");
					noLogoItem = false;
				}else if(logoCode == "-2"){
					standardBuyGridView.schoolUniformView.hideErrorIconSchoolUniformLogo();
					selection.schoolLogoCode = null;
					standardBuyGridView.schoolUniformView.setLogo("-2");
					standardBuyGridView.schoolUniformView.setSchoolUniformLogoImageUrl(null);
					noLogoItem = true;
				}else{
					standardBuyGridView.schoolUniformView.hideErrorIconSchoolUniformLogo();
					noLogoItem = false;
					selection.schoolLogoCode = logoCode;	
					standardBuyGridView.schoolUniformView.setLogoNumberText(logoCode);
		            var imgSrc = "/images/school/"+logoCode+".jpg";
		            debug("[schoolUniformController - selectLogo] url exists check");
		            if (leutil.net.URLExists(imgSrc)) { 	
		            	standardBuyGridView.schoolUniformView.setSchoolUniformLogoImageUrl(imgSrc);
		            	standardBuyGridView.schoolUniformView.hideSchoolUniformMissingLogoMessage();
		            } else {
		            	standardBuyGridView.schoolUniformView.setSchoolUniformLogoImageUrl(null);
		            	standardBuyGridView.schoolUniformView.showSchoolUniformMissingLogoMessage();
		            }
		            standardBuyGridView.schoolUniformView.showSchoolUniformLogoPreviewArea();		
		            standardBuyGridView.schoolUniformView.setLogo(logoCode);
				}
				valueAddedServiceChange();
			}
			
			var processSchoolUniformAjaxError = function(error){
				debug("[schoolUniformController - processSchoolUniformAjaxError]");
	        	invalid = true;
	        	thisSchoolUniformController.errorChecker(true);
	        	
	        	leutil.ui.modalHandler.show({
					content:prodViewNs.Messages.findMessage(29).text,
					cssClass:"le-modal-alert",
					dialogue:true,
					scrollable:false
				});
	        	
	        	throw error;
			}
		}	
	 
		this.monogramController = new function(){
			var baseUrl = "/images/monogram/"; // base URL for monogram images
			var clearImageUrl = "/images/clear.gif";
			var currentStep = null;
			var inUpdateReviewMode = false;
			
			this.isMonogramApplied = function(){
				if(selection.monogramApplied){
					return true;
				}
				if(! selection.monogramApplied && currentStep != null && currentStep < 4){
					return true;
				}
				return false;
			}
			
			this.getCurrentStep = function(){
				return currentStep;
			}
			
			this.init = function(){
				standardBuyGridView.monogramView.checkMonogram(false);	
				this.selectMonogram(false);
			}
			
			this.styleChangeMonogram = function(){
				if(selection.monogramApplied){
					if(! selection.style.getMonogramable()){
						leutil.ui.modalHandler.show({
							content:prodViewNs.Messages.findMessage(24).text,
							cssClass:"le-modal-alert",
							dialogue:true,
							scrollable:false
						});
					}else{		
						leutil.ui.modalHandler.show({
							content:prodViewNs.Messages.findMessage(23).text,
							cssClass:"le-modal-alert",
							dialogue:true,
							scrollable:false
						});
					}
				}
				
				inUpdateReviewMode = false;
				// TODO: I have no idea what the requirements are for style change
				if(selection.style.getMonogramable()){
					standardBuyGridView.monogramView.showMonogramVas();
					standardBuyGridView.monogramView.setMonogramPrice(selection.style.getMonogramPrice());
				}else{
					standardBuyGridView.monogramView.hideMonogramVas();
				}
				findThreadColor();	
				if(selection.threadColor != null){
					standardBuyGridView.monogramView.setMonogramThreadColor(selection.threadColor);
				}
				this.selectMonogram(false);
			}	
			
			this.skuChangeMonogram = function(){
				findThreadColor();
				if(selection.threadColor != null){
					standardBuyGridView.monogramView.setMonogramThreadColor(selection.threadColor);
				}			

				if(selection.monogramApplied){
					buildRecap();
				}
			}
			
			var findThreadColor = function(){
				selection.threadColor = null;
				if(selection.sku != null){
					if(selection.sku.getDefaultMonoThreadColor() != null){
						selection.threadColor = selection.sku.getDefaultMonoThreadColor().getName();
						return;
					}
				}else if(selection.colorCode != null){
					for (var i =0; i < selection.style.getSkus().length; i++) {
						if(selection.style.getSkus()[i].getColor() != null && selection.style.getSkus()[i].getColor().getCode() == selection.colorCode && selection.style.getSkus()[i].getDefaultMonoThreadColor() != null){
							selection.threadColor = selection.style.getSkus()[i].getDefaultMonoThreadColor().getName();
							return;
						}
					}
				}else if(selection.style.getSkus().length == 1 && selection.style.getSkus()[0].getDefaultMonoThreadColor() != null){
					selection.threadColor = selection.style.getSkus()[0].getDefaultMonoThreadColor().getName();
				}
			}
	
			var resetMonogramSelectionReferences = function(){
				selection.monogramApplied = false;
				selection.monogramType = null;
				selection.monogramFont = null;
				selection.monogramLocation = null;
				selection.monogramSingleInitalText  = null;
				selection.monogramWordText = null;
				selection.monogramMultiInitial = [];
				selection.monogramMultiLine = [];	
			}		
	
			var checkCharacters = function(input, monoType) {
				if(typeof(input) == "string"){
					return cleanCharactersInternal(input,monoType);
				}else if(typeof(input) == "object" && input instanceof Array){
					var newArray = new Array();
					for(var i = 0;i < input.length;i++){ 
						if(input[i] != null && input[i] != undefined){
							newArray[i] = cleanCharactersInternal(input[i],monoType)
						}
					}
					return newArray;
				}
			}
	
		    var cleanCharactersInternal = function(str, monoType) {
		       	if (monoType == 1){ // inital(s)
					var charRegEx = /^[A-Za-z]/;
		   		}else if(monoType == 2){ // word(s)
		    	    var charRegEx = /^[A-Za-z0-9#\-\s\.,\'\/&]*$/
			    }else{
			    	return false;
		       	}
		       	
		       	var buffer = "";
		       	for(var i = 0;i < str.length;i++){ 
		       		var theChar = str.charAt(i);
			   		if (theChar.match(charRegEx) !== null) {
			   			buffer = buffer + theChar;
			   		} 
		       	}
		       	return buffer;
		    };			
	  	    
		    this.selectInitial = function(inputChar){
		    	inputChar = inputChar.toUpperCase();
		    	inUpdateReviewMode = false;
		    	var inputChar = checkCharacters(inputChar,1);
		    	var monogramOption = selection.style.getMonoOptionsList().findMonogramOptionByType(selection.monogramType);
		    	var monogramFont = monogramOption.findMonogramFont(selection.monogramFont);
		    	if(inputChar == null || inputChar == undefined || inputChar.length < 1){
		    		standardBuyGridView.monogramView.setMonogramSingleInitial("");
		    		standardBuyGridView.monogramView.showPreview(monogramOption.getType().getNumber(),clearImageUrl);
		    		selection.monogramSingleInitalText = null;
		    		return;
		    	}
		    	selection.monogramSingleInitalText = inputChar;
		    	standardBuyGridView.monogramView.setMonogramSingleInitial(inputChar);
		    	var imageUrl = baseUrl + monogramFont.getCode().toLowerCase() + "/" + monogramFont.getCode().toLowerCase() + "_2_" + inputChar.toLowerCase() + ".gif";
		    	standardBuyGridView.monogramView.showPreview(monogramOption.getType().getNumber(),imageUrl);
		    	clearAnyBogusStepThreeErrors();
		    }
		    
		    this.selectInitials = function(inputChar,lineNumber){
		    	inputChar = inputChar.toUpperCase();
		    	inUpdateReviewMode = false;
		    	var inputChar = checkCharacters(inputChar,1);
		    	var previewLineNumber = lineNumber + 1;
		    	var monogramOption = selection.style.getMonoOptionsList().findMonogramOptionByType(selection.monogramType);
		    	var monogramFont = monogramOption.findMonogramFont(selection.monogramFont);	    	
		    	
		    	if(monogramFont.getReverseableCode() && previewLineNumber == 3){
		    		previewLineNumber = 2;
		    	}else if(monogramFont.getReverseableCode() && previewLineNumber == 2){
		    		previewLineNumber = 3;
		    	}
		    	
		    	if(inputChar == null || inputChar == undefined || inputChar.length < 1){
		    		standardBuyGridView.monogramView.setMonogramSingleInitials("",lineNumber);
		    		standardBuyGridView.monogramView.showPreview(monogramOption.getType().getNumber(),clearImageUrl,previewLineNumber-1);
		    		selection.monogramMultiInitial[lineNumber] = null;
		    		return;
		    	}
		    	selection.monogramMultiInitial[lineNumber] = inputChar;
		    	standardBuyGridView.monogramView.setMonogramSingleInitials(inputChar,lineNumber);
		    	var imageUrl = baseUrl + monogramFont.getCode().toLowerCase() + "/" + monogramFont.getCode().toLowerCase() + "_"+previewLineNumber+"_" + inputChar.toLowerCase() + ".gif";
		    	standardBuyGridView.monogramView.showPreview(monogramOption.getType().getNumber(),imageUrl,previewLineNumber-1);	
		    	clearAnyBogusStepThreeErrors();
		    }
		    
		    this.selectWord = function(inputString){
		    	inUpdateReviewMode = false;
		    	var inputString = checkCharacters(inputString,2);
		    	if(inputString == null || inputString == undefined || $.trim(inputString).length < 1){
		    		selection.monogramWordText = null;
		    		standardBuyGridView.monogramView.setMonogramWord("");
		    		return;
		    	}
		    	selection.monogramWordText = $.trim(inputString);
		    	standardBuyGridView.monogramView.setMonogramWord(inputString);
		    	clearAnyBogusStepThreeErrors();
		    }   
		    
		    this.selectMultiLine = function(inputString,lineNumber){
		    	inUpdateReviewMode = false;
		    	var inputString = checkCharacters(inputString,2);
		    	if(inputString == null || inputString == undefined || $.trim(inputString).length < 1){
		    		standardBuyGridView.monogramView.setMultiLine("",lineNumber);
		    		selection.monogramMultiLine[lineNumber] = null;
		    		return;
		    	}
		    	selection.monogramMultiLine[lineNumber] = $.trim(inputString);
		    	standardBuyGridView.monogramView.setMultiLine(inputString,lineNumber);
		    	clearAnyBogusStepThreeErrors();
		    }
		    
			this.selectMonogram = function(isMonogramed){
				inUpdateReviewMode = false;
				resetMonogramSelectionReferences();
				standardBuyGridView.monogramView.showMonoHeaderStepLinks();
				if(isMonogramed && selection.style.getMonogramable() && selection.style.getMonoOptionsList().getOptionList().length > 0){
					standardBuyGridView.monogramView.setapplyMonogramButtonDesc(false);
					selection.monogramApplied = false;
					currentStep = null;
					var options = new Array();
					for(var i = 0;i < selection.style.getMonoOptionsList().getOptionList().length;i++){ 		
						options.push(selection.style.getMonoOptionsList().getOptionList()[i].getType());	
					}					
					standardBuyGridView.monogramView.setupMonogramTypeView(options);
					this.selectMonogramType(null);
					this.selectStepOne();
					standardBuyGridView.monogramView.showMonogramContainer();
					standardBuyGridView.monogramView.checkMonogram(true);
					standardBuyGridView.monogramView.hideErrorIconMonogram();
				}else{
					this.selectStepOne();
					currentStep = null;
					standardBuyGridView.monogramView.hideMonogramContainer();
					standardBuyGridView.monogramView.checkMonogram(false);
				}
				standardBuyGridView.monogramView.hideErrorIconMonoType();
				standardBuyGridView.monogramView.hideErrorIconMonoLocation();
				standardBuyGridView.monogramView.hideErrorIconMonoFont();
				standardBuyGridView.monogramView.hideErrorIconMonoInitalsFirst(); 
				standardBuyGridView.monogramView.hideErrorIconMonoInitalsMiddle(); 
				standardBuyGridView.monogramView.hideErrorIconMonoInitalsLast(); 	
				standardBuyGridView.monogramView.hideErrorIconMonoWord(); 
				valueAddedServiceChange();
			}
			
			this.selectUpdateMonogram = function(){
				inUpdateReviewMode = true;
				if(selection.monogramApplied){
					standardBuyGridView.monogramView.setapplyMonogramButtonDesc(true);	
				}else{
					standardBuyGridView.monogramView.setapplyMonogramButtonDesc(false);						
				}
				selection.monogramApplied = false;	
				standardBuyGridView.monogramView.showMonoHeaderStepLinks();
				this.selectStepOne();
			}
			
			// if null provided - default to first in list, else if type found - set and return true, else return false
			this.selectMonogramType = function(type){
				inUpdateReviewMode = false;
				var found = true;
				if(type == null || type == undefined){
					type = null;
					found = false;
				}else if(selection.style.getMonoOptionsList().findMonogramOptionByType(type) == null){
					found = false;
				}else{
					standardBuyGridView.monogramView.hideErrorIconMonoType();
				}
				if(selection.monogramType != type){ // check to make sure we are actually changing the value
					resetMonogramSelectionReferences();
					var monogramOption = selection.style.getMonoOptionsList().findMonogramOptionByType(type);
					standardBuyGridView.monogramView.setupMonogramFontView(monogramOption.getFontList());
					standardBuyGridView.monogramView.setupMonogramLocationView(monogramOption.getFontList()[0].getLocationList()); // just grab the first list for now
					if(monogramOption.getFontList()[0].getLocationList().length == 1){ // no variable size in locations, set to default
						selection.monogramLocation = monogramOption.getFontList()[0].getLocationList()[0].getCode();
						standardBuyGridView.monogramView.setupMultiWordInputView(monogramOption.getFontList()[0].getLocationList()[0].getMaxLines(),monogramOption.getFontList()[0].getLocationList()[0].getMaxCharacters());
						standardBuyGridView.monogramView.setupWordInputView(monogramOption.getFontList()[0].getLocationList()[0].getMaxCharacters());
					}
					showCorrectMonogramInputModule(type);
					resetStep3();
				}
				selection.monogramType = type;
				var options = new Array();
				for(var i = 0;i < selection.style.getMonoOptionsList().getOptionList().length;i++){ 		
					options.push(selection.style.getMonoOptionsList().getOptionList()[i].getType());	
				}				
				standardBuyGridView.monogramView.checkMonogramType(options,type);
				return found;
			}
		
			var showCorrectMonogramInputModule = function(type){		
				standardBuyGridView.monogramView.hideSingleInitialSelector();
				standardBuyGridView.monogramView.hideMultiLineSelector();
				standardBuyGridView.monogramView.hideInitialsSelector();
				standardBuyGridView.monogramView.hideWordSelector();
				standardBuyGridView.monogramView.hideMonogramPreviewWindowInitial();
				standardBuyGridView.monogramView.hideMonogramPreviewWindowThreeInitials();
				standardBuyGridView.monogramView.hideMonogramPreviewWindowWord();
				standardBuyGridView.monogramView.hideMonogramPreviewWindowMultiLine();
				
				if(type == 1){ // single initial
					standardBuyGridView.monogramView.showSingleInitialSelector();		
					standardBuyGridView.monogramView.showMonogramPreviewWindowInitial();
				}else if(type == 2){ // initials	
					standardBuyGridView.monogramView.showInitialsSelector();	
					standardBuyGridView.monogramView.showMonogramPreviewWindowThreeInitials();
				}else if(type == 3){ // word 
					standardBuyGridView.monogramView.showWordSelector();	
					standardBuyGridView.monogramView.showMonogramPreviewWindowWord();
				}else if(type == 4){ // multi-Line	
					standardBuyGridView.monogramView.showMultiLineSelector();
					standardBuyGridView.monogramView.showMonogramPreviewWindowMultiLine();
				}
			}
			
			// if null provided return false, else if font found - set and return true, else return false
			this.selectMonogramFont = function(fontCode){
				inUpdateReviewMode = false;
				var found = null;
				var monogramOption = selection.style.getMonoOptionsList().findMonogramOptionByType(selection.monogramType);
				var monogramFont = monogramOption.findMonogramFont(fontCode);
				if(monogramFont == null){
					selection.monogramFont = null;
					found =  false;
				}else{			
					if(selection.monogramFont != fontCode){ // if making any change, clear step 3 
						resetStep3();
					}
					if(monogramFont.getName().match(/Engraving/)){ // if font engraving
						standardBuyGridView.monogramView.hidePreviewContainer();
					}else{
						standardBuyGridView.monogramView.showPreviewContainer();
						if(monogramOption.getType().getNumber() == 3 || monogramOption.getType().getNumber() == 4){
							var imageUrl = baseUrl + monogramFont.getCode().toLowerCase() + "/" + monogramFont.getCode().toLowerCase() + "_sample_name.gif";
							standardBuyGridView.monogramView.showPreview(monogramOption.getType().getNumber(),imageUrl);
						}
					}					
					
					selection.monogramFont = fontCode;
					this.selectMonogramLocation(selection.monogramLocation); // we do this to because max line / char on location might change based on font selected
					standardBuyGridView.monogramView.hideErrorIconMonoFont();
					found = true;
				}
				standardBuyGridView.monogramView.checkMonogramFont(monogramOption.getFontList(),fontCode);
				return found;
			}
			
			var resetStep3 = function(){
				standardBuyGridView.monogramView.clearAllMonoTextInput();
				selection.monogramSingleInitalText  = null;
				selection.monogramWordText  = null;
				selection.monogramMultiInitial = [];
				selection.monogramMultiLine = [];	
				standardBuyGridView.monogramView.showPreview(1,clearImageUrl);
				standardBuyGridView.monogramView.showPreview(2,clearImageUrl,0);
				standardBuyGridView.monogramView.showPreview(2,clearImageUrl,1);
				standardBuyGridView.monogramView.showPreview(2,clearImageUrl,2);
			}
			
			// if null provided return false, else if location found - set and return true, else return false
			this.selectMonogramLocation = function(locationCode){
				inUpdateReviewMode = false;
				var locationText = null;
				var found = null;
				var monogramOption = selection.style.getMonoOptionsList().findMonogramOptionByType(selection.monogramType);
				// this is here because UI folks want to show a location list before the user selects a font
				var font = null;
				if(selection.monogramFont == null){
					font = monogramOption.getFontList()[0];
				}else{
					font = monogramOption.findMonogramFont(selection.monogramFont);
				}	
				var monogramLocation = font.findMonogramLocation(locationCode);
				if(monogramLocation == null){
					selection.monogramLocation = null;
					standardBuyGridView.monogramView.checkMonogramLocation("");
					found = false;
					locationText = "";
				}else{
					if(selection.monogramLocation != locationCode){ // if making any change, clear step 3 
						resetStep3();
					}				
					if(selection.monogramLocation != locationCode && selection.monogramType == 4){ // rebuild input boxes for multi-line based on font
						standardBuyGridView.monogramView.setupMultiWordInputView(monogramLocation.getMaxLines(),monogramLocation.getMaxCharacters());
					}
					if(selection.monogramLocation != locationCode && selection.monogramType == 3){ // rebuild input box for word based on font
						standardBuyGridView.monogramView.setupWordInputView(monogramLocation.getMaxCharacters());
					}
					
					selection.monogramLocation = locationCode;
					standardBuyGridView.monogramView.displayMaxNumberCharacters(selection.monogramType,monogramLocation.getMaxCharacters());
					found = true;
					standardBuyGridView.monogramView.hideErrorIconMonoLocation();
					locationText = monogramLocation.getName();
				}	
				standardBuyGridView.monogramView.checkMonogramLocation(font.getLocationList(),locationCode,locationText);
				
				return found;
			}	
		    
		    var buildRecap = function(){
		    	var monogramOption = selection.style.getMonoOptionsList().findMonogramOptionByType(selection.monogramType);
		    	if(monogramOption == null){return;}
		    	var monogramFont = monogramOption.findMonogramFont(selection.monogramFont);
		    	if(monogramFont == null){return;}
		    	var monogramLocation = monogramFont.findMonogramLocation(selection.monogramLocation);
		    	standardBuyGridView.monogramView.setMonogramRecapTextType(monogramOption.getType().getName());
				if(selection.monogramType == 1){ // initial
					standardBuyGridView.monogramView.setMonogramRecapTextContent(selection.monogramSingleInitalText);
				}else if(selection.monogramType == 2){ // initials	
					standardBuyGridView.monogramView.setMonogramRecapTextContent(selection.monogramMultiInitial.join(""));
				}else if(selection.monogramType == 3){ // world 	
					standardBuyGridView.monogramView.setMonogramRecapTextContent(selection.monogramWordText);
				}else if(selection.monogramType == 4){ // multi word
					standardBuyGridView.monogramView.setMonogramRecapTextContent(selection.monogramMultiLine);
				}
				var monoFontStirng = 'undefined';
				if (monogramFont != null && monogramFont != undefined){ monoFontString = monogramFont.getName();}
				standardBuyGridView.monogramView.setMonogramRecapFontContent(monoFontString);
				var monoLocString = 'undefined';
				if (monogramLocation != null && monogramLocation != undefined){ monoLocString = monogramLocation.getName();}				
				standardBuyGridView.monogramView.setMonogramRecapLocationContent(monoLocString);
				if(selection.threadColor != null){
					standardBuyGridView.monogramView.setMonogramRecapThreadContent(selection.threadColor);
				}
		    }
			
			this.selectApplyUpdateOrMonogram = function(){
				var errors = this.errorChecker(true,3);
				var isValid = true;
				
				if(errors.length > 0){
					 // show modal window with all errors, should only be a single message for min/max length, invalid char message would already be on the screen
					isValid = false;
				}else{			
					currentStep = 4;
					selection.monogramApplied = true;
					standardBuyGridView.monogramView.hideStep1();
					standardBuyGridView.monogramView.hideStep2();		
					standardBuyGridView.monogramView.hideStep3();	
					standardBuyGridView.monogramView.showMonogramRecapContainer();	
					standardBuyGridView.monogramView.hideMonoHeaderStepLinks();
					buildRecap();
				}
				
				return isValid;
			}
		    
			var clearAnyBogusStepThreeErrors = function(){
				if(selection.monogramType == 1){ // initial
					if((selection.monogramSingleInitalText != null && selection.monogramSingleInitalText != undefined && selection.monogramSingleInitalText.length == 1)){
						standardBuyGridView.monogramView.hideErrorIconMonoSingleInitial();
					}
				}else if(selection.monogramType == 2){ // initials
					if((parseInt(selection.monogramMultiInitial.join("").length) > 1)) {
						standardBuyGridView.monogramView.hideErrorIconMonoInitalsFirst(); 
						standardBuyGridView.monogramView.hideErrorIconMonoInitalsMiddle(); 
						standardBuyGridView.monogramView.hideErrorIconMonoInitalsLast(); 
					}				
					if(selection.monogramMultiInitial[0] != null && selection.monogramMultiInitial[0] != undefined){
						standardBuyGridView.monogramView.hideErrorIconMonoInitalsFirst(); 
					}
					if(selection.monogramMultiInitial[1] != null && selection.monogramMultiInitial[1] != undefined){
						standardBuyGridView.monogramView.hideErrorIconMonoInitalsMiddle(); 
					}
					if(selection.monogramMultiInitial[2] != null && selection.monogramMultiInitial[2] != undefined){
						standardBuyGridView.monogramView.hideErrorIconMonoInitalsLast(); 
					}					
				}else if(selection.monogramType == 3){ // word 
					if((selection.monogramWordText != null && selection.monogramWordText != undefined && selection.monogramWordText.length > 0)){
						standardBuyGridView.monogramView.hideErrorIconMonoWord();
					}				
				}else if(selection.monogramType == 4){ // multi word
					if(! isMultiWordEmpty()){
						standardBuyGridView.monogramView.hideErrorIconMonoMultiWord();
					}
				}			
			}
			
			var isMultiWordEmpty = function(){
				if(selection.monogramMultiLine == null || selection.monogramMultiLine == undefined){
					return true;
				}
				for(var i = 0;i < selection.monogramMultiLine.length;i++){ 
					if(selection.monogramMultiLine[i] != null && selection.monogramMultiLine[i] != undefined && selection.monogramMultiLine[i].length > 0){
						return false;
					}
				}
				
				return true;
			}
			
			this.errorChecker = function(displayIndicator,goingTostep,errors){
				if(errors == undefined){
					errors = new Array();
				}
	
				if(inUpdateReviewMode){
					return errors;
				}
				
				if(currentStep == 1 && selection.monogramType == null && goingTostep != 0){
					if(displayIndicator){standardBuyGridView.monogramView.showErrorIconMonoType();}
					errors.push(prodViewNs.Messages.findMessage(2));
				}else if(currentStep == 1 && goingTostep == 2){
					errors.push(prodViewNs.Messages.findMessage(3));				
				}else if(currentStep == 2 && (selection.monogramLocation == null || selection.monogramFont == null) && goingTostep == 2){
					if(selection.monogramLocation == null){
						if(displayIndicator){standardBuyGridView.monogramView.showErrorIconMonoLocation();}
						errors.push(prodViewNs.Messages.findMessage(4));	
					}
					if(selection.monogramFont == null){
						if(displayIndicator){standardBuyGridView.monogramView.showErrorIconMonoFont();}
						errors.push(prodViewNs.Messages.findMessage(3));	
					}					
				}else if(currentStep < 4 && goingTostep == 3){
					if(selection.monogramType == 1){ // initial
						if(selection.monogramSingleInitalText == null || selection.monogramSingleInitalText == undefined || selection.monogramSingleInitalText.length < 1){
							if(displayIndicator){standardBuyGridView.monogramView.showErrorIconMonoSingleInitial();}
							errors.push(prodViewNs.Messages.findMessage(5));	
						}
					}else if(selection.monogramType == 2){ // initials
						if(parseInt(selection.monogramMultiInitial.join("").length) < 2) {
							if(selection.monogramMultiInitial[0] == null || selection.monogramMultiInitial[0] == undefined){
								if(displayIndicator){standardBuyGridView.monogramView.showErrorIconMonoInitalsFirst(); }
							}
							if(selection.monogramMultiInitial[1] == null || selection.monogramMultiInitial[1] == undefined){
								if(displayIndicator){standardBuyGridView.monogramView.showErrorIconMonoInitalsMiddle(); }
							}
							if(selection.monogramMultiInitial[2] == null || selection.monogramMultiInitial[2] == undefined){
								if(displayIndicator){standardBuyGridView.monogramView.showErrorIconMonoInitalsLast(); }
							}						
							errors.push(prodViewNs.Messages.findMessage(6));	
						}				
					}else if(selection.monogramType == 3){ // word 
						if(selection.monogramWordText == null || selection.monogramWordText == undefined || selection.monogramWordText.length < 1){				
							if(displayIndicator){standardBuyGridView.monogramView.showErrorIconMonoWord(); }
							errors.push(prodViewNs.Messages.findMessage(5));	
						}				
					}else if(selection.monogramType == 4){ // multi word
						if(isMultiWordEmpty()){
							if(displayIndicator){standardBuyGridView.monogramView.showErrorIconMonoMultiWord();}
							errors.push(prodViewNs.Messages.findMessage(5));	
						}				
					}					
				}
				
				return errors;
			}
			
			this.selectStepTwo = function(){
				var errors = this.errorChecker(true,1);
				if(errors.length == 0){
					currentStep = 2;
					standardBuyGridView.monogramView.hideStep1();
					standardBuyGridView.monogramView.showStep2();		
					standardBuyGridView.monogramView.hideStep3();
					standardBuyGridView.monogramView.hideMonogramRecapContainer();
				}
			}
			
			this.selectStepThree = function(){
				var errors = this.errorChecker(true,2);
				if(errors.length == 0){
					currentStep = 3;
					standardBuyGridView.monogramView.hideStep1();
					standardBuyGridView.monogramView.hideStep2();		
					standardBuyGridView.monogramView.showStep3(selection.monogramType);
					standardBuyGridView.monogramView.hideMonogramRecapContainer();
				}
			}
			
			this.selectStepOne = function(){
				currentStep = 1;
				standardBuyGridView.monogramView.showStep1();
				standardBuyGridView.monogramView.hideStep2();		
				standardBuyGridView.monogramView.hideStep3();	
				standardBuyGridView.monogramView.hideMonogramRecapContainer();
			}
			
			this.registerEvents = function(){
				standardBuyGridView.monogramView.registerEvents();
			}
		}		
	} // end value added services controller
	
	this.hemmingController = new function(){
		
		this.registerEvents = function(){
			debug("HemmingController.registerEvents registering for cuffing selections.");
			standardBuyGridView.hemmingView.registerCuffingSelectors();
		}
		
		this.errorChecker = function(displayIndicator,hemmingErrors){
			debug("HemmingController.errorChecker checking for errors.");
			if(hemmingErrors == undefined){
				hemmingErrors = new Array();
			}
			
			if(selection.style.getInseamable() && (selection.inseam == null || selection.inseam == "")) {
				hemmingErrors.push(prodViewNs.Messages.findMessage(14));
				if (displayIndicator) standardBuyGridView.hemmingView.showErrorHemmingSelection();
			}
			debug("HemmingController.errorChecker errors " + hemmingErrors.length);
			return hemmingErrors;
		}
		
		this.styleChangeHemming = function(){
			debug("HemmingController.styleChangeHemming making hemming changes on new style selection.");
			for(var i = 0;i < styles.length;i++){ 		
				standardBuyGridView.hemmingView.hideSizeElements(styles[i].getNumber());	
			}		
			standardBuyGridView.hemmingView.showSizeElements(selection.style.getNumber());	
			if(selection.style.getInseamable()){
				standardBuyGridView.hemmingView.showInseamElements();	
				standardBuyGridView.hemmingView.makeInseamNotSelectable();
			}else{
				standardBuyGridView.hemmingView.hideInseamElements();	
			}
			if(selection.style.getCuffable()){
				standardBuyGridView.hemmingView.showCuffingElements();
				var errMessage = prodViewNs.Messages.findMessage(26).text.replace("${minCuffingInseam}","a specific number of");
				if(selection.sku){
					errMessage = prodViewNs.Messages.findMessage(26).text.replace("${minCuffingInseam}",selection.sku.getMaxCuff());
				}
			}else{
				standardBuyGridView.hemmingView.hideCuffingElements();	
			}	
		}

		var wipeHemmingCuffingSelections = function() {
			debug("HemmingController.wipeHemmingCuffingSelections wiping hemming and cuffing selection.");
			saveForHoverResetInseamCode = null;
			saveForHoverResetCuffingCode = null;
			selection.inseam = null;
			selection.cuffing = null;			
		}
		
		this.skuChangeHemming = function(){
			debug("HemmingController.skuChangeHemming adjusting hemming for the new sku.");
			if(selection.sku != null && selection.style.getInseamable()){
				standardBuyGridView.hemmingView.buildInseamList(selection.sku.getInseamList());
				if (selection.inseam == null || selection.inseam == undefined || !selection.sku.isInseamValid(selection.inseam)) {
					wipeHemmingCuffingSelections();
				}
				standardBuyGridView.hemmingView.makeInseamSelectionVisible();
				standardBuyGridView.hemmingView.makeInseamSelectable();
				this.inseamSelect(selection.inseam);
				this.cuffingSelect(selection.cuffing);
			}else if(selection.style.getInseamable()){
				standardBuyGridView.hemmingView.clearInseamList();
				standardBuyGridView.hemmingView.makeInseamNotSelectable();
				selection.inseam = null;
				selection.cuffing = null;
				standardBuyGridView.hemmingView.makeInseamSelectionVisible();

			}
			debug("HemmingController.skuChangeHemming change inseam selection to " + selection.inseam + " and cuffing selection to " + selection.cuffing);
			if (!selection.style.getInseamable()) {
				selection.inseam = null;
				selection.cuffing = null;
				standardBuyGridView.hemmingView.hideInseamSelection();
			}
		}
		
		this.inseamSelect = function(inseam){
			debug("HemmingController.inseamSelect handling new inseam selection " + inseam);
			standardBuyGridView.hemmingView.hideErrorHemmingSelection();
			if((inseam != null || inseam != undefined) && !(inseam === 'UNF')){
				inseam = parseFloat(inseam).toString(); // get rid of trailing .00s
			}
			if(selection.sku == null || ! selection.sku.isInseamValid(inseam) || ! selection.style.getInseamable()){
				selection.inseam = null;
			}else{
				selection.inseam = inseam;				
			}			
			standardBuyGridView.hemmingView.displayInseamCode(selection.inseam);	
			// TODO: get the correct logic in isValidCuffableInseam method
			if (selection.inseam == null || selection.inseam == "UNF") {
				standardBuyGridView.hemmingView.makeCuffingOptionsNotSelected(prodViewNs.Messages.findMessage(27));
				selection.cuffing = null;	
			}
			else {
				if (selection.cuffing == null || selection.cuffing == undefined) selection.cuffing = "uncuffed";
				
				if(selection.sku != null && ! selection.sku.isValidCuffableInseam(selection.inseam)){	
					var errMessage = prodViewNs.Messages.findMessage(26).text.replace("${minCuffingInseam}","a specific number of");
					if(selection.sku){
						errMessage = prodViewNs.Messages.findMessage(26).text.replace("${minCuffingInseam}",selection.sku.getMaxCuff());
					}
					standardBuyGridView.hemmingView.makeCuffingNotSelectable(errMessage);
					standardBuyGridView.hemmingView.displayCuffingCode("uncuffed", false);
					selection.cuffing = "uncuffed";
				}
				else{
					standardBuyGridView.hemmingView.makeCuffingOptionsAvailable();
					if (selection.cuffing != null && selection.cuffing != undefined) {
						this.cuffingSelect(selection.cuffing);	
					}
				}
			}						
		}
		
		this.cuffingSelect = function(cuffing){
			debug("HemmingController.cuffingSelect handing cuffing selections " + cuffing);
			var isCuffingValid = false;
			if (selection.inseam != null && selection.inseam != "UNF" && selection.inseam != undefined) {					
				if(! selection.style.getCuffable()){
					selection.cuffing = null;
				}else{
					if (selection.sku.isValidCuffableInseam(selection.inseam)) {
						isCuffingValid = true;
					}
					else{
						if(selection.cuffing == "cuffed"){
							standardBuyGridView.hemmingView.displayUncuffableMessage(prodViewNs.Messages.findMessage(25).text.replace("${minCuffingInseam}",selection.sku.getMaxCuff()));
						}
					}
					if(cuffing == null || cuffing == undefined || cuffing == "uncuffed" || 	!isCuffingValid){
						selection.cuffing = "uncuffed";
					}else{
						selection.cuffing = cuffing;
					}
				}
				standardBuyGridView.hemmingView.displayCuffingCode(selection.cuffing, isCuffingValid);
			}	
			else {
				selection.cuffing = null;
			}
		}
	}
	
	this.sizeColorController = new function(){
		var saveForHoverResetColorCode = null;
		var saveForHoverResetSizeCode = null;
		var saveForHoverResetInseamCode = null;
		var saveForHoverResetCuffingCode = null;
		var colorMessage = null;
		var sizeMessage = null;
		var isColorHoverActive = false;
		
		this.getColorHoverActive = function(){
			return isColorHoverActive;
		}
		
		this.errorChecker = function(displayIndicator,sizeErrors){
			debug("SizeColorController.errorChecker checking for errors in the size color controller, display error fields " + displayIndicator);
			if(sizeErrors == undefined){
				sizeErrors = new Array();
			}	
			
			if (selection.style.getFeatureTreeLeaf().getSizes().length > 0 && 
					(selection.sizeCode == undefined  || selection.sizeCode == null || selection.sizeCode == "")) {
				var errMessage = null;
				if (selection.style.getInseamable() && selection.style.getFeatureTreeLeaf().isMale()) {
					errMessage = prodViewNs.Messages.findMessage(15);
				}
				else {
					errMessage =  prodViewNs.Messages.findMessage(13);
				}
				sizeErrors.push(errMessage);
				if (displayIndicator) standardBuyGridView.sizeView.showErrorSizeSelection(selection.style.getNumber());
			}
			
			if(selection.sku == null || selection.sku == "" || selection.sku == undefined) {
				sizeErrors.push(prodViewNs.Messages.findMessage(16));
			}
			debug("SizeColorController.errorChecker errors " + sizeErrors.length);
			return sizeErrors;
				
		}
		
		var saveHoverValues = function() {
			debug("SizeColorController.saveHoverValues saving selection values");
			saveForHoverResetColorCode = selection.colorCode;
			saveForHoverResetSizeCode = selection.sizeCode;
			saveForHoverResetInseamCode = selection.inseam;
			saveForHoverResetCuffingCode = selection.cuffing;		
		}
		
		var putBackPreHoverValues = function() {			
			selection.colorCode = saveForHoverResetColorCode;
			selection.sizeCode = saveForHoverResetSizeCode;
			selection.inseam = saveForHoverResetInseamCode;
			selection.cuffing = saveForHoverResetCuffingCode;
			saveForHoverResetInseamCode = null;			
			saveForHoverResetCuffingCode = null;
			debug("SizeColorController.putBackPreHoverValues putting back pre hover values ");
		}
				
		this.sizehoverOver = function(sizeCode) {
			debug('SizeColorController.sizehoverOver hovering over size ' + sizeCode);
			sizeMessage = null;
			saveHoverValues();
			this.sizeSelect(sizeCode);
			putBackPreHoverValues();
			return sizeMessage;
		}

		this.sizehoverOut = function() {
			debug('SizeColorController.sizehoverOut hover out of size ');
			this.sizeSelect(selection.sizeCode);
			return selection.style.number;
		}
			
		this.sizeSelect = function(sizeCode){		
			debug('SizeColorController.sizeSelect selected size code ' + sizeCode);
			standardBuyGridView.sizeView.hideErrorSizeSelection(selection.style.getNumber());
			var sizeObj = selection.style.getFeatureTreeLeaf().isSizeCodeValid(sizeCode);
			var sizeDisplayText = null;
			if (sizeObj == null){
				sizeDisplayText = null;			
				selection.sizeCode = null;
			} else {
				selection.sizeCode = sizeCode;
				sizeDisplayText = sizeObj.getDisplayName();
			}
			this.compareSelectionToSku();
			checkColors();	
			checkSizes();	
			standardBuyGridView.sizeView.showSizeChoice(selection.style.getNumber(),sizeDisplayText);
		}
		
		this.styleChangeSizeColor = function(){
			debug('SizeColorController.styleChangeSizeColor setting size/color on style change.');
			if(selection.style.getFeatureTreeLeaf().isSizeCodeValid(selection.sizeCode) == null){ // make sure we have a valid size for new style
				selection.sizeCode = null;
			}			

			if(! selection.style.getFeatureTreeLeaf().isColorCodeValid(selection.colorCode)){ // make sure we have a valid color for new style
				this.setDefaultColorCode();
			}			
			
			for(var i = 0;i < styles.length;i++){ // default size / color items
				standardBuyGridView.colorView.hideStyleLevelElements(styles[i].getNumber()); 
				standardBuyGridView.sizeView.hideStyleLevelElements(styles[i].getNumber()); 	
			}
			standardBuyGridView.colorView.showStyleLevelElements(selection.style.getNumber());
			standardBuyGridView.sizeView.showStyleLevelElements(selection.style.getNumber());	
			
			thisStandardBuyGrid.sizeColorController.colorSelect(selection.colorCode); 
			thisStandardBuyGrid.sizeColorController.sizeSelect(selection.sizeCode);
			debug('SizeColorController.styleChangeSizeColor FINISHED');
		}
		
		this.setDefaultColorCode = function(){
			if (selection.style.getFeatureTreeLeaf().getSwatches().length > 0){	 //try to find the first color within the style			
				selection.colorCode = selection.style.getFeatureTreeLeaf().getSwatches()[0].getColor().getCode();
			}else{
				selection.colorCode = null; //style has no color selections available
			}
		}
		
		this.registerEvents = function(){
			debug("SizeColorController.registerEvents for size and color click/hover, inseamHemming.");
			for(var i = 0;i < styles.length;i++){ 
				standardBuyGridView.colorView.registerEvents(styles[i].getNumber());
				var swatches = styles[i].getFeatureTreeLeaf().getSwatches();
				for(var y = 0;y < swatches.length;y++){ 
					standardBuyGridView.colorView.registerColorSelectors(styles[i].getNumber(), swatches[y].getColor().getCode());
				}
			}
			
			for(var i = 0;i < styles.length;i++){
				standardBuyGridView.sizeView.registerSizeChartSelector(styles[i].getNumber());
				var sizes = styles[i].getFeatureTreeLeaf().getSizes();
				for(var y = 0;y < sizes.length;y++){ 
					standardBuyGridView.sizeView.registerSizeSelectors(styles[i].getNumber(),sizes[y].getCode());
				}
			}
			standardBuyGridView.sizeView.registerInseamHemmingInfoSelector();
		}
		
		this.colorhoverOver = function(colorCode) {
			debug("SizeColorController.colorhoverOver hovering over color " + colorCode);
			isColorHoverActive = true;
			colorMessage = null;
			saveHoverValues();
			this.colorSelect(colorCode);			
			putBackPreHoverValues();
			isColorHoverActive = false;
			return colorMessage;
		}

		this.colorhoverOut = function() {
			debug("SizeColorController.colorhoverOut hover out of a color chip.");
			isColorHoverActive = true;
			this.colorSelect(selection.colorCode);
			isColorHoverActive = false;
		}

		
		this.colorSelect = function(colorCode){
			debug('SizeColorController.colorSelect selected color code ' + colorCode);
			if(! selection.style.getFeatureTreeLeaf().isColorCodeValid(colorCode)){ // if color provided is not found, try defaulting 
				this.setDefaultColorCode();
				if(selection.colorCode == null){
					return; // no color variation on view, nothing more to do
				}
			}else{ // valid color code choice 
				selection.colorCode = colorCode;
				if (selection.style.getCustomizableItem() == false){ //Trigger color changes only for non-custom items. Custom items do not have color selectors.
					colorChange(selection.colorCode);
				}
			}
			this.compareSelectionToSku();
			checkColors();	
			checkSizes();
		}
		
		this.highlightSelectedColorSwatch = function(){
			debug('SizeColorController.highlightSelectedColorSwatch');
			standardBuyGridView.colorView.highLightSelectedSwatch(selection.style.getNumber());
		}
		
		this.compareSelectionToSku = function(){
			debug('SizeColorController.compareSelectionToSku setting selection.sku');
			var newSku = selection.style.findSku(selection.colorCode,selection.sizeCode);
			if(newSku != selection.sku){
				selection.sku = newSku;
				checkSkuAvailability();
				skuChange();
			}
		}
		
		var checkColors = function(){
			debug("SizeColorController.checkColors setting availability information on color chips");
			if(selection.sizeCode == null && selection.style.hasSizeVariation()){// the best we can do at this level is simply select the chosen and default the rest
				var swatches = selection.style.getFeatureTreeLeaf().getSwatches();
				for(var y = 0;y < swatches.length;y++){ 
					standardBuyGridView.colorView.colorNotSelected(selection.style.getNumber(),swatches[y].getColor().getCode());
				}
				standardBuyGridView.productView.showText("1");
				standardBuyGridView.colorView.colorSelected(selection.style.getNumber(),selection.colorCode);
			}else{ // we either have a size code or no size variation, so we can proceed analyzing all color chips against SKU references
				var swatches = selection.style.getFeatureTreeLeaf().getSwatches();
				for(var y = 0;y < swatches.length;y++){ 
					var loopColorCode = swatches[y].getColor().getCode();
					var matchingSku = selection.style.findSku(loopColorCode,selection.sizeCode);
					if(matchingSku == null){
						standardBuyGridView.colorView.colorNotSelectedNotAvailable(selection.style.getNumber(),loopColorCode);
					}else if(matchingSku.getInventoryStatus().getStatus() == "B"){
						standardBuyGridView.colorView.colorNotSelectedBackOrdered(selection.style.getNumber(),loopColorCode);							
					}else if(matchingSku.getInventoryStatus().getStatus() == "A"){
						standardBuyGridView.colorView.colorNotSelected(selection.style.getNumber(),loopColorCode);
					}
				}
				
				if(selection.sku == null){
					standardBuyGridView.colorView.colorSelectedNotAvailable(selection.style.getNumber(),selection.colorCode);
					standardBuyGridView.productView.showText("I");
					colorMessage = prodViewNs.Messages.findMessage(1);
				}else if(selection.sku.getInventoryStatus().getStatus() == "B"){
					standardBuyGridView.productView.showText("B");
					standardBuyGridView.colorView.colorSelectedBackOrdered(selection.style.getNumber(),selection.colorCode);
					colorMessage = prodViewNs.Messages.findMessage(0);
					colorMessage.text = colorMessage.text + selection.sku.getDisplayBackorderDate();					
				}else if(selection.sku.getInventoryStatus().getStatus() == "A"){
					standardBuyGridView.colorView.colorSelected(selection.style.getNumber(),selection.colorCode);
					standardBuyGridView.productView.showText("A");
				}
				
				if (selection.sku != null) {
					if (selection.sku.getOriginalPrice() != null && selection.sku.getPrice() != null && 
							parseFloat(selection.sku.getOriginalPrice()) > parseFloat(selection.sku.getPrice())) {
						standardBuyGridView.productView.showPrice(selection.sku.getOriginalPrice(), selection.sku.getPrice());
					}
					else {
						standardBuyGridView.productView.showPrice(null, selection.sku.getPrice());
					}
				}				
			}
			standardBuyGridView.colorView.showColorChoice(selection.style.getNumber(),selection.style.getColorDescription(selection.colorCode));
		}
		
		var checkSizes = function(){
			debug("SizeColorController.checkSizes setting availability information on size chips");
			if(selection.sizeCode == null && selection.sku == null){ // default all size chips
				var sizes = selection.style.getFeatureTreeLeaf().getSizes();
				for(var y = 0;y < sizes.length;y++){ 
					var loopSizeCode = sizes[y].getCode();
					standardBuyGridView.sizeView.sizeNotSelected(selection.style.getNumber(),loopSizeCode);	
					var matchingSku = selection.style.findSku(selection.colorCode,loopSizeCode);
					if(matchingSku == null){
						standardBuyGridView.sizeView.sizeNotSelectedNotAvailable(selection.style.getNumber(),loopSizeCode);
					}else if(matchingSku.getInventoryStatus().getStatus() == "B"){
						standardBuyGridView.sizeView.sizeNotSelectedBackOrdered(selection.style.getNumber(),loopSizeCode);
					}else if(matchingSku.getInventoryStatus().getStatus() == "A"){
						standardBuyGridView.sizeView.sizeNotSelected(selection.style.getNumber(),loopSizeCode);
					}					
				}
				var highPriceSku = selection.style.getPriceDisplaySku();
				if (highPriceSku != null) {
					if (highPriceSku.getOriginalPrice() != null && highPriceSku.getPrice() != null && 
							parseFloat(highPriceSku.getOriginalPrice()) > parseFloat(highPriceSku.getPrice())) {
						standardBuyGridView.productView.showPrice(highPriceSku.getOriginalPrice(), highPriceSku.getPrice());
					}
					else {
						standardBuyGridView.productView.showPrice(null, highPriceSku.getPrice());
					}
				}				
			}
			
			if(selection.sizeCode != null){ 
				var sizes = selection.style.getFeatureTreeLeaf().getSizes();
				for(var y = 0;y < sizes.length;y++){ 
					var loopSizeCode = sizes[y].getCode();
					var matchingSku = selection.style.findSku(selection.colorCode,loopSizeCode);
					if(matchingSku == null){
						standardBuyGridView.sizeView.sizeNotSelectedNotAvailable(selection.style.getNumber(),loopSizeCode);
					}else if(matchingSku.getInventoryStatus().getStatus() == "B"){
						standardBuyGridView.sizeView.sizeNotSelectedBackOrdered(selection.style.getNumber(),loopSizeCode);
					}else if(matchingSku.getInventoryStatus().getStatus() == "A"){
						standardBuyGridView.sizeView.sizeNotSelected(selection.style.getNumber(),loopSizeCode);
					}
				}
				
				if(selection.sku == null){
					standardBuyGridView.sizeView.sizeSelectedNotAvailable(selection.style.getNumber(),selection.sizeCode);
					standardBuyGridView.productView.showText("I");
					sizeMessage = prodViewNs.Messages.findMessage(1);
				}else if(selection.sku.getInventoryStatus().getStatus() == "B"){
					standardBuyGridView.sizeView.sizeSelectedBackOrdered(selection.style.getNumber(),selection.sizeCode);
					standardBuyGridView.productView.showText("B");
					sizeMessage = prodViewNs.Messages.findMessage(0);
					sizeMessage.text = sizeMessage.text + selection.sku.getDisplayBackorderDate();
				}else if(selection.sku.getInventoryStatus().getStatus() == "A"){
					standardBuyGridView.sizeView.sizeSelected(selection.style.getNumber(),selection.sizeCode);
					standardBuyGridView.productView.showText("A");
				}
				standardBuyGridView.productView.resetPrice();
				
				if (selection.sku != null) {
					if (selection.sku.getOriginalPrice() != null && selection.sku.getPrice() != null && 
							parseFloat(selection.sku.getOriginalPrice()) > parseFloat(selection.sku.getPrice())) {
						standardBuyGridView.productView.showPrice(selection.sku.getOriginalPrice(), selection.sku.getPrice());
					}
					else {
						standardBuyGridView.productView.showPrice(null, selection.sku.getPrice());
					}
				}
				else {
					standardBuyGridView.productView.showPrice(null, selection.style.getPriceDisplaySku().getPrice());
				}
				
			}
		}
		
		var checkSkuAvailability = function(){
			// TODO: Pull in the error messaging from compareSelectionToSku sbg.js
			// For now we don't need method - Sankar/Scott on 08/12/10

		}
	}
	
	this.featureTypeController = new function(){
		
		this.registerEvents = function(){
			debug("FeatureTypeController.registerEvents registering for feature type click events.");
			for(var i = 0;i < allFeatures.length;i++){ 
				if(allFeatures[i].getLevel() > 0){
					var featureKeyList = buildFeatureNumberKeyArray(allFeatures[i]);
					standardBuyGridView.featureTypeView.registerFeatureTypeSelectors(featureKeyList[0],featureKeyList[1],featureKeyList[2]);
				}
			}			
		}
		
		this.selectFeature = function(primaryFeatureId,secondaryFeatureId,thirdFeatureId){
			debug("FeatureTypeController.selectFeature selected features with id feature 1=" + primaryFeatureId + " feature 2=" + secondaryFeatureId + "feature 3=" + thirdFeatureId);
			// create combination key based on current and previous selection to try for a perfect match
			var tempPrimaryFeatureId = null; if(primaryFeatureId != undefined){tempPrimaryFeatureId = primaryFeatureId}else if(selection.primaryFeatureId != null){tempPrimaryFeatureId = selection.primaryFeatureId};
			var tempSecondaryFeatureId = null; if(secondaryFeatureId != undefined){tempSecondaryFeatureId = secondaryFeatureId}else if(selection.secondaryFeatureId != null){tempSecondaryFeatureId = selection.secondaryFeatureId};
			var tempThirdFeatureId = null; if(thirdFeatureId != undefined){tempThirdFeatureId = thirdFeatureId}else if(selection.thirdFeatureId != null){tempThirdFeatureId = selection.thirdFeatureId};
			
			var bestFeatureMatch = product.findBestFeatureMatch(tempPrimaryFeatureId,tempSecondaryFeatureId,tempThirdFeatureId);
			var newStyle = bestFeatureMatch.getFirstStyle();
			if(selection.style != newStyle){
				selection.style = newStyle;
				styleChange(newStyle);
				this.updateSelectionBasedOnSelectedStyle();
				
				// remove focus from all features
				for(var i = 0;i < allFeatures.length;i++){
					if(allFeatures[i].getLevel() > 0){
						var featureKeyList = buildFeatureNumberKeyArray(allFeatures[i]);
						standardBuyGridView.featureTypeView.unselectFeature(featureKeyList[0],featureKeyList[1],featureKeyList[2]);
						// hide all feature groups
						if(allFeatures[i].getSubFeatureType() != null){
							standardBuyGridView.featureTypeView.hideFeatureGroup(featureKeyList[0],featureKeyList[1]);
						}
					}
				}
				
				// select all features that need to be selected
				standardBuyGridView.featureTypeView.hightLightFeature(selection.primaryFeatureId,selection.secondaryFeatureId,selection.thirdFeatureId, selection.style.getNumber());
				standardBuyGridView.featureTypeView.hightLightFeature(selection.primaryFeatureId,selection.secondaryFeatureId,null,selection.style.getNumber());
				standardBuyGridView.featureTypeView.hightLightFeature(selection.primaryFeatureId,null,null,selection.style.getNumber());

				if (selection.style.getCatalogNumber().getMediaCode() != null)
				standardBuyGridView.productView.changeItemNumber(selection.style.getCatalogNumber().getStyleNumber(), selection.style.getCatalogNumber().getMediaCode().getMediaCodeId(), 
																	selection.style.getCatalogNumber().getCheckDigit(), selection.style.getLongName());
				
				// show all feature groups that should be shown
				standardBuyGridView.featureTypeView.showFeatureGroup(selection.primaryFeatureId,selection.secondaryFeatureId,null);
				standardBuyGridView.featureTypeView.showFeatureGroup(selection.primaryFeatureId,null,null);
				if (selection.secondaryFeatureId != null) {
					var secondaryFeatureText = null;
					var thirdFeatureText = null;
					var secondFeatureTypeText = null;
					var thirdFeatureTypeText = null;
					for (var i = 0;i < allFeatures.length;i++) {
						if (allFeatures[i].getFeatureNumber() == selection.secondaryFeatureId) {
							 secondaryFeatureText = allFeatures[i].getDisplayText();						
						}
						if (allFeatures[i].getFeatureNumber() == selection.thirdFeatureId) {
							thirdFeatureText = allFeatures[i].getDisplayText();
						}
					}
					standardBuyGridView.featureTypeView.showFeatureText(secondaryFeatureText, thirdFeatureText);
				}
			}
			
			if (thisStandardBuyGrid.giftCardExtensionController != null) {
				thisStandardBuyGrid.giftCardExtensionController.selectGiftCardType(primaryFeatureId, secondaryFeatureId);
			}
		}
		
		this.updateSelectionBasedOnSelectedStyle = function(){
			debug("FeatureTypeController.updateSelectionBasedOnSelectedStyle updating selections based on style.");
			selection.primaryFeatureId = null;
			selection.secondaryFeatureId = null;
			selection.thirdFeatureId = null;
			
			setCorrectFeatureSelectionLevel(selection.style.getFeatureTreeLeaf());	
			if(selection.style.getFeatureTreeLeaf().getParentFeature() != null){
				setCorrectFeatureSelectionLevel(selection.style.getFeatureTreeLeaf().getParentFeature());
				if(selection.style.getFeatureTreeLeaf().getParentFeature().getParentFeature() != null){
					setCorrectFeatureSelectionLevel(selection.style.getFeatureTreeLeaf().getParentFeature().getParentFeature());	
				}
			}		
		}
		
		var setCorrectFeatureSelectionLevel = function(feature){
			debug("FeatureTypeController.setCorrectFeatureSelectionLevel ");
			if(feature.getLevel() == 1){selection.primaryFeatureId = feature.getFeatureNumber();}
			else if(feature.getLevel() == 2){selection.secondaryFeatureId = feature.getFeatureNumber();}
			else if(feature.getLevel() == 3){selection.thirdFeatureId = feature.getFeatureNumber();}			
		}
		
		var buildFeatureNumberKeyArray = function(feature){
			var featureKeyList = new Array();
			
			if(feature.getLevel() == 1){
				featureKeyList.push(feature.getFeatureNumber());
				featureKeyList.push(null);
				featureKeyList.push(null);
			}else if(feature.getLevel() == 2){
				featureKeyList.push(feature.getParentFeature().getFeatureNumber());
				featureKeyList.push(feature.getFeatureNumber());
				featureKeyList.push(null);
			}else if(feature.getLevel() == 3){
				featureKeyList.push(feature.getParentFeature().getParentFeature().getFeatureNumber());
				featureKeyList.push(feature.getParentFeature().getFeatureNumber());
				featureKeyList.push(feature.getFeatureNumber());	
			}
			return featureKeyList;
		}
	}

	this.dropShipController = new function(){
		
		this.registerEvents = function(){
			debug("DropShipController.registerEvents registering events");
			standardBuyGridView.dropShipView.registerEvents();
		}			
		
		this.resetDropShipData = function(){
			debug("DropShipController.registerEvents Reset the daytime and alternate phone numbers and extension fields");
			selection.dropShipDayPhone = null;
			selection.dropShipDayPhoneExt = null;
			selection.dropShipAltPhone = null;
			selection.dropShipAltPhoneExt = null;
			this.phoneSelect('', false);     // Drop ship daytime phone number
			this.extensionSelect('', false); // Drop ship daytime extension number.
			this.phoneSelect('', true);      // Drop ship alternate phone number.
			this.extensionSelect('', true);  // Drop ship alternate extension number.
		}
		
		this.errorChecker = function(displayIndicator,dropShipErrors){
			if(dropShipErrors == undefined){
				dropShipErrors = new Array();
			}
			
			// We need to run the validations only if the style requires white glove delivery.
			if (selection.style.getRequiresWhiteGloveDelivery()){
				debug("DropShipController.errorChecker Running validations.");
				// Daytime phone number is mandatory. First check if it has been entered, extension is always optional.
				// If the customer entered an alternate phone number and not a daytime phone number, that is an error also.
				debug("DropShipController.registerEvents Daytime Phone number is mandatory, checking if one is entered.");
				if (selection.dropShipDayPhone == null || selection.dropShipDayPhone == undefined || selection.dropShipDayPhone.length < 1)
				{
					if(displayIndicator){standardBuyGridView.dropShipView.showErrorIconDayPhone();}
					dropShipErrors.push(prodViewNs.Messages.findMessage(10));
				}
				
				if (selection.dropShipDayPhone != null && selection.dropShipDayPhone != undefined && selection.dropShipDayPhone.length > 0){				
					debug("DropShipController.errorChecker Checking if daytime phone number is valid");
					var cleanPhoneNum = selection.dropShipDayPhone; 
					cleanPhoneNum = cleanPhoneExtensionNumber(cleanPhoneNum);
					if (!checkPhoneNumber(cleanPhoneNum)){
						if(displayIndicator){standardBuyGridView.dropShipView.showErrorIconDayPhone();}
						dropShipErrors.push(prodViewNs.Messages.findMessage(9));
					}
					debug("DropShipController.errorChecker Checking if daytime phone Extn number is valid");
					var cleanExtensionNum = selection.dropShipDayPhoneExt;
					cleanExtensionNum = cleanPhoneExtensionNumber(cleanExtensionNum);
					if (!checkExtensionNumber(cleanExtensionNum)){
						if(displayIndicator){standardBuyGridView.dropShipView.showErrorIconDayExtension();}
						dropShipErrors.push(prodViewNs.Messages.findMessage(9));
					}
				}
				if (selection.dropShipAltPhone != null && selection.dropShipAltPhone != undefined  && selection.dropShipAltPhone.length > 0){				
					debug("DropShipController.errorChecker Checking if alternate phone number is valid");
					var cleanPhoneNum = selection.dropShipAltPhone; 
					cleanPhoneNum = cleanPhoneExtensionNumber(cleanPhoneNum);
					if (!checkPhoneNumber(cleanPhoneNum)){
						if(displayIndicator){standardBuyGridView.dropShipView.showErrorIconAltPhone();}
						dropShipErrors.push(prodViewNs.Messages.findMessage(9));
					}
					debug("DropShipController.errorChecker Checking if alternate phone Extn number is valid");
					var cleanExtensionNum = selection.dropShipAltPhoneExt;
					cleanExtensionNum = cleanPhoneExtensionNumber(cleanExtensionNum);
					if (!checkExtensionNumber(cleanExtensionNum)){
						if(displayIndicator){standardBuyGridView.dropShipView.showErrorIconAltPhone();}
						dropShipErrors.push(prodViewNs.Messages.findMessage(9));
					}
				}	
			}
			return dropShipErrors;
		}
		
		
		this.phoneSelect = function(phoneNum, alternatePhoneSelected){
			// Validate that a phone number can only contain numeric, space, hyphen, opening and closing brace character 
			var phoneCharRegEx = /^[0-9\-\s\(\)]$/
			var cleanCharString = "";
			for (var i = 0; i < phoneNum.length; i++){
				if (phoneNum.charAt(i).match(phoneCharRegEx) != null){
					cleanCharString = cleanCharString + phoneNum.charAt(i);
				}
			}
			if (alternatePhoneSelected){
				selection.dropShipAltPhone = cleanCharString;
				standardBuyGridView.dropShipView.hideErrorIconAltPhone();
			} else {
				selection.dropShipDayPhone = cleanCharString;
				standardBuyGridView.dropShipView.hideErrorIconDayPhone();
			}
			standardBuyGridView.dropShipView.displayPhoneNumber(cleanCharString, alternatePhoneSelected);
		}
		
		this.extensionSelect = function(extensionNumber, alternateExtensionSelected){
			// Validate that a phone number can only contain numeric character
			var extensionCharRegEx = /^[0-9]$/
			var cleanCharString = "";
			for (var i = 0; i < extensionNumber.length; i++){
				if (extensionNumber.charAt(i).match(extensionCharRegEx) != null){
					cleanCharString = cleanCharString + extensionNumber.charAt(i);
				}
			}
			if (alternateExtensionSelected){
				selection.dropShipAltPhoneExt = cleanCharString;
				standardBuyGridView.dropShipView.hideErrorIconAltExtension();
			} else {
				selection.dropShipDayPhoneExt = cleanCharString;
				standardBuyGridView.dropShipView.hideErrorIconAltExtension();
			}
			standardBuyGridView.dropShipView.displayExtensionNumber(cleanCharString, alternateExtensionSelected);
		}
		
		var cleanPhoneExtensionNumber = function(phoneNum) {
			debug("DropShipController.cleanPhoneExtensionNumber Cleaning up phone/extension number " + phoneNum);
			phoneNum = phoneNum.replace(/\-/g, "");
			phoneNum = phoneNum.replace(/\s/g, "");
			phoneNum = phoneNum.replace(/\(/g, "");
			phoneNum = phoneNum.replace(/\)/g, "");
			debug("DropShipController.cleanPhoneExtensionNumber Cleaned up phone/extension number " + phoneNum);
			return phoneNum;
		}
		
		var checkPhoneNumber = function(phoneNum) {
			debug("DropShipController.checkPhoneNumber Validating " + phoneNum);
			var theInput = phoneNum;
			var phoneRegEx = /^((\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,3})|(\(?\d{2,3}\)?))(-| )?(\d{3,4})(-| )?(\d{4}){0,1}$/
			var scrubbed = cleanPhoneExtensionNumber(theInput);
			if (theInput.match(phoneRegEx) && scrubbed.length == 10) {
				return true;
			} else if (theInput == "") {
				return true;
			} else {
				return false;
			}
		}
		
		var checkExtensionNumber = function(extensionNumber){
			debug("DropShipController.checkExtensionNumber Validating " + extensionNumber);
			var theInput = extensionNumber;
			var extRegEx = /^[0-9]*$/
		    var scrubbed = cleanPhoneExtensionNumber(theInput);
			if (theInput.match(extRegEx) && scrubbed.length <= 5){
				return true;
			} else if (theInput == ""){
				return true;
			} else {
				return false;
			}
		}
	}
	
	this.quantityController = new function(){
			
		this.init = function(){
			debug("QuantityController.init Building quantity drop list values.");
			standardBuyGridView.quantityView.buildQauntityOptionToList();
			debug("QuantityController.init Done.");
		}
		
		this.registerEvents = function(){
			debug("QuantityController.registerEvents Registering events on the view.");
			standardBuyGridView.quantityView.registerQuantitySelector(product.getNumber(), selection.style.getNumber());
		}
		
		this.quantitySelect = function(selectedQty){
			debug("QuantityController.quantitySelect quantity selected in view" + selectedQty);
			selection.quantity = selectedQty;
			debug("[quantitySelect] selection.quantity = " + selection.quantity);
			standardBuyGridView.quantityView.displayQuantity(selectedQty);
		}
	}
	
	this.productPhotoViewerController = new function(){
		var thisPhotoController = this;
		var photoDisplays = new Object();
		var fullScreenPhotoDisplay = null;
		
		this.init = function(){		
			fullScreenPhotoDisplay = new com.landsend.productView.FullScreenPhotoDisplay();
			photoDisplays = new Object();
			var funcName = "ProductPhotoViewerController.init ";
			// Custom styles alone will be initialized here. All others will be done only when we change to that style (see styleChangeViewer method).
			if (styles[0].getCustomizableItem()){
				debug(funcName + " Initializing a viewer for a custom style.");
				var photoViewer = new com.landsend.productView.PhotoDisplay();
				photoViewer.init(product.getNumber(), styles[0].getNumber(), styles[0].getFeatureTreeLeaf().getImageSetCollection(), styles[0].getFeatureTreeLeaf().getSwatches(), styles[0].hasOnlyLegacyImages(), null, null);
				photoViewer.registerForFullScreenEvent(thisPhotoController.launchFullScreenPhotoViewer);
				photoDisplays[product.getNumber() + '_' + styles[0].getNumber()] = photoViewer;
			}
		}
		
		var initializePhotoViewer = function(style){
			debug("ProductPhotoViewerController.initializePhotoViewer creating a photo viewer for style " + style.getNumber());
			
			var colorCode = null;			
			var pageMode = $.query.get("action");
			if(pageMode == "order_more" || pageMode == "modify"){	
				var querySku = $.query.get("sku_0").split(":");	
				if (querySku[2] != null && querySku[2] != ""){
					var tempColorCode = querySku[2];
					if (style.getFeatureTreeLeaf().isColorCodeValid(tempColorCode)){
						colorCode = tempColorCode;
					}
				}
			}	
			var photoViewer = new com.landsend.productView.PhotoDisplay();
			photoViewer.init(product.getNumber(), style.getNumber(), style.getFeatureTreeLeaf().getImageSetCollection(), style.getFeatureTreeLeaf().getSwatches(), style.hasOnlyLegacyImages(), colorCode, null);
			photoViewer.registerForFullScreenEvent(thisPhotoController.launchFullScreenPhotoViewer);
			photoDisplays[product.getNumber() + '_' + style.getNumber()] = photoViewer;
			debug("ProductPhotoViewerController.initializePhotoViewer FINISHED creating a photo viewer for style " + style.getNumber());
		}
		
		this.styleChangeViewer = function()
		{
			// Call out to photo viewer only if there are images at the style level
			if (selection.style.getFeatureTreeLeaf().getImageSetCollection().getImageSetList().length > 0 ) {
				if (photoDisplays[product.getNumber()  + '_' + selection.style.getNumber()] == null){initializePhotoViewer(selection.style);}
				var funcName = "ProductPhotoViewerController.styleChangeViewer";
				debug(funcName + "Changing to viewer for style " + selection.style.getNumber());
				if (styles[0].getCustomizableItem() == false){  // For a custom item, we only have a single viewer for the first style in the product, hence no need to hide any other viewers.
					for(var i = 0;i < styles.length;i++){var viewerKey = product.getNumber() + '_' + styles[i].getNumber(); if (photoDisplays[viewerKey] != null){ photoDisplays[viewerKey].hide();}}
				}
				photoDisplays[product.getNumber() + '_' + selection.style.getNumber()].show();
				debug(funcName + "Style change viewer complete for style  " + selection.style.getNumber());
			}
		}
		
		this.updateViewerColor = function () {
			debug("ProductPhotoViewerController.updateViewerColor Switching image to another color.");
			photoDisplays[product.getNumber() + '_' + selection.style.getNumber()].updateViewerColor();
		}		
		
		this.setPhotoViewerColorCode = function(colorCode){
			debug("ProductPhotoViewerController.setPhotoViewerColorCode new color " + colorCode);
			photoDisplays[product.getNumber() + '_' + selection.style.getNumber()].setPhotoViewerColorCode(colorCode);
		}
		
		this.launchFullScreenPhotoViewer = function(productNumber, styleNumber, imageSetCollection, swatchList, colorCode, imagePosition){
			debug("ProductPhotoViewerController.setPhotoViewerColorCode Launching full screen for style " + styleNumber + " colorCode " + colorCode + " imagePosition " + imagePosition); 
			fullScreenPhotoDisplay.launchFullScreenViewer(styleNumber, imageSetCollection, swatchList, selection.style.getColorsByPriceCodeBean(), colorCode, imagePosition, updateColorOnFullScreenExit, true);
			thisStandardBuyGrid.webAnalyticsController.sendFullScreenPhotoViewEvent(styleNumber);
		}
	    
		var updateColorOnFullScreenExit = function(colorCode){
			debug("ProductPhotoViewerController.updateColorOnFullScreenExit Update inpage viewer color to  " + colorCode);
			thisStandardBuyGrid.sizeColorController.colorSelect(colorCode);
			thisStandardBuyGrid.sizeColorController.highlightSelectedColorSwatch();
		}
	} //End PhotoViewer Controller.


	this.webAnalyticsController = new function() {
		debug("[webAnalyticsController].... ");
		var hasStyleSearchBeenProcessed = false;

		var bypassStyleChangeEvent = false;
		
		this.bypassSendStyleEvent = function(bypass){
			bypassStyleChangeEvent = bypass;
		}		
		
	     this.sendAddToBagMetric = function(response){
	    	debug("[sendAddToBagMetric].... ");
	    	var selection = response.selections[0]; 
	    	var inTypeCd = (selection.style.getCatalogNumber().getMediaCode() == null) ? null : 
	    									selection.style.getCatalogNumber().getMediaCode().getInternetComponentTypeCode();
	    	var selectedSkuPromoCode = selection.sku.getPromoMdseTypeCode();
	    	var storeType = "FP";
	    	if(inTypeCd == null || inTypeCd == 2 || inTypeCd == 4 || inTypeCd == 5){
	    		storeType = "LI";
	    	}
	    	 
	 		s = s_gi(s_account);
	 		 if (product.isGCProduct()) {
	 			s.linkTrackVars='products,events';
	 			s.linkTrackEvents='scAdd,event12';
	 			s.events='scAdd,event12';
	 			if (selection.primaryFeatureId == prodViewNs.GCConstants.VIRTUAL_CARD_FEATURE_NUMBER) {
	 				s.products=';' + 'FP_99025_I;1;' + selection.gcAmount + ';;;event12=1';
	 			}
	 			else {
	 				s.products=';' + 'FP_99025_P;1;' + selection.gcAmount + ';;;event12=1';
	 			}
	 		 }
	 		 else { 
		         s.linkTrackVars='products,events';
		         s.linkTrackEvents='scAdd,event12';
		         s.events='scAdd,event12';
		         s.products=';' + storeType + '_' + selection.style.getNumber() + ';;;event12=' + selection.quantity;
	         }
	         
	         
	         if(selectedSkuPromoCode != null){
	         	if(selectedSkuPromoCode == 1){
	         		s.products = s.products + "|event47=" + selection.quantity;
	         		s.events = s.events + ",event47";
	         		s.linkTrackEvents = s.linkTrackEvents  + ",event47";
	         	}else if(selectedSkuPromoCode == 2){
	         		s.products = s.products + "|event48=" + selection.quantity;
	         		s.events = s.events + ",event48";
	         		s.linkTrackEvents = s.linkTrackEvents  + ",event48";
	         	}else if(selectedSkuPromoCode == 3){
	         		s.products = s.products + "|event49=" + selection.quantity;
	         		s.events = s.events + ",event49";
	         		s.linkTrackEvents = s.linkTrackEvents  + ",event49";
	         	}
	         }
	         
	         s.tl(true,'o','Add To Bag');
	     }		
		
		this.sendStyleChangeEvents = function() {
			debug("[sendStyleChangeEvents].... ");
			var action = $.query.get('action');
			s_omtr.pageName = selection.style.getStoreTypeCode() + '_PP_' +  selection.style.getProductCode() + '_' 
			 						+ $.trim(product.getLongName().replace(/\'/, ""));
			if (!hasStyleSearchBeenProcessed && action != null && action.match(/DTP_SEARCH/)) {
				sendDirectStyleSearch();
				hasStyleSearchBeenProcessed = true;
			}
			else {
				sendChangeStyleMetric();
			}
		}
		
		this.sendFullScreenPhotoViewEvent = function(styleNum){
			$.debug('WebAnalyticsController.sendFullScreenPhotoViewEvent for style number ' + styleNum);
			s_omtr = s_gi(s_account);
			s_omtr.linkTrackVars='products,events';
			s_omtr.linkTrackEvents='event63';
			s_omtr.events='event63';
			s_omtr.products=';'  + selection.style.getStoreTypeCode() + '_' + selection.style.getNumber();
			s_omtr.tl(true,'o','link'); 
		}
		
		var sendDirectStyleSearch = function() {
			debug("[sendDirectStyleSearch].... ");
	   	 	var action = $.query.get('action');
	   	 	var query = ($.query.get('query')).toString();
	   	 	var selectStyleQtys =  selection.style.getQuantities();
			s_omtr = s_gi(s_account);
			s_omtr.linkTrackVars='prop1,prop2,prop4,events,eVar1,eVar3,eVar4,eVar12,products,evar15';
			s_omtr.linkTrackEvents='prodView,event1,event2,event28,event29,event30,event31,event61,event62';
			s_omtr.events='prodView,event1,event2,event28,event29,event30,event31,event61,event62';
			var rrAvgRating = 0;
			var rrTotProductRecommendations = 0;
			if (product.getProductRating() != null && product.getProductRating().getAverageRating() != null){ rrAvgRating = product.getProductRating().getAverageRating();}
			if (product.getProductRating() != null && product.getProductRating().getTotalProductRecomendations() != null){ rrTotProductRecommendations = product.getProductRating().getTotalProductRecomendations();}
			s_omtr.products=';' + selection.style.getStoreTypeCode() + '_' + selection.style.getNumber() 
								   + ';;;event28=' + selectStyleQtys.getTotalNumberofSkus() 
			                       + '|event29=' + selectStyleQtys.getTotalAvailableSkus()
			                       + '|event30=' + selectStyleQtys.getTotalNotAvailabeSkus()
			                       + '|event31=' + selectStyleQtys.getTotalBackOrderedSkus()
			                       + '|event61=' + rrAvgRating
			                       + '|event62=' + rrTotProductRecommendations
			                       + ';evar4=' + getCategoryID()
			                       + '|evar15=' + s_omtr.evar15;
			s_omtr.prop1= query;
			s_omtr.prop2=1;
			s_omtr.prop4='Item Number';
			s_omtr.evar1= query;
			s_omtr.evar3='search';
			s_omtr.evar12='Item Number';
			
			addPromoCode(s_omtr);
			
			s_omtr.tl(true,'o','link'); 			
		}
		
		var sendChangeStyleMetric = function() {
			if(bypassStyleChangeEvent){
				return;
			}			
			
			debug("[sendChangeStyleMetric].... ");
			var selectStyleQtys =  selection.style.getQuantities();
			s_omtr = s_gi(s_account);
	        s_omtr.linkTrackVars='products,eVar4,eVar19,events';
	        s_omtr.linkTrackEvents='prodView,event2,event28,event29,event30,event31,event61,event62';
	        s_omtr.events='prodView,event2,event28,event29,event30,event31,event61,event62';    
	        s_omtr.eVar19=getCategoryID();
	        
	        addPromoCode(s_omtr);
	        var rrAvgRating = 0;
			var rrTotProductRecommendations = 0;
			if (product.getProductRating() != null && product.getProductRating().getAverageRating() != null){ rrAvgRating = product.getProductRating().getAverageRating();}
			if (product.getProductRating() != null && product.getProductRating().getTotalProductRecomendations() != null){ rrTotProductRecommendations = product.getProductRating().getTotalProductRecomendations();}
			s_omtr.products=';' + selection.style.getStoreTypeCode() + '_' + selection.style.getNumber() 
									+ ';;;event28=' + selectStyleQtys.getTotalNumberofSkus() 
									+ '|event29=' + selectStyleQtys.getTotalAvailableSkus()
									+ '|event30=' + selectStyleQtys.getTotalNotAvailabeSkus()
									+ '|event31=' + selectStyleQtys.getTotalBackOrderedSkus()
									+ '|event61=' + rrAvgRating
									+ '|event62=' + rrTotProductRecommendations
									+ ';evar4=' + getCategoryID()  
									+ '|evar15=' + s_omtr.evar15;
	        
	        s_omtr.tl(true,'o','link');
		}
		
	    var addPromoCode = function(s_omtr){
	    	debug("[addPromoCode].... ");
	        var y = null;
	        var event44 = false;
	        var event45 = false;
	        var event46 = false;
	        var skuPromoCode = null;
	        var allSkus = selection.style.getSkus();
	        for(var k = 0; k < allSkus.length; k++) {
	        	skuPromoCode = allSkus[k].getPromoMdseTypeCode();
	        	if(skuPromoCode == 1){
	        		event44 = true;
	        	}else if(skuPromoCode == 2){
	        		event45 = true;
	        	}else if(skuPromoCode == 3){
	        		event46 = true;
	        	}        	
	        }
	        
	        if(event44){
	        	s_omtr.events = s_omtr.events + ",event44";
	        	s_omtr.linkTrackEvents = s_omtr.linkTrackEvents + ",event44"; 
	        }
	        if(event45){
	        	s_omtr.events = s_omtr.events + ",event45";
	        	s_omtr.linkTrackEvents = s_omtr.linkTrackEvents + ",event45"; 
	        } 
	        if(event46){
	        	s_omtr.events = s_omtr.events + ",event46";
	        	s_omtr.linkTrackEvents = s_omtr.linkTrackEvents + ",event46"; 
	        }   	
	    }
	    
	    var getCategoryID = function() {
	    	debug("[getCategoryID].... ");
	    	var categoryID = "";
	    	
	    	if(product.getParentProduct() != null){
	    		return 'SPR_'  + product.getParentProduct().getNumber() + '_' + product.getParentProduct().getLongName();
	    	}
	    	
	    	if (webAnalyticsParam != null && webAnalyticsParam != undefined) {	    		
	    		categoryID = webAnalyticsParam.getCmMerch();
	    	} else {
	    		categoryID = $.query.get('CM_MERCH');
	    	}
	    	
	    	var inetSructureNumber = $.query.get('inetStructNum');

	        if(categoryID != "" && categoryID == "SRCH"){
	        	categoryID = "SRCH_" + inetSructureNumber;
	        }
	        else if (categoryID == "") {
	           	categoryID = "PAGE_" + inetSructureNumber;
	        }

	        return categoryID;	    	
	    }
	}	

	this.makeBuyGridSelections = function(selObj){
		debug("[makeBuyGridSelections]  in standard buy grid......");
		// Setup the page to display the selections that are coming in. 
		
		// we will get only style number from shopping bag. Get the style object from product tree
		if (selObj.styleNumber != undefined  && selObj.styleNumber != null && 
				 (selObj.style == undefined || selObj.style == null || selObj.style == "")) {
			selObj.style = product.findStyleInProduct(selObj.styleNumber);
		}		
		// Display the style, if one needs to be preselected. 
		if (selObj.style != null){
			debug("[makeBuyGridSelections] " + selObj.style.getNumber());
			selection.style = selObj.style;
			thisStandardBuyGrid.featureTypeController.updateSelectionBasedOnSelectedStyle(); // get default features for default style
			selection.style = null; // default back to null, will be set by selectFeature method call
			thisStandardBuyGrid.featureTypeController.selectFeature(selection.primaryFeatureId,selection.secondaryFeatureId,selection.thirdFeatureId); // initialize style on view
			thisStandardBuyGrid.sizeColorController.colorSelect(null); // setup default color is there is one
			thisStandardBuyGrid.sizeColorController.highlightSelectedColorSwatch();
		}
		
		// Display the color code, if one needs to be preselected.
		if (selObj.colorCode != null) {
			debug("[makeBuyGridSelections] " + selObj.colorCode);
			thisStandardBuyGrid.sizeColorController.colorSelect(selObj.colorCode);
			thisStandardBuyGrid.sizeColorController.highlightSelectedColorSwatch();
 		}
		
		// Display the size code, if one needs to be preselected.
		if (selObj.sizeCode != null) {
			selObj.sizeCode = selObj.sizeCode.replace(/ /g,"");
			debug("[makeBuyGridSelections] " + selObj.sizeCode);
			thisStandardBuyGrid.sizeColorController.sizeSelect(selObj.sizeCode);
		}

		// Display the inseam length, if one needs to be preselected.
		if (selObj.inseam != null) {
			debug("[makeBuyGridSelections] " + selObj.inseam);
			thisStandardBuyGrid.hemmingController.inseamSelect(selObj.inseam);
		}
		
		// Display cuffing, if one needs to be preselected.
		if (selObj.cuffing != null) {
			debug("[makeBuyGridSelections] " + selObj.cuffing);
			thisStandardBuyGrid.hemmingController.cuffingSelect(selObj.cuffing);
		}
		
		// Display quantity, if one needs to be preselected.
		if (selObj.quantity != null) {
			debug("[makeBuyGridSelections] " + selObj.quantity);
			thisStandardBuyGrid.quantityController.quantitySelect(selObj.quantity);
		}
		
		var monogramController = thisStandardBuyGrid.valueAddedServicesController.monogramController;
		// Display the monogramming information, if one needs to be applied to the product.
		if (selObj.monogramApplied){
			monogramController.selectMonogram(true);
			
			// Mimic step 1 actions, update the monogram type.
			monogramController.selectStepOne();
			debug("[makeBuyGridSelections] " + selObj.monogramType);
			monogramController.selectMonogramType(selObj.monogramType);
			
			// Mimic step 2 actions, update monogram font and location.
			monogramController.selectStepTwo();
			debug("[makeBuyGridSelections] " + selObj.monogramFont);
			monogramController.selectMonogramFont(selObj.monogramFont);	
			debug("[makeBuyGridSelections] " + selObj.monogramLocation);
			if(selObj.monogramLocation != null){
				monogramController.selectMonogramLocation(selObj.monogramLocation);
			}
			
			// Mimic step 3, update the monogram text (based on monogram type).
			monogramController.selectStepThree();
			if (selObj.monogramType == 1){          // Single Initial
				debug("[makeBuyGridSelections] " + selObj.monogramSingleInitalText);
				monogramController.selectInitial(selObj.monogramSingleInitalText);
			} else if (selObj.monogramType == 2) {  // Initials
				for(var k =0; k < selObj.monogramMultiInitial.length; k++){
					debug("[makeBuyGridSelections] " + selObj.monogramMultiInitial[k]);
					monogramController.selectInitials(selObj.monogramMultiInitial[k], k);
				}
			} else if (selObj.monogramType == 3){ //Word
				debug("[makeBuyGridSelections] " + selObj.monogramWordText);
				monogramController.selectWord(selObj.monogramWordText);
			} else if (selObj.monogramType == 4){ //Multiline
				for(var k =0; k < selObj.monogramMultiLine.length; k++){
					debug("[makeBuyGridSelections--] " + selObj.monogramMultiInitial[k]);
					monogramController.selectMultiLine(selObj.monogramMultiLine[k], k);
				}
			}

			// Mimic applying the monogram, should show the recap container and the edit monogram button set.
			monogramController.selectApplyUpdateOrMonogram();
		}
		
		// Apply the school uniform school Number, if they need to be preselected.
		if (selObj.schoolNumber != null && product.getSchool() == null) {
			debug("[makeBuyGridSelections] " + selObj.schoolNumber);
			thisStandardBuyGrid.valueAddedServicesController.schoolUniformController.selectFindSchool(selObj.schoolNumber);
		}
		// Apply the school uniform school logo code, if they need to be preselected.
		if(selObj.schoolLogoCode != null && selObj.schoolLogoCode !=""){
			debug("[makeBuyGridSelections] " + selObj.schoolLogoCode);
			thisStandardBuyGrid.valueAddedServicesController.schoolUniformController.selectLogo(selObj.schoolLogoCode);
		}
		
		if (selObj.dropShipDayPhone != null){
			thisStandardBuyGrid.dropShipController.phoneSelect(selObj.dropShipDayPhone, false);
		}
		
		if (selObj.dropShipDayPhoneExt != null){
			thisStandardBuyGrid.dropShipController.extensionSelect(selObj.dropShipDayPhoneExt, false);
		}
		
		if (selObj.dropShipAltPhone != null){
			thisStandardBuyGrid.dropShipController.phoneSelect(selObj.dropShipAltPhone, true);
		}
		
		if (selObj.dropShipAltPhoneExt != null){
			thisStandardBuyGrid.dropShipController.extensionSelect(selObj.dropShipAltPhoneExt, true);
		}
		
		if (thisStandardBuyGrid.giftCardExtensionController != undefined && thisStandardBuyGrid.giftCardExtensionController != null)
			{
				if (selObj.personalizedRecipientEmail != null){
					thisStandardBuyGrid.giftCardExtensionController.giftCardMessageAreaController.setPersonalizedRecipientEmail(selObj.personalizedRecipientEmail, selection.primaryFeatureId);
				}
		
				if (selObj.personalizedTo != null){
					thisStandardBuyGrid.giftCardExtensionController.giftCardMessageAreaController.setPersonalizedTo(selObj.personalizedTo, selection.primaryFeatureId);
				}
				
				if (selObj.personalizedMessage != null){
					thisStandardBuyGrid.giftCardExtensionController.giftCardMessageAreaController.setPersonalizedMessage(selObj.personalizedMessage, selection.primaryFeatureId);
				}	
				
				if (selObj.personalizedFrom != null){
					thisStandardBuyGrid.giftCardExtensionController.giftCardMessageAreaController.setPersonalizedFromEmail(selObj.personalizedFrom, selection.primaryFeatureId);
				}
				
				if (selObj.gcAmount != null){
					thisStandardBuyGrid.giftCardExtensionController.amountController.setAmount(selObj.gcAmount);
				}
		}
        		
		// Always copy the itemID forward for modify condition
		selection.itemId = selObj.itemId;
		
		if (!(selObj.itemId == null || selObj.itemId == undefined || selObj.itemId.length == 0)) {
			selObj.mode = "update";
			selection.mode = selObj.mode;
		}
		
		if (selObj.mode == "update") {			
			thisStandardBuyGrid.shoppingBagController.setToUpdateMode();
		}
		

                
		// Run error checkers and mark errors on the page.
		thisStandardBuyGrid.shoppingBagController.checkAddToBagState();
	}
	
	init();
}
/**
 * jQuery.debugWindow - debug window logger
 * usage: $.debug("message");
 * @author mtambo
 **/

/* REQUIRES hoverIntent jQuery plugin (tested with ver. 5) */
//$.jsNamespace('com.landsend.productView');
var com;
if(com == undefined){
	com = new Object();
}
if(com.landsend == undefined){
	com.landsend = new Object();
}
if(com.landsend.productView == undefined){
	com.landsend.productView = new Object();
}

com.landsend.productView.util = new function(){
	var line=0, debug=($.query.get("debugExpand")==="true");
	this.debugExpand=function(msg){
		if(!debug)return;
		var clr = (line++ % 2 == 0)?"background-color:#E3E3D6;":"";
		var win = window.open("","debugWindow","width=700,height=600,resizable=yes,scrollbars=yes,status=no,alwaysraised=yes");
		win.document.writeln("<div style='border-top:solid .1em;font-size:small;"+clr+"'>"+new Date().toLocaleTimeString()+":"+ msg+"</div>\n");
		win.scrollTo(0,999999999);
	}; 	
}

com.landsend.productView.BundleView = function(bundleController){
	var isIE = window.leutil.ui.browser.isIE();
	var isIE6 = window.leutil.ui.browser.isIE6();
	var isIE7 = window.leutil.ui.browser.isIE7();
	var isiPad = window.leutil.ui.browser.isiPad();
	
	this.childProductView = function(productId,childProductController){
		var productId = productId;
		var heroViewer = "bundleHeroImage";     
		
		var bundleItem = "productGrid";
		var header = "bundleHeader";
		var tabs = "bundleTabs";
		var content = "bundleContent";
		var selectionsTab = "bundleTabSelections";
		var selectionsDisplay = "bundleTabSelectionsDisplay";
		var imagesTab = "bundleTabImages";
		var imagesDisplay = "bundleTabImagesDisplay";
		var descriptionTab = "bundleTabDescription";
		var descriptionDisplay = "productDesc";
		var bundleProductNameDisplay = "bundleProductName";
		var productNameDisplay = "productName";
		var reviewsTab = "bundleTabReviews";
		var reviewsDisplay = "bundleTabReviewsDisplay";
		var bundlePrice = "bundlePrice";
		var itemNumber = "itemNumberWrapper";
		var bundleButton = "bundleButton"; //gray select item button 
		var swatchImage = "swatchImage"; // pre-existing standard buy grid swatches
		var minimizedSwatchList = "bundleMinimizedSwatches";
		var swatchItem = "swatchImageProductLevel";
		var bundleColorChooser = "bundleColorChooser";		
		var clicker = "bundleClicker"; //transparent element used to trigger expansion of a minimized grid.
		var expander = "bundleExpander";
		var closer = "bundleCloser";
		var closerImageTab = "bundleCloserImageTab";
		var cart = "bundleCart";
		var cartItem = "bundleCartItem";
		var cartItemEdit = "bundleCartItemEdit";
		var cartItemRemove = "bundleCartItemRemove";
		var bundleLoader = "bundleLoader";
		var bundleFullScreenLink = "fullScreenBundleLink";
		
		var thisBundleView = this;		
		var viewState = 0; // 0 = closed, 1 = expanding, 2 = expanded	
		
		this.changeItemTab = function(tabName){
			thisBundleView.resetDisplay();           
			
			if(tabName == "images"){
				$("#"+buildCompoundKey(header)).addClass("pp-hide");
				$("#"+buildCompoundKey(imagesTab)).addClass("le-modal-tab-selected");
				$("#"+buildCompoundKey(imagesDisplay)).removeClass("pp-hide-alt pp-hide");
				thisBundleView.imageTabSwatches.selectColor(childProductController.getStyleNumber(),childProductController.getCurrentColorCode());
			}		
			else if(tabName == "reviews"){
				$("#"+buildCompoundKey(header)).removeClass("pp-hide");
				$("#"+buildCompoundKey(reviewsTab)).addClass("le-modal-tab-selected");
				$("#"+buildCompoundKey(reviewsDisplay)).removeClass("pp-hide");
				if(isiPad){
					$("#"+buildCompoundKey(reviewsDisplay)).css({overflow:"auto",height:"auto"});
				}
			}		
			else if(tabName == "description"){
				$("#"+buildCompoundKey(header)).removeClass("pp-hide");
				$("#"+buildCompoundKey(descriptionTab)).addClass("le-modal-tab-selected");
				$("#"+buildCompoundKey(descriptionDisplay)).removeClass("pp-hide");
				if(isiPad){
					$("#"+buildCompoundKey(descriptionDisplay)).css({overflow:"auto",height:"auto"});
				}
			}
			else{ // default to selection grid
				tabName = "selections";
				$("#"+buildCompoundKey(header)).removeClass("pp-hide");
				$("#"+buildCompoundKey(selectionsTab)).addClass("le-modal-tab-selected");
				$("#"+buildCompoundKey(selectionsDisplay)).removeClass("pp-hide-alt pp-hide");
			}
			childProductController.activeTab = tabName;
			window.swatchSelector.hilight(productId,childProductController.getStyleNumber());
			redraw();
		}
	
		this.makeActive = function(){
			$("#"+buildCompoundKey(bundleItem)).addClass("pp-bundle-item-hover");
		}
	
		this.makeInactive = function(){
			$("#"+buildCompoundKey(bundleItem)).removeClass("pp-bundle-item-hover");
		}
		
		var showLoadingIconTimer = null;
		this.showLoadingIcon = function(){
			showLoadingIconTimer = setTimeout(showLoadingIcon,500);
		}
		var showLoadingIcon = function(){
			if(childProductController.isInFlight()){
				$("#"+buildCompoundKey(bundleLoader)).fadeTo(0,.5).removeClass("pp-hide");
			}
		}		
		this.hideLoadingIcon = function(){
			clearTimeout(showLoadingIconTimer);
			$("#"+buildCompoundKey(bundleLoader)).addClass("pp-hide");
		}
		
		this.expand = function(){
			com.landsend.productView.util.debugExpand("Is child in flight " + productId + " isInFlight" + childProductController.isInFlight() + " ,viewState = " + viewState);
			if(viewState == 0){
				viewState = 1;
				
				this.hideLoadingIcon();
				isLoaded = true;
				thisBundleView.resetDisplay();			
				bundleController.minimizeItems();
				$("#"+buildCompoundKey(bundleProductNameDisplay)).addClass("pp-hide");
				$("#"+buildCompoundKey(productNameDisplay)).removeClass("pp-hide");
				$("#"+buildCompoundKey(content)).css("display","none");
				$("#"+buildCompoundKey(selectionsTab)).addClass("le-modal-tab-selected");
				$("#"+buildCompoundKey(selectionsDisplay)).removeClass("pp-hide-alt pp-hide");            
				
				$("#"+buildCompoundKey(clicker)).addClass("pp-hide");
				$("#"+buildCompoundKey(bundleItem)).addClass("pp-bundle-item-expanded").removeClass("pp-bundle-item-hover");            
				
				$("#"+buildCompoundKey(imagesDisplay)).addClass("pp-hide-alt");
				$("#"+buildCompoundKey(descriptionDisplay)).addClass("pp-hide");
				$("#"+buildCompoundKey(reviewsDisplay)).addClass("pp-hide");
				$("#"+buildCompoundKey(tabs)).removeClass("pp-hide");            
				
				if(isIE == false || (isIE6 == false && isIE7 == false)){
					$("#"+buildCompoundKey(bundlePrice)+", #"+buildCompoundKey(bundleButton)+", #"+buildCompoundKey(minimizedSwatchList)).stop().fadeOut(500);
					$("#"+buildCompoundKey(tabs)+", #"+buildCompoundKey(itemNumber)).stop().fadeIn(500);
					$("#"+buildCompoundKey(content)).stop().slideToggle(500,"swing",function(){$(this).css("overflow","visible")});
					$("#"+buildCompoundKey(bundleItem)).stop().animate({top:20,marginBottom:25}, 500, function(){
						scrollPage();
						window.swatchSelector.hilight(productId,childProductController.getStyleNumber());
						viewState = 2;
						com.landsend.productView.util.debugExpand("Setting child viewState to '2' from inside expand stop().fadeIn() method - " + productId + " isInFlight" + childProductController.isInFlight() + " ,viewState = " + viewState);
					});	
				}
				else{ // don't attempt animations in IE7 or earlier as it struggles to render
					$("#"+buildCompoundKey(bundlePrice)+", #"+buildCompoundKey(bundleButton)+", #"+buildCompoundKey(minimizedSwatchList)).css("display","none");
					$("#"+buildCompoundKey(tabs)+", #"+buildCompoundKey(itemNumber)).css("display","block");
					$("#"+buildCompoundKey(content)).css("display","block");
					$("#"+buildCompoundKey(bundleItem)).css({top:20,marginBottom:25});					
					viewState = 2;
					com.landsend.productView.util.debugExpand("Setting child viewState to '2' from inside expand() method - " + productId + " isInFlight" + childProductController.isInFlight() + " ,viewState = " + viewState);
					var t = setTimeout(scrollPage,200);
				}
			}
		}
		
		var moveHero = function(){
			myY = $("#"+buildCompoundKey(bundleItem)).position().top - $("#"+heroViewer).offset().top - 20;
			if(myY<0){ myY=0 }
			if(isIE == false || (isIE6 == false && isIE7 == false)){
				$("#"+heroViewer).animate({paddingTop:myY}, 500);
			}
			else{
				$("#"+heroViewer).css({paddingTop:myY});
			}			
		}
		
		var scrollPage = function(){
			myY = $("#"+buildCompoundKey(bundleItem)).offset().top - 25;
			if(myY < 0){ myY = 0 }		
			if(isIE == false || (isIE6 == false && isIE7 == false)){
				$('html, body').animate({scrollTop:myY}, 'slow', function() { 
						moveHero();
				});
			}
			else{		
				window.swatchSelector.hilight(productId,childProductController.getStyleNumber());
				$('html, body').scrollTop(myY);
				var t = setTimeout(moveHero,200);
			}
		}
		
		this.close = function(otherSelected){     
			com.landsend.productView.util.debugExpand("Close Child " + productId + " isInFlight" + childProductController.isInFlight() + " ,viewState = " + viewState);
			if(viewState == 2){
				var contentHeight = $("#"+buildCompoundKey(content)).height() + 20;	
				
				if(otherSelected){
					$("#"+buildCompoundKey(bundleItem)).removeClass("pp-bundle-item-expanded").removeClass("pp-bundle-item-hover");
				}
				else{
					$("#"+buildCompoundKey(bundleItem)).removeClass("pp-bundle-item-expanded").addClass("pp-bundle-item-hover");
				}	
				$("#"+buildCompoundKey(bundleProductNameDisplay)).removeClass("pp-hide");
				$("#"+buildCompoundKey(productNameDisplay)).addClass("pp-hide");
				$("#"+buildCompoundKey(clicker)).removeClass("pp-hide");	
				$("#"+buildCompoundKey(header)).removeClass("pp-hide"); 
				$("#"+buildCompoundKey(bundlePrice)+", #"+buildCompoundKey(bundleButton)+", #"+buildCompoundKey(minimizedSwatchList)).stop().fadeIn(0);	
				window.swatchSelector.hilight(productId);
				$("#"+buildCompoundKey(tabs)+", #"+buildCompoundKey(itemNumber)).stop().fadeOut(0);	
				$("#"+buildCompoundKey(content)).stop().slideToggle(0,function(){	
					$(this).css("overflow","visible");	
					$("#"+buildCompoundKey(bundleItem)).css("height","auto");
					com.landsend.productView.util.debugExpand("Inside stop() method - " + productId + " isInFlight" + childProductController.isInFlight() + " ,viewState = " + viewState);
					if(isiPad){
						$("#"+buildCompoundKey(bundleItem)).removeClass("pp-bundle-item-hover")
					}
				});	
				$("#"+buildCompoundKey(bundleItem)).stop().css("margin-bottom",contentHeight+"px").stop().animate({top:0,marginBottom:5}, 500);
				childProductController.viewClosed();
				viewState = 0;
				com.landsend.productView.util.debugExpand("Setting view state = '0' close() method - " + productId + " isInFlight" + childProductController.isInFlight() + " ,viewState = " + viewState);
			}else if(! childProductController.isInFlight() && viewState == 1){
				com.landsend.productView.util.debugExpand("Putting view on timer close - " + productId + " isInFlight" + childProductController.isInFlight() + " ,viewState = " + viewState);
				setTimeout(this.close,500);
			}
		}
	
		this.registerEvents = function(){
			$("#"+buildCompoundKey(selectionsTab)).click(function(e){
				e.preventDefault();
				childProductController.changeItemTab("selections");			
			});
		
			$("#"+buildCompoundKey(imagesTab)).click(function(e){
				e.preventDefault();
				childProductController.changeItemTab("images");			
			});
			
			$("#"+buildCompoundKey(descriptionTab)).click(function(e){
				e.preventDefault();
				childProductController.changeItemTab("description");			
			});
			
			$("#"+buildCompoundKey(reviewsTab)).click(function(e){
				e.preventDefault();
				childProductController.changeItemTab("reviews");			
			});
		
			$("#"+buildCompoundKey(header)).click(function(e){
				e.preventDefault();
				com.landsend.productView.util.debugExpand("Expand from view " + productId + " isInFlight" + childProductController.isInFlight() + " ,viewState = " + viewState);
				if(viewState == 0){
					childProductController.expand();
				}
			});
			
			$("#"+buildCompoundKey(bundleFullScreenLink)).click(function(e){
				e.preventDefault();
				if(viewState == 0){
					$("#"+buildCompoundKey(header)).click();
				}
				else{
					childProductController.launchFullScreenViewerForStyle();
				}
			});
		
			$("#"+buildCompoundKey(closer)).click(function(e){
				e.preventDefault();
				e.stopPropagation();
				thisBundleView.close();			
			});
		
			if(!isiPad){
				$("#"+buildCompoundKey(bundleItem)).hoverIntent(function(){
					if(viewState == 0 && ! childProductController.isInFlight()){
						thisBundleView.makeActive();	
					}
				}, function(){
					thisBundleView.makeInactive();
				});	
			}
			
			$("#"+buildCompoundKey(selectionsDisplay)).click(function(e){
				redraw();
			});
			$("#"+buildCompoundKey(selectionsDisplay)).find("select").change(function(){
				redraw();
			});
			
			this.minimizedSwatches.register();
		}
		
		var colorChangeNotAvailableTimer;
		this.colorChangeNotAvailable = function(message, colorCode, styleId){
			if(viewState != 0){
				window.leutil.ui.tooltipHandler.hide($("#bundleIcon_"+productId));
				window.leutil.ui.tooltip.show({
					button: $("#bundleIcon_"+productId),
					text: message,	
					type: "warning"
				});				
				clearTimeout(colorChangeNotAvailableTimer);
				colorChangeNotAvailableTimer = setTimeout(hideColorChangeNotAvailable,1000);
			}
			else if(childProductController.activeTab == "selections"){
				window.leutil.ui.tooltipHandler.hide($("#bundleIcon_"+productId));
				window.leutil.ui.tooltip.show({
					button: $("#bundleIcon_"+productId),
					text: message,	
					type: "warning"
				});	
				clearTimeout(colorChangeNotAvailableTimer);
				colorChangeNotAvailableTimer = setTimeout(hideColorChangeNotAvailable,1000);
			}
		}
		var hideColorChangeNotAvailable = function(){
			window.leutil.ui.tooltipHandler.hide($("#bundleIcon_"+productId));
		}

		this.minimizedSwatches = new function(){
			var items;
			var thisRef = this;
			
			this.register = function(){
				items = $("#"+buildCompoundKey(minimizedSwatchList)).find("a");
				items.each(function(){
					if(!isiPad){
						$(this).hoverIntent(function(){
							childProductController.colorHoverOver($(this).attr("id").split("_")[2]);
						}, function(){
							childProductController.colorHoverOut();
						});	
					}			
					$(this).bind("click",function(e){						
						e.preventDefault();
						e.stopPropagation();	
						if(viewState == 0 && ! childProductController.isInFlight()){
							childProductController.colorSelect($(this).attr("id").split("_")[2]);	
							thisRef.select(childProductController.getCurrentColorCode());	
						}
					});
				});
				window.swatchSelector.hilight(productId);
			}
		
			this.select = function(colorCode){
				items.each(function(){
					if($(this).attr("id").split("_")[2] == colorCode){
						$(this).addClass("pp-selected");
					}
					else{
						$(this).removeClass("pp-selected");
					}
				});
				window.swatchSelector.hilight(productId);
			}
		}
		
		this.imageTabSwatches = new function(){	
			var sets = [];			
			this.selectColor = function(styleId,colorCode){
				sets[styleId].swatches.each(function(){
					if($(this).attr("id").split("_")[3] == colorCode){
						$(this).addClass("pp-selected");
					}
					else{
						$(this).removeClass("pp-selected");
					}
				});
				window.swatchSelector.hilight(productId,styleId);
			}
			this.selectStyle = function(styleId){
				$("#"+buildCompoundKey(bundleColorChooser,styleId)).css("display","block").siblings().css("display","none");
			}
			this.register = function(styleId){
				var temp = {};
				temp.group = $("#"+buildCompoundKey(bundleColorChooser,styleId));
				temp.swatches = temp.group.find("a");
				
				temp.swatches.each(function(){					
					if($(this).data("gridSwatch")!= "null"){			
						$(this).data("gridSwatch", $("#swatchImage_"+$(this).attr("id").split("_")[1]+"_"+styleId+"_"+$(this).attr("id").split("_")[3]));
						
						$(this).bind("click",function(e){	
							$(this).data("gridSwatch").trigger("click");
							e.preventDefault();
						});				
						$(this).hoverIntent(function(){
							$(this).data("gridSwatch").trigger("mouseover");			
						}, function(){
							$(this).data("gridSwatch").trigger("mouseout");
						});
						
						$(this).data("gridSwatch").data("imageSwatch",$(this));
						$(this).data("gridSwatch").bind("click",function(e){
							temp.swatches.removeClass("pp-selected");
							$(this).data("imageSwatch").addClass("pp-selected");
							window.swatchSelector.hilight(productId,styleId);
							e.preventDefault();
						});
					}
				});
				
				sets[styleId] = temp;
			}
		}
		
		this.updateBundleItemImage = function(imgUrl){
			$("#bundleIcon_"+productId).attr("src", imgUrl);
			window.leutil.ui.tooltipHandler.hide($("#bundleIcon_"+productId));
		}
			
		var redraw = function(){ // hack to force IE7 to redraw drop shadow correctly when the buy grid updates size
			$("#"+buildCompoundKey(bundleItem)).css("position","static");
			$("#"+buildCompoundKey(bundleItem)).css("position","relative");
		}
	
		this.resetDisplay = function(){ // unselect all tabs and hide all content
			$("#"+buildCompoundKey(selectionsTab)).removeClass("le-modal-tab-selected").addClass("le-modal-tab");
			$("#"+buildCompoundKey(imagesTab)).removeClass("le-modal-tab-selected").addClass("le-modal-tab");
			$("#"+buildCompoundKey(descriptionTab)).removeClass("le-modal-tab-selected").addClass("le-modal-tab");
			$("#"+buildCompoundKey(reviewsTab)).removeClass("le-modal-tab-selected").addClass("le-modal-tab");
			$("#"+buildCompoundKey(selectionsDisplay)).addClass("pp-hide");
			$("#"+buildCompoundKey(imagesDisplay)).addClass("pp-hide-alt");
			$("#"+buildCompoundKey(descriptionDisplay)).addClass("pp-hide");
			$("#"+buildCompoundKey(reviewsDisplay)).addClass("pp-hide");  
		}  
		
		this.cart = new function(){
			var cartDisplay = null;
			var itemList;
			
			this.init = function(){
				cartDisplay = cartTemplate.clone();
				$("#"+buildCompoundKey(content)).after(cartDisplay);
				itemList = cartDisplay.find("ul.pp-cart-items");				
			}
			
			this.showCartDisplay = function(){
				cartDisplay.removeClass("pp-hide");
			}
			
			this.hideCartDisplay = function(){
				cartDisplay.addClass("pp-hide");
			}
			
			this.clearCartDisplay = function(){
				itemList.html("");
			}
			
			var cartTemplate = 
				$('<div class="pp-cart pp-hide">' +
					'<h3>Added to <a href="https://' + window.location.host + '/co/ShoppingBag.html?refer=' + encodeURIComponent(window.location.href) + '">Shopping Bag</a></h3>' +
					'<ul class="pp-cart-items">' +
					'</ul>' +
				'</div>');

			var printGiftBox = function(selection){
				var giftBoxed = "";
				if(selection.giftBox){
					giftBoxed = '<p>Gift Boxed </p>';
				}	
				return giftBoxed;
			}			
			
			var printMongramming = function(selection){
		    	var monogramValue = "";
		    	if(selection.monogramType == 1){ // initial 
	            	monogramValue = selection.monogramSingleInitalText;
				}else if(selection.monogramType == 2){ // initials 
					monogramValue = selection.monogramMultiInitial.join("");
				}else if(selection.monogramType == 3){ // word 
					monogramValue = selection.monogramWordText;
				}
				else if(selection.monogramType == 4){// multi-word
		    		var realCounter = 1;
		    		for(var i=0; i < selection.monogramMultiLine.length; i++){ 
		    			if(i != 0){
		    				monogramValue = monogramValue + ";";
		    			}
		    			monogramValue = monogramValue + selection.monogramMultiLine[i];
		    		}
				}	
		    	
		    	if(monogramValue.length > 0){
		    		monogramValue = '<p>Monogram <span>'+monogramValue+'</span></p>';
		    	}
		    	
				return monogramValue;
			}
			
			var printInseam = function(selection){
				r = "";
				if(selection.inseam != null){
					var inseamText = (selection.inseam == "UNF") ? "Unfinished" : selection.inseam;
					r = '<p>Inseam <span>'+inseamText +'</span></p>'
					if(selection.cuffing != null && selection.cuffing == "cuffed"){
						r += '<p>Hemming <span>Cuffed</span></p>';
					}
					else if(selection.cuffing != null && selection.cuffing == "uncuffed"){
						r += '<p>Hemming <span>Uncuffed</span></p>';
					}
				}
				return r;
			}			

			var printStyleName = function(selection){
				return "<p>"+ selection.style.getLongName() +"</p>";
			}
			
			
			this.addItem = function(myObject){
				var html = "";
				
				if(myObject.sku.getSize() != undefined && myObject.sku.getSize() != null){
					myObject.size = '<p>Size <span>'+myObject.sku.getSize().getDisplayName() +'</span></p>'
				}
				else{
					myObject.size = "";
				}	
				if(myObject.colorCode != undefined && myObject.colorCode != null){
					var colorName = "Unknown";
					var colorSwatchURL = "#";
					for(var s=0; s < myObject.style.getFeatureTreeLeaf().getSwatches().length; s++){
						if (myObject.colorCode === myObject.style.getFeatureTreeLeaf().getSwatches()[s].getColor().getCode()){
							colorName = myObject.style.getFeatureTreeLeaf().getSwatches()[s].getColor().getName();
							colorSwatchURL = myObject.style.getFeatureTreeLeaf().getSwatches()[s].getUrl();
						}
					}
					myObject.color = '<p><span class="pp-cart-item-color-swatch" style="background-image: url(\'' + colorSwatchURL + '\');"></span> Color <span>' + colorName + '</span></p>'
				}
				else{
					myObject.color = "";
				}			
				leutil.ui.modalHandler.hideAll();  //Here to close the quick Model in case of update item from QV
				
				html = '<li id="'+buildCompoundKey(cartItem,myObject.itemId)+'">' +
						'<div class="pp-cart-item-options">' +
							'<a href="#" id="'+buildCompoundKey(cartItemEdit,myObject.itemId)+'">Edit</a>&nbsp;<span>|</span>&nbsp;<a href="#" id="'+buildCompoundKey(cartItemRemove,myObject.itemId)+'">Remove</a>' +
						'</div>' +
						'<div class="pp-cart-item-attributes">' +
							printStyleName(myObject) + 
							myObject.color + 
							myObject.size + 
							printInseam(myObject) + 
							printMongramming(myObject) + 
							printGiftBox(myObject) +
						'</div>' +
						'<div class="pp-cart-item-summary">' +
							'<p class="pp-cart-item-price">' +
								'<span class="pp-accessibility-text">Price</span>' +
								'<span>$ '+Number(myObject.itemSubTotal).toFixed(2)+'</span>' +
								'</p>' +
							'<p>Qty <span>'+myObject.quantity+'</span></p>' +
						'</div>' +
						'<div class="clear-float"> </div>' +
					'</li>';
				
				itemList.append(html);
	     		thisBundleView.close(true);					
				
			   $("#"+buildCompoundKey(cartItemEdit,myObject.itemId)).bind("click",function(e){
						editItem(myObject);
						e.preventDefault();
				});
			   $("#"+buildCompoundKey(cartItemRemove,myObject.itemId)).bind("click",function(e){
					removeItem(myObject);
					e.preventDefault();
				});	
			}

			var cancelUpdateBag = function(){
				leutil.ui.modalHandler.hideAll();
			}					
			
			var quickViewCallBack = function(eventType,request,quickViewBuyGrid){
				if(eventType == "preLoadCachedIntance"){ //If this is part of bundle page edit call then we need to switch ids
					leutil.toogleIds.checkAndToggle("productGrid_", request.productId);
					leutil.toogleIds.checkAndToggle("QV_", request.productId);						
				}
				else if(eventType == "preLoadNewIntance"){ //If this is part of bundle page edit call then we need to switch ids
					leutil.toogleIds.checkAndToggle("productGrid_",request.productId);						
				}				
				else if(eventType == "postLoadNewIntance"){
					quickViewBuyGrid.getStandardBuyGridController().registerCallbackForShoppingBag(childProductController.addedToCart);
					quickViewBuyGrid.getStandardBuyGridController().registerCallbackForCancelUpdateBag(cancelUpdateBag);		
				}		
				else if(eventType == "closeQuickView"){
					leutil.toogleIds.checkAndToggle("QV_", request.productId);
					leutil.toogleIds.checkAndToggle("productGrid_", request.productId); 			
				}	
			}
			
			var editItem = function(myObject){
				var showRR = false;
				com.landsend.quickViewService.getQuickView(myObject.productNumber,-1,'',myObject,quickViewCallBack, showRR);
			}
			
			var removeItem = function(myObject){	
				childProductController.removeItem(thisBundleView,myObject)
			}
		}
		
		//used to build a compound key based on provided key values. Always prefixes the product id.
		var buildCompoundKey = function(keyPrefix,key1,key2,key3){
			var key = "";
			if(key1 != null && key2 != null && key3 != null){
				key = "_" + key1 + "_" + key2 + "_" + key3;
			}else if(key1 != null && key2 != null){
				key = "_" + key1 + "_" + key2;
			}else if(key1 != null){
				key = "_" + key1;
			}     
		
			key = "_" + productId + key;
			if(keyPrefix != null || keyPrefix != undefined){
				key = keyPrefix + key;
			}
			
			return key;
		}			
	}
}
 

com.landsend.productView.BundleController = function(prdtDisplayGroup,productPage){
	thisBundleController = this;
	var prodViewNs = com.landsend.productView;
	var bundleView = new prodViewNs.BundleView(this);
	var productDisplayGroup = prdtDisplayGroup;
	var childProductControllers = new Array();
	var inFlightProductId = null;
	var queryStringSelectionObject = null;
	var inFlight = false;
	
	var init = function(){
		com.landsend.productView.util.debugExpand("Start it up");
		queryStringSelectionObject = productPage.buildSelectionFromQueryString();
		prodViewNs.GlobalManager.setBundleController(thisBundleController);
		var isFirstBuyGrid = true;
		for(var i = 0; i < productDisplayGroup.getProductDisplays().length; i++){ 
			var childProductController = new thisBundleController.childProductController(productDisplayGroup.getProductDisplays()[i]);
			childProductControllers.push(childProductController);	
			
			if(queryStringSelectionObject.colorCode != null){ // this is currently used only for a reverse lookup (example: coming from index)
				childProductController.colorSelectNoExpand(queryStringSelectionObject.colorCode);				
			}
			
			if(prdtDisplayGroup.reversedLookup() && isFirstBuyGrid){ // this is currently used only for a reverse lookup (example: coming from index)
				childProductController.expand();
				isFirstBuyGrid = false;	
			}
		}
		if (!prdtDisplayGroup.reversedLookup()){
			if (productDisplayGroup.getProduct().getRootFeature().getImageSetCollection().getImageSetList().length > 0){
				thisBundleController.bundleProductPhotoViewerController.init(null,productDisplayGroup.getProduct().getRootFeature().getImageSetCollection(), null, null, false);
			}
			leutil.gomez.nameEvent("buyGridBuilt");
		}
	}
	
	
	this.initializePhotoViewer = function(productDisplay, feature){
		if (productDisplayGroup.reversedLookup() && productDisplay.getProduct().getNumber() == productDisplayGroup.getProductDisplays()[0].getProduct().getNumber()){
			var featureToUse = feature;
			if (featureToUse == null || featureToUse == undefined){
				if (productDisplay.getRequestedFeature() != null) { 
					featureToUse = productDisplay.getRequestedFeature();
				} else {
					featureToUse = productDisplay.getProduct().getRootFeautre().getFirstStyle().getFeatureTreeLeaf();
				}
			}
				
			var	imagSetcoll = featureToUse.getImageSetCollection();
			var swatchList = featureToUse.getSwatches();
			var colorCode = queryStringSelectionObject.colorCode;		
			var colorsByPriceCodeBean = featureToUse.getFirstStyle().getColorsByPriceCodeBean();
			var styleNumber = featureToUse.getFirstStyle().getNumber();
			if (!featureToUse.isColorCodeValid(colorCode)){ colorCode = swatchList[0].getColor().getCode();}
			
			if (imagSetcoll.getImageSetList().length > 0){
				thisBundleController.bundleProductPhotoViewerController.init(styleNumber, imagSetcoll, swatchList, colorCode, true, colorsByPriceCodeBean);
			}
		}
	}
	
	this.findChildProductController = function(productId){
		for(var y = 0;y < childProductControllers.length; y++){	
			if(childProductControllers[y].getProduct().getNumber() == productId){
				return childProductControllers[y];
			}
		}			
	}	
	
	this.childProductController = function(productDisplay){
		var thisRef = this;
		var product = productDisplay.getProduct(); // shortcut reference
		var view = new bundleView.childProductView(product.getNumber(),this);
		var standardBuyGrid = null;
		var lineItems = new Array();
		
		var colorSelectInProgress = false;
		// If we are coming from the index with a predefined feature via refinements?
		var currentStyle = productDisplay.getRequestedFeature().getFirstStyle();
		var currentColorCode = null;
		var bundleImageQryStr = '?' + com.landsend.global.PageConfigParms.BUNDLE_PAGE_THUMBNAIL_PRESET_STRING;
		
		this.getCurrentColorCode = function(){ return currentColorCode;	}		
		this.getStyleNumber = function(){ return currentStyle.getNumber(); }
		this.getProduct = function(){return product;}

		this.isInFlight = function(){
			if(product.getNumber() == inFlightProductId){
				return true;
			}
			return false;
		}		
		
		this.changeItemTab = function(tabName){
			view.changeItemTab(tabName);
			this.webAnalyticsController.changeItemTabEvent(tabName);
		}
		
		this.launchFullScreenViewerForStyle = function(){
			getStandardBuyGrid().productPhotoViewerController.launchFullScreenPhotoViewer(
					this.getProduct().getNumber(), this.getStyleNumber(), currentStyle.getFeatureTreeLeaf().getImageSetCollection(), 
					currentStyle.getFeatureTreeLeaf().getSwatches(), this.getCurrentColorCode(), 0);
		}
		
		this.webAnalyticsController = new function(){
			
			this.changeItemTabEvent = function(tabName){
				if(tabName == "selections"){
					return;
				}
				$.debug('WebAnalyticsController.changeItemTabEvent for style number ' + currentStyle.getNumber());
				s_omtr = s_gi(s_account);
				s_omtr.linkTrackVars='products,events';
				if(tabName == "images"){
					s_omtr.linkTrackEvents='event64';
					s_omtr.events='event64';
				}else if(tabName == "description"){
					s_omtr.linkTrackEvents='event65';
					s_omtr.events='event65';					
				}else if(tabName == "reviews"){
					s_omtr.linkTrackEvents='event66';
					s_omtr.events='event66';					
				}
				s_omtr.products=';'  + currentStyle.getStoreTypeCode() + '_' + currentStyle.getNumber();
				s_omtr.tl(true,'o','link'); 
			}
		}
		
		this.expand = function(){
			if(inFlightProductId != null){
				com.landsend.productView.util.debugExpand("Return expand in progress - " + inFlightProductId);
				return;
			}else{
				inFlightProductId = product.getNumber();
				com.landsend.productView.util.debugExpand("Setting new inflight Id = " + inFlightProductId);
			}
			
			if(standardBuyGrid == null){
				com.landsend.productView.util.debugExpand("Calling show icon " + product.getNumber() + " inFlight = " + inFlight + " / " + inFlightProductId);
				view.showLoadingIcon();	
				com.landsend.productService.getProductBasedOnSingleProduct(product.getNumber(),fullProductLoadCallback,'product',productDisplayGroup.getProduct().getNumber());
			}else{			
				setupBuyGridForDisplay();
				standardBuyGrid.webAnalyticsController.sendStyleChangeEvents();
				inFlightProductId = null;
				com.landsend.productView.util.debugExpand("Setting in flight to null from expand- " + inFlightProductId);
			}
		}
		
		var fullProductLoadCallback = function(fullProduct){	
			com.landsend.productView.util.debugExpand("Set in flight false " + product.getNumber() + " inFlight = " + inFlight + " / " + inFlightProductId);
			
			$.ajax({
				   async:false,
				   url: "/pp/BundleView~" + productDisplayGroup.getProduct().getNumber() + "_" + product.getNumber() +".html",
				   success:function(html){
						$("#bundleExpandedViewGrid_" + product.getNumber()).html(html);
				   },
				   error:function(){
						leutil.ui.modalHandler.show({
							content:com.landsend.productView.Messages.findMessage(29).text,
		                    cssClass:"le-modal-alert",
		                    dialogue:true,
		                    scrollable:false
						});					   
				   },
				   timeout:10000,
				   type:"GET",
				   cache:false
			});			
			view.cart.init();
			product = fullProduct[0].getProduct();
			prodViewNs.GlobalManager.getBundleController().initializePhotoViewer(fullProduct[0]);
			var originalRequestedFeature = productDisplay.getRequestedFeature();
			productDisplay = fullProduct[0];
			
			// copy/reset the requested feature
			if(originalRequestedFeature != null){
				var featuresFromProduct = productDisplay.getProduct().getAllFeatures();
				for(var r=0; r<featuresFromProduct.length; r++){
					if(featuresFromProduct[r] != null && featuresFromProduct[r].getFeatureNumber() == originalRequestedFeature.getFeatureNumber()){
						productDisplay.setRequestedFeature(featuresFromProduct[r]);
						break;
					}
				}
			}
			product.setParentProduct(productDisplayGroup.getProduct());
			
			// reset selected style with full style object
			for(var j=0; j<product.getStylesAsTheyAppearInTree().length; j++){
				if(product.getStylesAsTheyAppearInTree()[j].getNumber() == currentStyle.getNumber()){
					currentStyle = product.getStylesAsTheyAppearInTree()[j];
					break;
				}
			}
			
			getStandardBuyGrid(); // make sure we have a buygrid object to work with
			//standardBuyGrid.makeBuyGridSelections(queryStringSelectionObject);
			setupBuyGridForDisplay();
			view.hideLoadingIcon();	
			
		    if((ratings.leActive && !location.host.match("canvas")) || (ratings.canvasActive && location.host.match("canvas"))) {
		    	bvLoadRR(product.getNumber());
		    } else {
		    	bvCssAction()
		    }			
		    
		    if(prdtDisplayGroup.reversedLookup() && prdtDisplayGroup.getProductDisplays()[0].getProduct().getNumber() == product.getNumber()){
		    	leutil.gomez.nameEvent("buyGridBuilt");
		    }
		    
			inFlightProductId = null;
			com.landsend.productView.util.debugExpand("Setting in flight to null from fullProductLoadCallback- " + inFlightProductId);
		}
		
		var setupBuyGridForDisplay = function(){
			standardBuyGrid.sizeColorController.colorSelect(currentColorCode);
			standardBuyGrid.sizeColorController.highlightSelectedColorSwatch();	
			showStyleThumbnailImage(true);
			view.minimizedSwatches.select(currentColorCode);
			if(inFlightProductId == product.getNumber()){
				view.expand();
			}
		}
		
		var getStandardBuyGrid = function(){
			if(standardBuyGrid == null){
				standardBuyGrid = new prodViewNs.StandardBuyGridController(productDisplay,null);
				standardBuyGrid.registerCallbackForShoppingBag(thisRef.addedToCart);
				standardBuyGrid.registerCallbackForColorChange(colorChanged);	
				standardBuyGrid.registerCallbackForStyleChange(styleChanged);
				for(var j=0; j<product.getStylesAsTheyAppearInTree().length; j++){
					view.imageTabSwatches.register(product.getStylesAsTheyAppearInTree()[j].getNumber());
				}
				view.hideLoadingIcon();
			}
			return standardBuyGrid;
		}
		
		var init = function(){
			registerEvents();
			
			if(product.getRootFeature().getSwatches() != null && product.getRootFeature().getSwatches().length > 0){ 
				currentColorCode = product.getRootFeature().getSwatches()[0].getColor().getCode();
			}
		}
		
		var registerEvents = function(){
			view.registerEvents();
		}
		
		var reprintLineItems = function(){
			view.cart.clearCartDisplay();
			
			for(var y = 0;y < lineItems.length; y++){	
				view.cart.addItem(lineItems[y]);
			}
			
			if(lineItems.length > 0){
				view.cart.showCartDisplay();
			}else{
				view.cart.hideCartDisplay();
			}
		}
		
		var buildItemTotal = function(skuItem){
			var itemTotal = 0;
			var monogramPrice = 0;
			var logoPrice = 0;
			var giftBoxPrice = 0;
			
			if(skuItem.monogram != null && skuItem.monogram.monogramPrice != null && skuItem.monogram.monogramPrice > 0){
				monogramPrice = skuItem.monogram.monogramPrice;
			}
			
			if(skuItem.isGiftBoxSelected){
				giftBoxPrice = skuItem.giftBoxPrice;
			}
			
			if(skuItem.logo != null && skuItem.logo.price != null && skuItem.logo.price > 0){
				logoPrice = skuItem.logo.price;
			}
			
			if(skuItem.unitPrice != null && skuItem.unitPrice > 0 && skuItem.quantity != null && skuItem.quantity > 0){
				itemTotal = skuItem.quantity *(skuItem.unitPrice + monogramPrice + giftBoxPrice + logoPrice);
				if(itemTotal > 0){
					itemTotal = itemTotal / 100;
				}
			}
			
			return itemTotal;
		}
		
		var resetSelectionObjects = function(eventType,buyGrid,selection,shoppingBag){ 
			
			if(eventType == "closeInlineBag"){ // new item added
				lineItems.push(selection);
			}
			
			if(eventType == "update"){ // make sure we have the most recent selection object to go with the updated line item
				for(var y = 0;y < lineItems.length; y++){	
					if(lineItems[y].itemId == selection.itemId){
						lineItems[y] = selection;
					}
				}
			}
			
			var bagItems = new Array(); // build reference sku item array
			if(shoppingBag != null && shoppingBag.basket != null && shoppingBag.basket.shipToArray != null){
				for(var y = 0;y < shoppingBag.basket.shipToArray.length; y++){	
					var shipTo = shoppingBag.basket.shipToArray[y];
					if(shipTo != null && shipTo.skuItemArray != null){
						for(var i = 0;i < shipTo.skuItemArray.length; i++){
							var skuItem = shipTo.skuItemArray[i];
							if(skuItem != null){
								bagItems[skuItem.key] = skuItem;
							}
						}
					}
				}
			}
			
			// update prices on existing items
			for(var y = 0;y < lineItems.length; y++){	
				var skuItem = bagItems[lineItems[y].itemId];
				if(skuItem != null){
					lineItems[y].itemSubTotal = buildItemTotal(skuItem);
				}
			}
			
			reprintLineItems();
		}
		
		this.addedToCart = function(eventType,buyGrid,selection,shoppingBag){
			if(eventType == "update" || eventType == "closeInlineBag"){
				resetSelectionObjects(eventType,buyGrid,selection,shoppingBag);
			}
			
			if(eventType == "update" || eventType == "add" || eventType == "removed"){
				com.landsend.persistentBag.controller.updateBagDisplay();
			}

			if(eventType == "update"){
		    	var itemIdHolder = selection.itemId;
		    	selection.itemId = null;
		    	standardBuyGrid.makeBuyGridSelections(selection);
				selection.itemId = itemIdHolder;				
			}
		}
		
		this.refreshShipTo =  function(){
			if (standardBuyGrid != null){
				standardBuyGrid.shipToController.init();
			}
		}
		
		
		this.colorHoverOver = function(colorCode){
			colorSelectInProgress = false;
			showProductThumbnailImage(colorCode, false);
		}		

		this.colorHoverOut = function(){
			if (!colorSelectInProgress) showProductThumbnailImage(currentColorCode, false);
		}		

		this.colorSelectNoExpand = function(colorCode){
			var swatches = product.getRootFeature().getSwatches();
			var found = false;
			for(var y = 0;y < swatches.length; y++){	
				if(swatches[y].getColor().getCode() == colorCode){
					found = true;
					break;
				}
			}
			if(found){
				currentColorCode = colorCode;
				view.minimizedSwatches.select(colorCode);
				showStyleThumbnailImage(false);
			}
		}
		
		this.colorSelect = function(colorCode){
			colorSelectInProgress = true;
			currentColorCode = colorCode;
			this.expand();
		}
		
		var showStyleThumbnailImage = function(){			
			var imgSetCollection = currentStyle.getFeatureTreeLeaf().getImageSetCollection();
			if (imgSetCollection.getImageSetList().length > 0){
				var viewerImage = imgSetCollection.getImageSetList()[0].getColorImage(currentColorCode);
				if (viewerImage == null){
					viewerImage = imgSetCollection.getImageSetList()[0].getProductImageList()[0];
				}
				if (viewerImage != null){
					if (viewerImage.getImageServed() == true){
						view.updateBundleItemImage("http://s7.landsend.com" + viewerImage.getUrl() + bundleImageQryStr);
					} else {
						view.updateBundleItemImage("http://www.landsend.com" + viewerImage.getUrl());
					}
				} else {
					view.colorChangeNotAvailable(prodViewNs.Messages.findMessage(30).text, currentColorCode);						
				}
			}
		}
		
		var showProductThumbnailImage = function(colorCode, useDefaultColor){
			//Show the color as selected.
			view.minimizedSwatches.select(colorCode);	
			
			//Adjust the image to the right color.
			var imgSetCollection = product.getRootFeature().getImageSetCollection();
			if (imgSetCollection.getImageSetList().length > 0 ){
				var viewerImage = imgSetCollection.getImageSetList()[0].getColorImage(colorCode);
				if (viewerImage == null && useDefaultColor){
					viewerImage = imgSetCollection.getImageSetList()[0].getProductImageList()[0];
				}
				if (viewerImage != null){	
					if (viewerImage.getImageServed() == true){
						view.updateBundleItemImage("http://s7.landsend.com" + viewerImage.getUrl() + bundleImageQryStr);
					} else {
						view.updateBundleItemImage("http://www.landsend.com" + viewerImage.getUrl());
					}
				} else {
					view.colorChangeNotAvailable(prodViewNs.Messages.findMessage(30).text, colorCode);
				}			
			}
		}
		
		
		this.viewClosed = function(){
			showProductThumbnailImage(currentColorCode, true);
		}


		var colorChanged = function(product,colorCode){
			//If we are working with the first child product, then update the photoviewer color
			if (productDisplayGroup.reversedLookup() && product.getNumber() == productDisplayGroup.getProductDisplays()[0].getProduct().getNumber()){				
				thisBundleController.bundleProductPhotoViewerController.updateColor(colorCode);
			}
			currentColorCode = colorCode;
			showStyleThumbnailImage(false);
		}

		
		var styleChanged = function(product, style){
			currentStyle = style;
			view.imageTabSwatches.selectStyle(currentStyle.getNumber());
			if (productDisplayGroup.reversedLookup() && product.getNumber() == productDisplayGroup.getProductDisplays()[0].getProduct().getNumber()){
				thisBundleController.initializePhotoViewer(productDisplayGroup.getProductDisplays()[0], style.getFeatureTreeLeaf());
			}
		}
		
		this.minimize = function(){
			view.close(true);
		}		
		
		this.removeItem = function(bundleView, deletedItem) {
			
			var deletionSuccess = function(deleteResponse) {
				
				// remote item from list
				var newLineItemList = new Array();
				for(var y = 0;y < lineItems.length; y++){	
					if(lineItems[y].itemId != deletedItem.itemId){
						newLineItemList.push(lineItems[y]);
					}
				}
				lineItems = newLineItemList;
				resetSelectionObjects('removeItem',null,null,deleteResponse);
			}
			
			var onError = function(error){
				leutil.ui.modalHandler.show({
					content:com.landsend.productView.Messages.findMessage(29).text,
                    cssClass:"le-modal-alert",
                    dialogue:true,
                    scrollable:false
				});
			}	
			
			standardBuyGrid.shoppingBagController.removeItemFromBag(deletedItem.itemId,deletionSuccess,onError);
		}		
		
		init();
	}  	

	this.minimizeItems = function(){
		for(var i = 0;i < childProductControllers.length;i++){
			childProductControllers[i].minimize();
		}
	} 	
	
	this.bundleProductPhotoViewerController = new function(){
		var thisPhotoController = this;
		var photoDisplay = null;
		var fullScreenPhotoDisplay = null;
		var currentStyleNumber = null;
		var photoDisplays = new Object();
		var colorsByPriceBeans = new Object();
		
		this.init = function(styleNumber, imageSetCollection, swatchList, colorCode, useSwatch, colorsByPriceCodeBean){
			// Hide the photo viewer that is currently showing.
			if (currentStyleNumber != null) {photoDisplays[currentStyleNumber].hide();}
			currentStyleNumber = styleNumber;			
			if (currentStyleNumber == null || photoDisplays[currentStyleNumber] == null){				
				fullScreenPhotoDisplay = new com.landsend.productView.FullScreenPhotoDisplay(); 
				photoDisplay = new com.landsend.productView.PhotoDisplay();
				photoDisplay.init(productDisplayGroup.getProduct().getNumber(), styleNumber, imageSetCollection, swatchList, false, colorCode, null, null);
				photoDisplay.registerForFullScreenEvent(launchFullScreenPhotoViewer);
				photoDisplay.show();
				if (colorCode != null){
					photoDisplay.setPhotoViewerColorCode(colorCode);
					photoDisplay.updateViewerColor();
				}
				colorsByPriceBeans[currentStyleNumber] = colorsByPriceCodeBean;
				photoDisplays[currentStyleNumber] = photoDisplay;
			} else {
				photoDisplays[currentStyleNumber].show();
			}
		}		
		
		var launchFullScreenPhotoViewer = function(productNumber, styleNumber, imageSetCollection, swatchList, colorCode, imagePosition){
			// The full screen photo viewer on the bundle page will have no style number if we are using the hero shot setup for the bundle product. 
			// If we are pulling in the images from a child product, then the style number will correspond to one of the styles within that child product. 
			// We can use this to differentiate whether we should tie a color change call back function. Color Changes need to be reflected only if we are
			// pulling in the images from a child product. There are no color chips showing within the hero shot for the bundle product. 
			var fullScreenColorChangeCallback = (styleNumber == null ? null : thisPhotoController.updateColor);
			fullScreenPhotoDisplay.launchFullScreenViewer(productNumber, imageSetCollection, swatchList, colorsByPriceBeans[currentStyleNumber], colorCode, imagePosition, fullScreenColorChangeCallback , false);
		}
		
		this.updateColor = function(colorCode){
			photoDisplays[currentStyleNumber].setPhotoViewerColorCode(colorCode);
			photoDisplays[currentStyleNumber].updateViewerColor();
		}		
	}
		
	init();
}


		// creating landsend namespace to hang functionality off of.
		// We will not use our convenience jquery function for namespacing. This is a file that should not
		// depend on jquery being available. Part of the product service that could be called from non-UI code.
		
		if(com == undefined){
			com = new Object();
		}
		if(com.landsend == undefined){
			com.landsend = new Object();
		}
		
	
		// attaching product service to landsend namespace
		com.landsend.productService = new (function(){
		
			var headLoc = document.getElementsByTagName("head").item(0);
			var javaScriptTagUniqueId = 1;
	
			var libraryCheck = new Object(); // holds instances of LibraryStatus
			var loadedProducts = new Object(); // hashmap used to hold key (schema) / value (array indexed by product number/ value instance of ProductStatus)
			var outstandingRequests = new Array(); // holds instances of ProductRequest
			
			var ProductRequest = function(){
				this.schema = null;
				this.productsRequested = new Array();
				this.callBackMethod = null;
			}
			
			// represents a wrapper around a product object, that is either loaded or in the processes of being loaded
			var ProductStatus = function(){
				this.loaded = false;
				this.value = null; // the product object
			}
			
			var LibraryStatus = function(){
				this.loaded = false;
				this.productsToBeLoaded = new Array(); // a list of method enclosers that need to be executed in order to load previously fetched product data into the runtime
			}

			var checkOutstandingRequests = function(){
				var unfulfilledRequests = new Array();
				var requestedProducts = null;
				var validRequest;
				var nextRequest = outstandingRequests.pop();
				while(nextRequest != undefined){
					validRequest = true;
					requestedProducts = new Array();
					if(nextRequest.callBackMethod != null){
						for(var i = 0;i < nextRequest.productsRequested.length;i++){
							if(loadedProducts[nextRequest.schema][nextRequest.productsRequested[i]] == undefined || ! loadedProducts[nextRequest.schema][nextRequest.productsRequested[i]].loaded){
								validRequest = false;	
							}else{
								requestedProducts[i] = loadedProducts[nextRequest.schema][nextRequest.productsRequested[i]].value;
							} 
						}
						if(validRequest){
							nextRequest.callBackMethod.call(window,requestedProducts);
						}else{
							unfulfilledRequests.push(nextRequest);
						}
					}
					nextRequest = outstandingRequests.pop();
				} 
				outstandingRequests = unfulfilledRequests;
			}
	
			var addNewProductsToCache = function(productMethodHolder){
				productMethodHolder.call(window);
				var products = com.landsend.productService.justLoadedProducts;
				var objectsInTree = com.landsend.productService.justLoadedAllObjectsInTree;
				var schema = com.landsend.productService.productResponseSchema;
			
				if(products.productDisplays != null && products.productDisplays != undefined){ // used to load products baked into product page
					if(loadedProducts[schema] == null || loadedProducts[schema] == undefined){
						loadedProducts[schema] = new Array();
					}
					for(var i = 0;i < products.productDisplays.length;i++){
						if(loadedProducts[schema][products.productDisplays[i].requestKey] == null || loadedProducts[schema][products.productDisplays[i].requestKey] == undefined){
							loadedProducts[schema][products.productDisplays[i].requestKey] = new ProductStatus();
						}
						loadedProducts[schema][products.productDisplays[i].requestKey].value = products.productDisplays[i];
						loadedProducts[schema][products.productDisplays[i].requestKey].loaded = true;
					}				
				}else{ // used to load products from this service
					for(var i = 0;i < products.length;i++){
						loadedProducts[schema][products[i].requestKey].value = products[i];
						loadedProducts[schema][products[i].requestKey].loaded = true;
					}
				}	

				var showData = $.query.get("prodData");
				//var showData = "true";
				var deletePublicData = true;
				if(showData == "true"){
					deletePublicData = false;
				}
				
				for(var i = 0;i < objectsInTree.length;i++){ 					
					if(objectsInTree[i].initialize != undefined){
						objectsInTree[i].initialize.call(objectsInTree[i],deletePublicData);
					}					
				}		
				
				for(var i = 0;i < objectsInTree.length;i++){ 					
					if(objectsInTree[i].init != undefined){
						objectsInTree[i].init.call(objectsInTree[i]);
					}						
				}					
			}
	
			
			this.postLoadLibrary = function(versionId){
				if(libraryCheck[versionId] == null || libraryCheck[versionId] == undefined){ // only needed if we already have the library loaded on the page and we want to register it
					libraryCheck[versionId] = new LibraryStatus();
				}
				libraryCheck[versionId].loaded = true;
				// iterate through previously loaded product enclosers in order to bring the products into the runtime now that the library has been loaded
				for(var i = 0;i < libraryCheck[versionId].productsToBeLoaded.length;i++){
					addNewProductsToCache(libraryCheck[versionId].productsToBeLoaded[i]);	
				}
				checkOutstandingRequests();
			}
	
			this.postLoadData = function(versionId,productData){
				if(libraryCheck[versionId] == undefined){
					libraryCheck[versionId] = new LibraryStatus();
					libraryCheck[versionId].productsToBeLoaded[libraryCheck[versionId].productsToBeLoaded.length] = productData;
					
					var url =  '/pp/ProductServiceLibrary?revisionNumber='+ versionId;					
					var scriptObj2 = document.createElement("script");
					scriptObj2.setAttribute("type", "text/javascript");
					scriptObj2.setAttribute("src",url);
					scriptObj2.setAttribute("id","productLibrary_"+versionId);
					headLoc.appendChild(scriptObj2);							
				}else if(libraryCheck[versionId].loaded == false){				
					libraryCheck[versionId].productsToBeLoaded[libraryCheck[versionId].productsToBeLoaded.length] = productData;
				}else{
					addNewProductsToCache(productData);
					checkOutstandingRequests();
				}
			}
			
			var requestIds = null;
			
			var styleRequest = function() {
				var styleNumber = null;
				var mediaCode = null;
			}
			
			var buildRequestIds = function(requestPayLoad) {
				requestIds = new Array();
				for (var i = 0; i < requestPayLoad.payLoad.length; i++ ) {
				if (requestPayLoad.requestType == "S") {
						styleRequest = requestPayLoad.payLoad[i];
						if (styleRequest.mediaCode == undefined || styleRequest.mediaCode  == "") {
							styleRequest.mediaCode = "-9";
						}
						if (styleRequest.schoolNumber == null || styleRequest.schoolNumber == undefined) {
							requestIds.push(styleRequest.styleNumber + "~" + styleRequest.mediaCode);
						}
						else {
							requestIds.push(styleRequest.styleNumber + "~" + styleRequest.mediaCode + "~" + styleRequest.schoolNumber);
						}
					}
					else {
						requestIds.push(requestPayLoad.payLoad[i]);
					}
				}
			}
			
		    var requestPayLoad = function(requestedType,requestedPayLoad,parentProductNumber) {
		    	this.requestType = requestedType;
		    	this.payLoad = requestedPayLoad;
		    	this.parentProductNumber = parentProductNumber;
		    }
		    
		    var requestStyleDetails = function(requeststyleNumber, requestmediaCode, schoolNumber) {
		    	this.styleNumber = null;
		    	this.mediaCode = null;
		    	this.schoolNumber = null;
		    	var thisStyleDetails = this;
		    	
		    	var initialize = function() {
		    		thisStyleDetails.styleNumber = requeststyleNumber;
		    		thisStyleDetails.mediaCode = requestmediaCode;
		    		thisStyleDetails.schoolNumber = schoolNumber;
		    	}		    	
		    	initialize();
		    }
		    
		    //Typical example call - productService.getProductBasedOnSingleProduct(productId, callbackMethod,schema ('smallProduct' or 'mediumProduct' or 'largeProduct' or 'product'),parentProductNumber (optional) );
		    this.getProductBasedOnSingleProduct = function(productNumber, callBackMethod,schema,parentProductNumber) {
		    	var productNumbers = new Array();
		    	productNumbers.push(productNumber);
		    	var localRequest = new requestPayLoad('P', productNumbers,parentProductNumber);
		    	getProduct(localRequest,callBackMethod,schema);
		    }
		    
		    //Typical example call - productService.getProductBasedOnSingleStyleMedia(styleNumber, mediaCode, callbackMethod,schema ('smallProduct' or 'mediumProduct' or 'largeProduct' or 'product'), schoolNumber);
		    this.getProductBasedOnSingleStyleMedia = function(styleNumber, mediaCode, callBackMethod,schema, schoolNumber) {
		    	var styleDetails = new Array();
		    	var	requestStyle = new requestStyleDetails(styleNumber, mediaCode, schoolNumber)

		    	styleDetails.push(requestStyle);

		    	var localRequest = new requestPayLoad('S', styleDetails);
		    	getProduct(localRequest,callBackMethod,schema);		    	
		    }		    
		    
		    //Typical example call - productService.getProductBasedOnProducts([productId], callbackMethod,schema ('smallProduct' or 'mediumProduct' or 'largeProduct' or 'product'));
		    this.getProductBasedOnProducts = function(productNumbers, callBackMethod,schema) {
		    	var localRequest = new requestPayLoad('P', productNumbers);
		    	getProduct(localRequest,callBackMethod,schema);
		    }
		    
		    //Typical example call -  productService.getProductBasedOnStyles([[styleNumber1, mediaCode1],[styleNumber2, mediaCode2]], callbackMethod,schema('smallProduct' or 'mediumProduct' or 'largeProduct' or 'product'), schoolNumber);
		    this.getProductBasedOnStyles = function(styleMediaCodes, callBackMethod,schema) {
		    	var styleDetails = new Array();
		    	for (var i = 0;i < styleMediaCodes.length; i++) {
		    		var requestStyle = new requestStyleDetails(styleMediaCodes[i].styleNumber, styleMediaCodes[i].mediaCode, styleMediaCodes[i].schoolNumber)
		    		styleDetails.push(requestStyle);
		    	}
		    	var localRequest = new requestPayLoad('S', styleDetails);
		    	getProduct(localRequest,callBackMethod,schema);		    	
		    }		    
		
		    var getProduct = function(requestPayLoad,callBackMethod,schema){
		    	// if schema isn't already defined in loadedProducts hashmap, then defined it
		    	if(loadedProducts[schema] == undefined){
		    		loadedProducts[schema] = new Array();
		    	}	    
				var requestKey = '';
				var productKey = '';
				var parentProductNumber = '';
				var firstRequestedProduct = true;
				var productLoadRequired = false;
				var productsRequestAlreadyInFlight = false;
				buildRequestIds(requestPayLoad);
				for(var i = 0;i < requestIds.length;i++){
					if(loadedProducts[schema][requestIds[i]] == undefined){
						productLoadRequired = true;
						loadedProducts[schema][requestIds[i]] = new ProductStatus();
						if(firstRequestedProduct){
							requestKey = requestKey + '_';
						}
						requestKey = requestKey + requestIds[i];
					}else if(loadedProducts[schema][requestIds[i]] != undefined && loadedProducts[schema][requestIds[i]].loaded == false){
						productsRequestAlreadyInFlight = true;
					}
					productKey = productKey + "_" + requestIds[i];
				}	
	
				var productRequest = new ProductRequest();
				productRequest.schema = schema;
				productRequest.productsRequested = requestIds;
				productRequest.callBackMethod = callBackMethod;
				outstandingRequests.push(productRequest);
				
				if(requestPayLoad.parentProductNumber != null && requestPayLoad.parentProductNumber != undefined){
					parentProductNumber = requestPayLoad.parentProductNumber;
				}
	
				if(productLoadRequired){		
				    var url = "/pp/ProductService?productNumbers=" + requestKey + "&schema=" + schema + "&parentProductNumber=" + parentProductNumber;
				    var scriptObj = document.createElement("script");
				    scriptObj.setAttribute("type", "text/javascript");
				    scriptObj.setAttribute("src",url);
				    scriptObj.setAttribute("id","theID_"+requestKey);
				    headLoc.appendChild(scriptObj);
			    }else if(!productLoadRequired && productsRequestAlreadyInFlight){   	
			    }else{	
			   	 	checkOutstandingRequests();  
			    }
		    }
	    })();
//		$.jsNamespace('com.landsend.productView');
		
//		$.jsNamespace('com.landsend.quickView');
var com;
if(com == undefined){
	com = new Object();
}
if(com.landsend == undefined){
	com.landsend = new Object();
}
if(com.landsend.productView == undefined){
	com.landsend.productView = new Object();
}
if(com.landsend.quickView == undefined){
	com.landsend.quickView = new Object();
}

com.landsend.quickView.QuickViewBuyGridView = function(productId, quickViewGridController, divId) {
	var thisQuickViewGridView = this;
	var divId = divId;
	
	var productId = productId;
	var quickViewGridController = quickViewGridController;	    	
	$.debug("[QVBGV " + productId + "]");

	this.showMe = function() {
		var localdiv = $("#QV_" + divId);
		return leutil.ui.modalHandler.show({
			content:localdiv,
			cssClass:"pp-quick-view-modal",
			width:950,
			cacheable:true,
			onShow:quickViewOpenCallback,
			onHide:quickViewCloseCallback
		});
	}
	var quickViewOpenCallback = function(){
		quickViewGridController.quickViewOpenCallback();
	}
	var quickViewCloseCallback = function(){
		quickViewGridController.quickViewCloseCallback();
	}
		    	
	this.tabView = new function(id) {
		$.debug("[QVBGV tabView " + productId + "]");
		var descTabKeyPrefix = "qvDescTab";
		var rrTabKeyPrefix = "qvRrTab";
		var imageTabKeyPrefix = "qvImageTab";
		
		var descAreaKeyPrefix = "productDesc";
		var rrAreaKeyPrefix = "productRR";
		var imageAreaKeyPrefix = "productImage";	
		var productContentAreaKeyPrefix = "productContent";
		
    	this.selectTab = function() {
    		$.debug("[QVBGV selectTab " + productId + "]");
    		var ids = this.id.split('_').slice(0);
    		var tabdesc = ids[0];
    		var tabId = null;
    		switch (tabdesc) {
    			case imageTabKeyPrefix:
    				tabId = 1;
    				break;
    			case descTabKeyPrefix :
    				tabId = 2;
    				break;
    			case rrTabKeyPrefix :
    				tabId = 3;
    				break;		    				
    		}
    		quickViewGridController.tabController.selectTab(tabId);
    		return false;
    	};
    	
    	this.activateDescriptionTab = function() {
    		$.debug("[QVBGV activateDescriptionTab " + productId + "]");
    		$("#" + descTabKeyPrefix + "_" + productId).addClass("le-modal-tab-selected");		    		
    		$("#" + descAreaKeyPrefix + "_" + productId).removeClass("pp-hide");
    		$("#" + productContentAreaKeyPrefix + "_" + productId).removeClass("pp-hide").addClass("pp-content-wDescription");
    	}
    	
    	this.activateImageTab = function() {
    		$.debug("[QVBGV activateImageTab " + productId + "]");
    		$("#" + imageTabKeyPrefix + "_" + productId).addClass("le-modal-tab-selected");
    		$("#" + imageAreaKeyPrefix + "_" + productId).removeClass("pp-hide");
    		$("#" + productContentAreaKeyPrefix + "_" + productId).removeClass("pp-hide").removeClass("pp-content-wDescription");
    	}
    	
    	this.activateRatingsTab = function() {
    		$.debug("[QVBGV activateRatingsTab " + productId + "]");
    		$("#" + rrTabKeyPrefix + "_" + productId).addClass("le-modal-tab-selected");
    		$("#" + rrAreaKeyPrefix + "_" + productId).removeClass("pp-hide");
    	}
    	
    	this.hideAllTabs = function() {
    		$.debug("[QVBGV hideAllTabs " + productId + "]");
    		$("#" + descTabKeyPrefix + "_" + productId).removeClass("le-modal-tab-selected");
    		$("#" + rrTabKeyPrefix + "_" + productId).removeClass("le-modal-tab-selected");
    		$("#" + imageTabKeyPrefix + "_" + productId).removeClass("le-modal-tab-selected");
    		
    		$("#" + descAreaKeyPrefix + "_" + productId).addClass("pp-hide");
    		$("#" + rrAreaKeyPrefix + "_" + productId).addClass("pp-hide");
    		$("#" + imageAreaKeyPrefix + "_" + productId).addClass("pp-hide");
    		$("#" + productContentAreaKeyPrefix + "_" + productId).addClass("pp-hide");
    	}

    	
		this.registerTabSelector = function() {
			$.debug("[QVBGV registerTabSelector " + productId + "]");
			$("#" + descTabKeyPrefix + "_" + productId).bind('click',this.selectTab);
			$("#" + rrTabKeyPrefix + "_" + productId).bind('click',this.selectTab);
			$("#" + imageTabKeyPrefix + "_" + productId).bind('click',this.selectTab);
		};
	}();
	
}		

// attaching product service to landsend namespace
com.landsend.quickView.QuickViewBuyGrid = function(quickViewProduct, standardBuyGridController, request) {

	var thisQuickViewGrid = this;
	var prodViewNs = com.landsend.productView;
	var quickViewNs = com.landsend.quickView;
	var divId = request.requestKey;
	var productNum = quickViewProduct.getProduct().getNumber();	
	var quickViewBuyGridView = new quickViewNs.QuickViewBuyGridView(quickViewProduct.getProduct().getNumber(), this, divId);
	var childProductController = null;
	//var modalIndex = null;
	var modal = null;
			
	$.debug("[QVBG " + productNum + "]");

	this.getStandardBuyGridController = function(){return standardBuyGridController;}
	
	var intialize = function() {
		thisQuickViewGrid.tabController.registerEvents();
	}
	
	this.showMe = function() {
		modal = quickViewBuyGridView.showMe();
		//modalIndex = quickViewBuyGridView.showMe();
		standardBuyGridController.webAnalyticsController.bypassSendStyleEvent(true);
		standardBuyGridController.resetBuyGrid();
		quickViewBuyGridView.tabView.hideAllTabs();
		quickViewBuyGridView.tabView.activateImageTab();
	}
	
	this.quickViewOpenCallback = function(){
		if (request.currentSelection != null && request.currentSelection != undefined) {
			standardBuyGridController.makeBuyGridSelections(request.currentSelection);
		}
		if (prodViewNs.GCConstants.GCProduct(quickViewProduct.getProduct().getNumber())) {
			standardBuyGridController.giftCardExtensionController.sendGiftCardTypeEvent();
		}
		else {
			standardBuyGridController.webAnalyticsController.bypassSendStyleEvent(false);
			standardBuyGridController.webAnalyticsController.sendStyleChangeEvents();
		}	
	}
	
	this.quickViewCloseCallback = function(){
		com.landsend.quickViewService.broadcastQuickViewEvent("closeQuickView",request);
	}
	
	this.setViewId = function(viewId) {
		standardBuyGridController.setRequestedView(viewId);
	}
				
	this.tabController = new function() {
		$.debug("[QVBG tabController" + productNum + "]");
		this.registerEvents = function() {
			quickViewBuyGridView.tabView.registerTabSelector();
		}
		
		this.selectTab = function(tabId) {
			var tabId = tabId;
			quickViewBuyGridView.tabView.hideAllTabs();
			$.debug("[QVBG selectTab" + productNum + "]");
			switch (tabId) {
				case 1 :
					quickViewBuyGridView.tabView.activateImageTab();
					break;
				case 2 :
					quickViewBuyGridView.tabView.activateDescriptionTab();
					break;		
				case 3 :
					quickViewBuyGridView.tabView.activateRatingsTab();
					break;							
			}
		}
	}();
	
	intialize();
}




		

var com;
if(com == undefined){
	com = new Object();
}
if(com.landsend == undefined){
	com.landsend = new Object();
}
if(com.landsend.productView == undefined){
	com.landsend.productView = new Object();
}

if (com.landsend.productView.GCConstants == undefined) {	
	com.landsend.productView.GCConstants = new function() {
		this.CORE_GIFTCARD_PRODUCT_NUMBER = 999999999;
		this.CANVAS_GIFTCARD_PRODUCT_NUMBER = 999999998;
		this.GLOBAL_GIFTCARD_PRODUCT_NUMBER = 999999997;
		this.PHYSICAL_CARD_FEATURE_NUMBER = 999999991;
		this.VIRTUAL_CARD_FEATURE_NUMBER = 999999992;
		
		this.GCProduct = function(productNumber) {
			return (productNumber == this.CORE_GIFTCARD_PRODUCT_NUMBER || productNumber == this.CANVAS_GIFTCARD_PRODUCT_NUMBER
						|| productNumber == this.GLOBAL_GIFTCARD_PRODUCT_NUMBER ) ? true : false;
		}
		
		this.isGCTypeVirtual = function(featureId) {
			return (featureId == this.VIRTUAL_CARD_FEATURE_NUMBER) ? true : false;
		}
	}
}

com.landsend.productView.GiftCardExtensionView = function(product, gcExtController) {
	var thisGiftCardExtensionView = this;
	var prodViewNs = com.landsend.productView;
	var gcExtController = gcExtController;
	
	var cursorKeyCheck = function(event){
		if(event.keyCode == 37 || event.keyCode == 39){
			return true;
		}
		return false;
	}
	
	this.quickviewView = new function(){
		var isInitialized = false;
		var imageColumn;
		var	descriptionColumn;
		var	imageTab;
		var	descriptionTab;
		
		this.init = function(){
			imageColumn = $("#imageColumn_"+product.getNumber());
			descriptionColumn = $("#descriptionColumn_"+product.getNumber());
			imageTab = $("#imageTab_"+product.getNumber());
			descriptionTab = $("#descriptionTab_"+product.getNumber());
			
			// assumption that tabs will only be found in event of quickview version, therefor continue initializion
			if(imageTab.length > 0 && descriptionTab.length > 0){
				descriptionColumn.append($("#descriptionWrapper_"+product.getNumber()).removeClass("pp-quick-view-hide"));
				
				imageTab.click(function(){
					imageTab.addClass("le-modal-tab-selected");
					descriptionTab.removeClass("le-modal-tab-selected");
					imageColumn.show();
					descriptionColumn.hide();
				});
				
				descriptionTab.click(function(){
					imageTab.removeClass("le-modal-tab-selected");
					descriptionTab.addClass("le-modal-tab-selected");
					imageColumn.hide();
					descriptionColumn.show();
				});
			}
			
			isInitialized = true;
		}
	}
	
	this.giftCardImageView = new function() {
		this.hideGCExtType = function(featureId) {
			$("#" + "GCProductPageHeading" + "_" + product.getNumber() + "_" + featureId).hide();
			$("#" + "GCDescription" + "_" + product.getNumber() + "_" + featureId).hide();
		}
		
		this.selectGiftCardExtType = function(featureId) {
			$("#" + "GCProductPageHeading" + "_" + product.getNumber() + "_" + featureId).show();
			$("#" + "GCDescription" + "_" + product.getNumber() + "_" + featureId).show();			
		}
		
		this.selectPhotoViewer = function(styleNumber) {
			$(".fn-image-viewer").hide();
			var x= "#imageViewer_" + product.getNumber() + "_" + styleNumber;
			$("#imageViewer_" + product.getNumber() + "_" + styleNumber).show();
		}
		
		
		this.registerEvents = function(styleNumber) {			
	 		var imageId =  product.getNumber()  + "_" + styleNumber;
	 		$("#altImage_0_" + imageId).bind('click',  selectLargeImage);	
	 		$("#altImage_1_" + imageId).bind('click',  selectLargeImage);
		}
		
		var selectLargeImage = function(event) {
			var activeDivId = null;
			if (this.id.indexOf("_0") > -1) {
				activeDivId = this.id.replace("_0", "_1");
				activeDivId = "largeImageFor_" + activeDivId;
			}
			else {
				activeDivId = this.id.replace("_1", "_0");
				activeDivId = "largeImageFor_" + activeDivId;
			}
			var newDivId = "largeImageFor_" + this.id;
			$("#" + activeDivId).hide();
			$("#" + newDivId).show();
	 		event.preventDefault();
		}		
	}
	
	this.giftCardMarketingView = new function(){
		this.toggle = function(featureId){
			if (featureId == prodViewNs.GCConstants.VIRTUAL_CARD_FEATURE_NUMBER) {
				$(".fn-physical-card-marketing").hide();
				$(".fn-e-card-marketing").show();
			}
			else{
				$(".fn-physical-card-marketing").show();
				$(".fn-e-card-marketing").hide();
			}
		}
	}

	this.giftCardMessageAreaView = new function() {	
		this.registerEvent = function(featureId) {
			if (featureId == prodViewNs.GCConstants.VIRTUAL_CARD_FEATURE_NUMBER) {
				$("#personalizedRecipientEmail_" + product.getNumber()  + "_" + featureId).bind('focus', hideErrorPersonalizedRecipientEmailSelection);
				$("#personalizedRecipientEmail_" + product.getNumber()  + "_" + featureId).bind('keyup', changePersonalizedRecipientEmail);
				$("#personalizedRecipientEmail_" + product.getNumber()  + "_" + featureId).val("");		
			}
			$("#personalizedTo_" + product.getNumber()  + "_" + featureId).bind('keyup', changePersonalizedTo);
			$("#personalizedMessage_" + product.getNumber()  + "_" + featureId).bind('change', changePersonalizedMessage);
			$("#personalizedMessage_" + product.getNumber()  + "_" + featureId).bind('focus', hideErrorPersonalizedMessage);
			$("#personalizedFrom_" + product.getNumber()  + "_" + featureId).bind('keyup', changePersonalizedFrom);
			
			$("#personalizedTo_" + product.getNumber()  + "_" + featureId).val("");
			$("#personalizedMessage_" + product.getNumber()  + "_" + featureId).val("");
			$("#personalizedFrom_" + product.getNumber()  + "_" + featureId).val("");

			leutil.ui.characterCounter("#personalizedMessage_" + product.getNumber()  + "_" + featureId+":visible");
		}
		
		
		this.showErrorPersonalizedRecipientEmailSelection = function (featureId) {
			$("#personalizedRecipientEmail_" + product.getNumber()  + "_" + featureId + "_Wrapper").addClass("pp-selector-error");
		}	
		
		this.showErrorPersonalizedMessage = function (featureId) {
			$("#personalizedMessage_" + product.getNumber()  + "_" + featureId + "_Wrapper").addClass("pp-selector-error");
		}		
		
		var hideErrorPersonalizedMessage = function() {
			var ids = this.id.split('_').slice(2);
			thisGiftCardExtensionView.giftCardMessageAreaView.hidePersonalizedMessageErrorOnSetOrFocus(ids[0]);
		}
		
		this.hidePersonalizedMessageErrorOnSetOrFocus = function(featureId){
			$("#personalizedMessage_" + product.getNumber()  + "_" + featureId + "_Wrapper").removeClass("pp-selector-error");
		}
		
		var hideErrorPersonalizedRecipientEmailSelection = function() {
			var ids = this.id.split('_').slice(2);
			thisGiftCardExtensionView.giftCardMessageAreaView.hidePersonalizedRecipientEmailErrorOnSetOrFocus(ids[0]);
		}	
		
		this.hidePersonalizedRecipientEmailErrorOnSetOrFocus = function(featureId){
			$("#personalizedRecipientEmail_"  + product.getNumber()  + "_" + featureId + "_Wrapper").removeClass("pp-selector-error");
		}
		
		this.hideGCExtType = function(featureId) {
			$("#" + "personalized" + "_" +  product.getNumber() + "_" + featureId).hide();
		}
		
		this.isActiveFeature = function(featureId) {
			return $("#" + "personalized" + "_" +  product.getNumber() + "_" + featureId).is(":visible");
		}
		
		this.copyValueBetweenTabs = function(FromFeatureId, ToFeatureId) {
			$("#personalizedTo_" + product.getNumber()  + "_" + ToFeatureId).val($("#personalizedTo_" + product.getNumber()  + "_" + FromFeatureId).val());
			$("#personalizedMessage_" + product.getNumber()  + "_" + ToFeatureId).val($("#personalizedMessage_" + product.getNumber()  + "_" + FromFeatureId).val());
			$("#personalizedFrom_" + product.getNumber()  + "_" + ToFeatureId).val($("#personalizedFrom_" + product.getNumber()  + "_" + FromFeatureId).val());
			leutil.ui.watermarkHandler.updateAll();
		}
		
		this.selectGiftCardExtType = function(featureId) {
			$("#" + "personalized" + "_" + product.getNumber() + "_" + featureId).show();			
			leutil.ui.characterCounter("#personalizedMessage_" + product.getNumber()  + "_" + featureId+":visible");
		}
		
		this.checkPersonalizedMessageLength = function(featureId) {
			return ($("#personalizedMessage_" + product.getNumber()  + "_" + featureId).data("errorState")) ? true : false;
		}
	
		var changePersonalizedRecipientEmail = function(event) {		
			var pos = $("#" + this.id).getCursorPosition();
			if(cursorKeyCheck(event)){return;}
			gcExtController.giftCardMessageAreaController.selectPersonalizedRecipientEmail(this.value);
			$("#" + this.id).setCursorPosition(pos);			
			event.preventDefault();
		}
		var changePersonalizedTo  = function(event) {
			var pos = $("#" + this.id).getCursorPosition();
			if(cursorKeyCheck(event)){return;}
			gcExtController.giftCardMessageAreaController.selectPersonalizedTo(this.value);
			$("#" + this.id).setCursorPosition(pos);
			event.preventDefault();
			
		}
		
		var changePersonalizedMessage  = function(event) {
			$this = $(this); // uses character counter logic to add \n between each line per cgi necessity
			var result = leutil.ui.charCounterTest($this.val(),$this.attr("rows"),$this.attr("cols"));
			var value = '';
			for(var i=0; i<result.lines.length; i++){
				if(i!=0){ value +='\n'; }
				value+=$.trim(result.lines[i]);
			}
			gcExtController.giftCardMessageAreaController.selectPersonalizedMessage(value);
		}
		
		var changePersonalizedFrom  = function(event){
			var pos = $("#" + this.id).getCursorPosition();
			if(cursorKeyCheck(event)){return;}
			gcExtController.giftCardMessageAreaController.selectPersonalizedFrom(this.value);
			$("#" + this.id).setCursorPosition(pos);
			event.preventDefault();
		}
		
		this.getSetValues = function(featureId, tmessageFields) {
			tmessageFields.personalizedRecipientEmail =  (featureId == prodViewNs.GCConstants.VIRTUAL_CARD_FEATURE_NUMBER) ?
											$("#personalizedRecipientEmail_" + product.getNumber()  + "_" + featureId).val() : "";				   
			tmessageFields.personalizedTo      =  $("#personalizedTo_" + product.getNumber()  + "_" + featureId).val();
			tmessageFields.personalizedMessage =  $("#personalizedMessage_" + product.getNumber()  + "_" + featureId).val();
			tmessageFields.personalizedFrom    =  $("#personalizedFrom_" + product.getNumber()  + "_" + featureId).val();				   
		}
		
		this.setPersonalizedRecipientEmail = function(value, featureId) {
			if (value != null && value != undefined) {
				$("#personalizedRecipientEmail_" + product.getNumber()  + "_" + featureId).val(value)
			}
		}
		
		this.setPersonalizedTo = function(value, featureId) {
			if (value != null && value != undefined) {
				$("#personalizedTo_" + product.getNumber()  + "_" + featureId).val(value);
				leutil.ui.watermarkHandler.update($("#personalizedTo_" + product.getNumber()  + "_" + featureId));
			}
		}
		
		this.setPersonalizedMessage = function(value, featureId) {
			if (value != null && value != undefined) {
				$("#personalizedMessage_" + product.getNumber()  + "_" + featureId).val(value);
				leutil.ui.characterCounter($("#personalizedMessage_" + product.getNumber()  + "_" + featureId).filter(":visible"));
			}
		}
		
		this.setPersonalizedFromEmail = function(value, featureId) {
			if (value != null && value != undefined) {
				$("#personalizedFrom_" + product.getNumber()  + "_" + featureId).val(value);
				leutil.ui.watermarkHandler.update($("#personalizedFrom_" + product.getNumber()  + "_" + featureId));
			}
		}		
	}
	
	this.amountView = new function(){		
		this.registerAmountSelector = function(){
			$("#amount_" + product.getNumber()).val("50.00");
			$("#amount_" + product.getNumber()).format({precision: 2,allow_negative:false,autofix:true}, function(){alert("Not a number");})
			$("#amount_" + product.getNumber()).bind('change', selectAmount);
			$("#amount_" + product.getNumber()).bind('focus', this.hideAmountErrorSelection);
		}
		
		var selectAmount = function(){
			gcExtController.amountController.amountSelect(this.value);
		}
		
		this.setFormattedAmount = function(formattedAmount) {
			$("#amount_" + product.getNumber()).val(formattedAmount);			
		}
		
		this.showAmountErrorSelection = function() {
			$("#amount_" + product.getNumber() + "_Wrapper").addClass("pp-selector-error");
		}
		
		this.hideAmountErrorSelection = function() {
			$("#amount_" + product.getNumber() + "_Wrapper").removeClass("pp-selector-error");	
		}
				
	}
}

com.landsend.productView.GiftCardExtensionController = function(productView, selection, webAnalyticsParam) {
	
	var thisGiftCardExtension = this;
	var prodViewNs = com.landsend.productView;
	var product = productView.getProduct();
	var giftCardExtensionView = new prodViewNs.GiftCardExtensionView(product, this);
	var allFeatures = product.getAllFeatures(); // shortcut reference
	var styles = product.getRootFeature().getAllStylesAtOrBelow();
	var selection = selection;
	
	var messageFields = function() {
		this.personalizedRecipientEmail = null;
		this.personalizedTo = null;
		this.personalizedMessage = null;
		this.personalizedFrom = null;		
	}
	
	this.resetSelectionObject = function(lselection) {
		selection = lselection;
		this.giftCardMessageAreaController.reset();
		this.amountController.reset();
	}
	
	this.init = function() {
		$.debug("GiftCardExtensionController.init.");
		this.giftCardImageController.init();
		this.giftCardMessageAreaController.init();
		this.amountController.init();
		giftCardExtensionView.quickviewView.init();
	}
	
	this.errorChecker = function(displayIndicator,errors){
		this.giftCardMessageAreaController.errorChecker(displayIndicator,errors);
		this.amountController.errorChecker(displayIndicator,errors);
	}

	this.selectGiftCardType = function(primaryFeatureId, secondaryFeatureId) {
		this.giftCardImageController.selectGiftCardType(primaryFeatureId, secondaryFeatureId);
		this.giftCardMessageAreaController.selectGiftCardType(primaryFeatureId, secondaryFeatureId);
		if (secondaryFeatureId == null) {
			//Means clicked on the gift card tab and we need to send an ominture event
			this.sendGiftCardTypeEvent();
		}		
	}
	
	this.sendGiftCardTypeEvent = function() {
		$.debug("[sendGiftCardTypeSelectionMetric].... ");
		s_omtr = s_gi(s_account);			
		s_omtr.linkTrackVars='products,eVar4,eVar19,events';
		s_omtr.linkTrackEvents='prodView,event2';
		s_omtr.events='prodView,event2'
	    var localEvar15 =  (webAnalyticsParam != undefined && webAnalyticsParam != null) ? "QV" : "PP";
		if (prodViewNs.GCConstants.isGCTypeVirtual(selection.primaryFeatureId)) {
		  s_omtr.pageName = 'VIRTUAL GIFT CARD';
		  s_omtr.products='FP_99025_I;;;evar15=' + localEvar15;
		}
		else {
			  s_omtr.pageName = 'GIFT CARD';
			  s_omtr.products='FP_99025_P;;;evar15=' + localEvar15;
		}
		s_omtr.tl(true,'o','link');			
	}

	this.giftCardImageController = new function() {		
		this.init = function() {
			$.debug("giftCardImageController.init.");
			for(var i = 0;i < styles.length;i++){ 		
				giftCardExtensionView.giftCardImageView.registerEvents(styles[i].getNumber());	
			}	
		}
		
		this.selectGiftCardType = function(primaryFeatureId, secondaryFeatureId) {
			if (secondaryFeatureId == null) {
				for(var i = 0;i < allFeatures.length;i++){
					if(allFeatures[i].getLevel() == 1)  {
						giftCardExtensionView.giftCardImageView.hideGCExtType(allFeatures[i].getFeatureNumber());
					}	
				}
				giftCardExtensionView.giftCardImageView.selectGiftCardExtType(primaryFeatureId);
			}
		}
		
		
		this.styleChangeViewer = function(selectedStyle) {
			giftCardExtensionView.giftCardImageView.selectPhotoViewer(selectedStyle.getNumber());
		}
	}
	
	this.giftCardMessageAreaController = new function() {
		
		this.init = function() {
			$.debug("giftCardMessageAreaController.init.");
			for(var i = 0;i < allFeatures.length;i++) {
				if(allFeatures[i].getLevel() == 1)  {
					giftCardExtensionView.giftCardMessageAreaView.registerEvent(allFeatures[i].getFeatureNumber());
				}				
			}
			leutil.ui.watermarkHandler.init(); // initialize watermark fields in instance of quickview
		}
		
		this.reset = function() {
			this.setPersonalizedTo("", prodViewNs.GCConstants.VIRTUAL_CARD_FEATURE_NUMBER);
			this.setPersonalizedMessage("",prodViewNs.GCConstants.VIRTUAL_CARD_FEATURE_NUMBER); 
			this.setPersonalizedFromEmail("",prodViewNs.GCConstants.VIRTUAL_CARD_FEATURE_NUMBER);
			this.setPersonalizedRecipientEmail("", prodViewNs.GCConstants.VIRTUAL_CARD_FEATURE_NUMBER);

			this.setPersonalizedTo("", prodViewNs.GCConstants.PHYSICAL_CARD_FEATURE_NUMBER);
			this.setPersonalizedMessage("",prodViewNs.GCConstants.PHYSICAL_CARD_FEATURE_NUMBER); 
			this.setPersonalizedFromEmail("",prodViewNs.GCConstants.PHYSICAL_CARD_FEATURE_NUMBER);
		}
		
		this.errorChecker = function(displayIndicator,errors){
			$.debug("[giftCardMessageAreaController errorChecker]");
			if(errors == undefined){
				errors = new Array();
			}
			if (selection.primaryFeatureId == prodViewNs.GCConstants.VIRTUAL_CARD_FEATURE_NUMBER) {
				if (selection.personalizedRecipientEmail == null || selection.personalizedRecipientEmail == undefined ||
						selection.personalizedRecipientEmail == "") {
					errors.push(prodViewNs.Messages.findMessage(31));
					if (displayIndicator) giftCardExtensionView.giftCardMessageAreaView.showErrorPersonalizedRecipientEmailSelection(selection.primaryFeatureId);
				}
				else {
					if (!checkEmail(selection.personalizedRecipientEmail)) {
						errors.push(prodViewNs.Messages.findMessage(33));
						if (displayIndicator) giftCardExtensionView.giftCardMessageAreaView.showErrorPersonalizedRecipientEmailSelection(selection.primaryFeatureId);
					}
				}

			}
			
			if (giftCardExtensionView.giftCardMessageAreaView.checkPersonalizedMessageLength(selection.primaryFeatureId)) {
					errors.push(prodViewNs.Messages.findMessage(34));
					if (displayIndicator) giftCardExtensionView.giftCardMessageAreaView.showErrorPersonalizedMessage(selection.primaryFeatureId);
				}
		}		
		
		this.selectGiftCardType = function(primaryFeatureId, secondaryFeatureId) {

			var switchFromFeatureId = null;
			
			for(var i = 0;i < allFeatures.length;i++){
				if(allFeatures[i].getLevel() == 1)  {
					//Before we hide let check if it is active tab. If yes then we need to switch values from the active to 
					//one that is going to be active.
					if (giftCardExtensionView.giftCardMessageAreaView.isActiveFeature(allFeatures[i].getFeatureNumber())) {
						switchFromFeatureId = allFeatures[i].getFeatureNumber();
					}
					giftCardExtensionView.giftCardMessageAreaView.hideGCExtType(allFeatures[i].getFeatureNumber());
				}	
			}
			
			if (switchFromFeatureId != primaryFeatureId) {
				giftCardExtensionView.giftCardMessageAreaView.copyValueBetweenTabs(switchFromFeatureId, primaryFeatureId);
			}
			
			giftCardExtensionView.giftCardMessageAreaView.selectGiftCardExtType(primaryFeatureId);
			giftCardExtensionView.giftCardMarketingView.toggle(primaryFeatureId);
			//Set the selection value to what is stored in the fields
			
			tmessageFields = new messageFields();
			giftCardExtensionView.giftCardMessageAreaView.getSetValues(primaryFeatureId, tmessageFields);
			
			selection.personalizedRecipientEmail = tmessageFields.personalizedRecipientEmail;
			selection.personalizedTo = tmessageFields.personalizedTo;
			selection.personalizedMessage = tmessageFields.personalizedMessage;
			selection.personalizedFrom = tmessageFields.personalizedFrom;
		}	
		

	
		this.selectPersonalizedRecipientEmail  = function(value) {
			if (value == null || value == undefined) 
				selection.personalizedRecipientEmail = "";
			else 
			    selection.personalizedRecipientEmail = value;
		}
		
		this.selectPersonalizedTo  = function(value) {
			if (value == null || value == undefined) 
				selection.personalizedTo = "";
			else 
			    selection.personalizedTo = value;			
		}
		
		this.selectPersonalizedMessage = function(value) {
			if (value == null || value == undefined) 
				selection.personalizedMessage = "";
			else 
			    selection.personalizedMessage = value;
		}
		
		this.selectPersonalizedFrom = function(value){
			if (value == null || value == undefined) 
				selection.personalizedFrom = "";
			else 
			    selection.personalizedFrom = value;
		}	
		
		this.setPersonalizedRecipientEmail = function(value, featureId) {
			if (value != null && value != undefined) {
				giftCardExtensionView.giftCardMessageAreaView.setPersonalizedRecipientEmail(value, featureId);
				selection.personalizedRecipientEmail = value;
			}
			giftCardExtensionView.giftCardMessageAreaView.hidePersonalizedRecipientEmailErrorOnSetOrFocus(featureId);
		}
		
		this.setPersonalizedTo = function(value, featureId) {
			if (value != null && value != undefined) {
				giftCardExtensionView.giftCardMessageAreaView.setPersonalizedTo(value, featureId);
				 selection.personalizedTo = value;		
			}
		}
		
		this.setPersonalizedMessage = function(value, featureId) {
			if (value != null && value != undefined){
				if(value.join){
					value = value.join('\n');
				}
				giftCardExtensionView.giftCardMessageAreaView.setPersonalizedMessage(value, featureId);
				giftCardExtensionView.giftCardMessageAreaView.hidePersonalizedMessageErrorOnSetOrFocus(featureId);
				selection.personalizedMessage = value;
			}
		}
		
		this.setPersonalizedFromEmail = function(value, featureId) {
			if (value != null && value != undefined){
				giftCardExtensionView.giftCardMessageAreaView.setPersonalizedFromEmail(value, featureId);
				selection.personalizedFrom = value;
			}
		}			
	}
	
	this.amountController = new function(){
		
		this.init = function(){
			selection.gcAmount = 50.00;
			thisGiftCardExtension.amountController.registerEvents();
		}
		
		this.reset = function() {
			selection.gcAmount = 50.00;
			this.setAmount(50);	
		}

		this.errorChecker = function(displayIndicator,errors){
			$.debug("[amountController errorChecker]");
			if(errors == undefined){
				errors = new Array();
			}

			if (selection.gcAmount == undefined || selection.gcAmount == null || selection.gcAmount < 5 || selection.gcAmount > 500)  {
				errors.push(prodViewNs.Messages.findMessage(32));	
				if (displayIndicator) giftCardExtensionView.amountView.showAmountErrorSelection();
			}
		}
		
		this.registerEvents = function(){
			$.debug("amountController.registerEvents Registering events on the view.");
			giftCardExtensionView.amountView.registerAmountSelector(product.getNumber());
		}
		
		this.amountSelect = function(selectedAmt){
			$.debug("amountController.quantitySelect quantity selected in view" + selectedAmt);
			if (isNaN(Number(selectedAmt))) {
				alert('Not Numeric');
				return;
			}

			selection.gcAmount = selectedAmt;
			var formattedValue = $.number_format(selectedAmt);
			giftCardExtensionView.amountView.setFormattedAmount(formattedValue);
			
		}
		
		this.setAmount = function(value) {
			selection.gcAmount = value;
			var formattedValue = $.number_format(value);
			giftCardExtensionView.amountView.setFormattedAmount(formattedValue);
			giftCardExtensionView.amountView.hideAmountErrorSelection();
		}
	}
} 

		// creating landsend namespace to hang functionality off of. 
//	$.jsNamespace('com.landsend');
var com;
if(com == undefined){
	com = new Object();
}
if(com.landsend == undefined){
	com.landsend = new Object();
}
if(com.landsend.productView == undefined){
	com.landsend.productView = new Object();
}

if(com.landsend.productView == undefined){
	com.landsend.productView = new Object();
}
			
// attaching product service to landsend namespace
com.landsend.quickViewService = new (function(){
	var qvs = this;
	var prodViewNs = com.landsend.productView;	
	var quickViewNs = com.landsend.quickView;
	var requests = new Array();
	var activeProductId = null;
	var globalManager = prodViewNs.GlobalManager;
	var schoolIsCustom = null;

	this.getQVActiveRequest = function() {
		if (activeProductId == null) return null;
		return requests[activeProductId];
	}
	
	this.broadcastQuickViewEvent = function(eventType,request){
		var requestPara = new Object();
		requestPara.productId = request.productId;
		requestPara.viewId = request.viewId;
		requestPara.styleNumber = request.styleNumber;
		requestPara.mediaCode = request.mediaCode;
		requestPara.requestKey = request.requestKey
		requestPara.schoolNumber = request.schoolNumber;
		
		if(request.quickViewCallback != null && request.quickViewCallback != undefined){
			request.quickViewCallback.call(null,eventType,requestPara,request.quickViewBuyGrid);
		}
	}
	
	var errorMessage = "<h1>We're sorry.</h1> <p> The page you're looking for is currently not available. <br /> " +
					"If you would like assistance, please contact us via Get Live Help (text chat) or call 1-800-963-4816.<br /> "; 

	var Request = function(requestType, requestKey, productId,viewId,styleNumber, mediaCode,quickViewCallback, schoolNumber, showRR,
							isSchoolCustom){
		var thisRequest = this;
		this.requestKey = requestKey;
		this.requestType = requestType;
		this.productId = productId;
		this.inFlight = true;
		this.viewId = viewId;
		this.addtionalParam = null;
		this.productDisplayGroup = null;
		this.quickViewBuyGrid = null;
		this.requestTimedOut = false;
		this.requestTimer = null;
		this.styleNumber = styleNumber;
		this.currentSelection = null;
		this.schoolNumber = schoolNumber;
		this.quickViewCallback = quickViewCallback;
		this.showRR = showRR;
		this.isSchoolCustom = isSchoolCustom;
		
		if (mediaCode == null || mediaCode == undefined || mediaCode == "") {
			this.mediaCode = null;
		}
		else {
			this.mediaCode = mediaCode;
		}
		
		this.timedOut = function() {
			thisRequest.requestTimedOut = true;
			if (activeProductId == thisRequest.productId) {
				activeProductId = null;
				leutil.ui.modalHandler.show({
					content:errorMessage,
					cssClass:"le-modal-alert",
					dialogue:true,
					scrollable:false
				});
//						alert("Request for " + thisRequest.productId + " has time Out")
			};
		}
	}
	
	var qvRequestParams = function(cmMerch) {
		this.cmMerch = cmMerch;
	}			
	
	var htmlRetrevier = function(request) {
		var thisRetrevier = this;
		var request = request;
		var rrDisplay =  (request.showRR == false) ? "N" : "Y";
		
		var load = function() {
			if (request.requestType == 'P') {
				requestURL = "/pp/QuickViewProduct~" + request.productId + ".html?rrDisplay=" + rrDisplay;
			}
			else {
				if (request.mediaCode == null) {
					requestURL = "/pp/QuickViewStyle-" + request.styleNumber + ".html?rrDisplay=" + rrDisplay;
				}
				else {
					requestURL = "/pp/QuickViewStyle-" + request.styleNumber + '_' + request.mediaCode + ".html?rrDisplay=" + rrDisplay;
				}
				if (request.schoolNumber != null && request.schoolNumber != undefined && request.schoolNumber != "" && 
						request.isSchoolCustom) {
					requestURL = requestURL + "&schoolStoreNum=" + request.schoolNumber.toString();
				}
			}
			 $.debug("[Making AJAX call to get the product for QuickView for product" + request.productId + "]");
			 $.ajax({
				   async:true,
				   url: requestURL,
				   success:parseResponse,
				   error:handleError
				 });
		}
		
		var parseResponse = function(html) {
			$.debug("[Parsing response from  AJAX call to get the product for QuickView" + request.productId + "]");
			var buyGrids = new Array();
			var buyGrid = null;
			
			if(request.productDisplayGroup.length > 0){ // as of today there a quick view can only show a single product
				com.landsend.quickViewService.broadcastQuickViewEvent("preLoadNewIntance",request);
								
				injectHtml(request.requestKey,html);
				var qvWebAnalyticsParams = null;
			
				if (request.addtionalParam != undefined && request.addtionalParam != null) {
					 qvWebAnalyticsParams = new quickViewNs.WebAnalyticsParams(request.addtionalParam);
				}	
 				buyGrid = new prodViewNs.StandardBuyGridController(request.productDisplayGroup[0], qvWebAnalyticsParams);		
				buyGrids.push(buyGrid);
				request.quickViewBuyGrid = new com.landsend.quickView.QuickViewBuyGrid(request.productDisplayGroup[0],buyGrid, request);
			}	
			prodViewNs.GlobalManager.addQuickViewBuyGrids(buyGrids);	

			$.debug("done");		
			if(activeProductId == request.requestKey){
				$.debug("[Generate the quickview Buygrid...]");
				var qvrecommendationsController = new prodViewNs.RecommendationsController();
				for(var i = 0;i < buyGrids.length;i++){ 
					buyGrids[i].registerCallbackForStyleChange(qvrecommendationsController.notifyStyleView);
				}
				
				request.quickViewBuyGrid.showMe();				
				if(request.viewId != undefined && request.viewId != null && request.viewId != "-1") {
					request.quickViewBuyGrid.setViewId(request.viewId);
				}	
				com.landsend.quickViewService.broadcastQuickViewEvent("postLoadNewIntance",request);			
			}
			else {
				com.landsend.quickViewService.broadcastQuickViewEvent("loadedNotDisplayed",requests[requestKey]);
			}
			$.debug("done again");
			request.inFlight = false;
			if ( !request.requestTimedOut ) {clearTimeout(request.requestTimer)}
			else { request.requestTimedOut = false }

		}
		
		var handleError = function(request, errorStatus) {
		    $.debug("erroroadfaksdjfl");
		    //	onerror(request);
		}
		
		load();
	}
			
	var injectHtml = function(productId, theHtml) {				
		var prdDivId = "QV_" + productId;
		if (!document.getElementById(prdDivId)) {
			theHtml = "<div id='" + prdDivId + "' class='le-modal-content-hide'>" + theHtml + "</div>";
			$("body").append(theHtml);
		}
	}
	
	var getRequestKey = function(requestType, productId, styleNumber, mediaCode, schoolNumber) {
		if (requestType == 'P') {
			return productId;
		}
		else {
			var tempKey = null;
			tempKey = (mediaCode == undefined || mediaCode == "" || mediaCode == null) ? styleNumber.toString() + "_-9":styleNumber.toString() + "_" + mediaCode;
			return (schoolNumber != null && schoolNumber != undefined && schoolNumber != "")?  tempKey + "_" + schoolNumber.toString():tempKey;
		}
	}
	
	/**
	 * Public method used to load a style based quick view 
	 * 
	 * cmMerch - used for ominture tracking, see object definition above  
	 * 			Current domain values 
	 * 			null - value to be used if no special behavior is needed
	 * 			'BUNDLE' - used to tell the quickview service that there will be two buygrids on the page for the given product/style
	 * 					   and that HTML representing those buygrids should adjust there HTML element's IDs accordingly to make sure both buy grids
	 * 			           can live an breathe on the same page. 
	 */
	this.getQuickViewForStyle = function(styleNumber,mediaCode, cmMerch, selection,quickViewCallback, showRR){
		getQuickViewInternal('S', null,null, styleNumber, mediaCode, cmMerch,selection,quickViewCallback,showRR)
	}

	
	/**
	 * Public method used to load a product based quick view 
	 * 
	 * cmMerch - used for ominture tracking, see object definition above  
	 * 			Current domain values 
	 * 			null - value to be used if no special behavior is needed
	 * 			'BUNDLE' - used to tell the quickview service that there will be two buygrids on the page for the given product/style
	 * 					   and that HTML representing those buygrids should adjust there HTML element's IDs accordingly to make sure both buy grids
	 * 			           can live an breathe on the same page. 
	 */			
	this.getQuickView = function(productId, viewId, cmMerch,selection,quickViewCallback, showRR){
		if ((prodViewNs.GCConstants.GCProduct(productId))  && window.location.protocol != "https:") {
			alert("Can't lauch Gift Card Quick View from http page");
			return;
		}
		getQuickViewInternal('P', productId, viewId, null, null, cmMerch,selection,quickViewCallback, showRR)
	}
	
	var checkIfSchoolIsCustom = function(schoolNumber) {
		var schoolNum = String(schoolNumber);
        var schoolID = schoolNum.substring(0,schoolNum.length-1);
        var checkDigit = schoolNum.substring(schoolNum.length-1);
        $.debug("[checkIfSchoolIsCustom] schoolID=" + schoolID + " checkDigit=" + checkDigit);
		DWREngine.setAsync(false);				
		$.debug("[checkIfSchoolIsCustom] before findSchoolBySchoolNumber in checkIfSchoolIsCustom");
    	JSchoolFacade.findSchoolBySchoolNumber(schoolID, checkDigit,{
    		callback:setCustomSchoolOrNot,
    		timeout:10000,
    		errorHandler:null
    	});	   
    	$.debug("[codeEntry] after findSchoolBySchoolNumber in checkIfSchoolIsCustom");
    	DWREngine.setAsync(true);			
	}
	
	var setCustomSchoolOrNot = function(school) {
		if (school == null || school == undefined) {
			$.debug("[setCustomSchoolOrNot] Trouble. School cannot be found in DB");
			return ;
		}	
		$.debug("[setCustomSchoolOrNot] School found.");
		schoolIsCustom = (school.productionSchoolStore != null && typeof (school.productionSchoolStore) == "object")? true:false;
		return;
	}
	
	
	/**
	 * Private method used to execute the retrieval of the quick view
	 * 
	 */
	var getQuickViewInternal = function(requestType, productId, viewId, styleNumber, mediaCode, cmMerch,selection,quickViewCallback, showRR){
		$.debug("[Getting product/ViewId -" + productId  + "/"+ viewId + "]");
		
		var schoolNumber = null;
		if (selection != undefined && selection != null && selection.schoolNumber !=  undefined &&  selection.schoolNumber != null)
			schoolNumber = selection.schoolNumber;		
	
		if (schoolNumber != null && schoolNumber != undefined) {
			schoolIsCustom = null;
			 // Check whether the school is custom or not get the value set.
			checkIfSchoolIsCustom(schoolNumber);
		}	
		//For non Custom School we get the entire product back. 
		if (!schoolIsCustom)  {
			$.cookie("schoolNumber",schoolNumber,{path: '/'});
		}
		
		var productService = com.landsend.productService;
		
		var requestKey = getRequestKey(requestType, productId, styleNumber, mediaCode, schoolNumber)

		activeProductId = requestKey;
		
		if(requests[requestKey] != null && requests[requestKey] != undefined && requests[requestKey].requestTimedOut) {
			activeProductId = null;
			modalHandler.buildError(errorMessage)
		}
		else {
			if(requests[requestKey] != null && requests[requestKey] != undefined && ! requests[requestKey].inFlight){
				$.debug("[product/ViewId Already in the Grid. Just show -" + productId  + "/"+ viewId + "]");
				requests[requestKey].quickViewCallback = quickViewCallback;
				com.landsend.quickViewService.broadcastQuickViewEvent("preLoadCachedIntance",requests[requestKey]);
				if (selection != undefined && selection != null) requests[requestKey].currentSelection = selection;
			
				requests[requestKey].quickViewBuyGrid.showMe();				
				if(viewId != undefined && viewId != null && viewId != "-1") {
					requests[requestKey].quickViewBuyGrid.setViewId(viewId);
				}	
				com.landsend.quickViewService.broadcastQuickViewEvent("postLoadCachedIntance",requests[requestKey]);
			}else if(requests[requestKey] == null || requests[requestKey] == undefined){
				$.debug("[product/ViewId Not in the Grid. Get it -" + productId  + "/"+ viewId + "]");

				requests[requestKey] = new Request(requestType, requestKey, productId,viewId,styleNumber, mediaCode,
						    quickViewCallback, schoolNumber, showRR, schoolIsCustom);
				if (selection != undefined && selection != null) {requests[requestKey].currentSelection = selection;}
				if (cmMerch != undefined && cmMerch != null) {
					requests[requestKey].addtionalParam = new qvRequestParams(cmMerch);
				}				
				requests[requestKey].requestTimer = setTimeout(requests[requestKey].timedOut, 15000);
				if (requestType == 'P') {
					productService.getProductBasedOnSingleProduct(productId, getQuickViewBuyGrid,'product');
				}
				else {
						productService.getProductBasedOnSingleStyleMedia(styleNumber, mediaCode, getQuickViewBuyGrid,'product', schoolNumber);
				}
			}
		}
	}
						
	var getQuickViewBuyGrid = function (productDisplayGroup) {
		var requestKey = productDisplayGroup[0].getRequestKey();
		requestKey = requestKey.replace(/~/g,"_");
		$.debug("[Calling quick view service after product Service for product -" + requestKey + "]");	
		requests[requestKey].productDisplayGroup = productDisplayGroup;
		var htmlGetter = new htmlRetrevier(requests[requestKey]);	
	}
})();

com.landsend.quickView.WebAnalyticsParams = function(addtionalParam) {		
	var cmMerch = addtionalParam.cmMerch;
	
	this.getCmMerch = function() {
		return cmMerch;
	}
	
	this.init = function(buyGrid) {
//		s_omtr.t();
		s_omtr.evar15 = "QV";
		buyGrid.webAnalyticsController.bypassSendStyleEvent(true);
	}
}		
		

if(!leutil){ var leutil = {}; }
if(!leutil.ui){ leutil.ui = {}; }
leutil.ui.window = new function(){	
	var callbacks = [];
	this.addListener = function(myFunc){
		callbacks.push(myFunc);
	}	
	var exec = function(){
		for(var i=0; i<callbacks.length; i++){
			callbacks[i]();
		}
	}
	var scrollTimer;
	var init = function(){
		$(window).scroll(function(){
			clearTimeout(scrollTimer);
			scrollTimer = setTimeout(exec,100);
		});
		$(window).resize(function(){
			exec();
		});
		
		if(leutil.ui.browser.isMac()){
			$("body").addClass("os-mac");
		}
		if(leutil.ui.browser.isiPad()){
			$("body").addClass("b-iPad")
		}
		if(leutil.ui.browser.isIE6()){
			$("body").addClass("b-ie6");
		}
		if(leutil.ui.browser.isIE7()){
			$("body").addClass("b-ie7");
		}
		if(leutil.ui.browser.isIE8()){
			$("body").addClass("b-ie8");
		}
		if(leutil.ui.browser.isIE9()){
			$("body").addClass("b-ie9");
		}
		if(leutil.ui.browser.isAndroid()){
			$("body").addClass("b-android");
		}
	}	
	$(init);
}
leutil.ui.browser = new function(){
	this.isMac = function(){ //needed to turn off some functionality in select box ui
		if (navigator.appVersion.indexOf("Mac")!=-1){ return true; }
		return false;
	}
	this.isIE = function(){
		return $.browser.msie;
	}
	this.isIE6 = function(){
		if($.browser.msie && parseInt($.browser.version)<=6){ return true }
		return false;
	}
	this.isIE7 = function(){
		if($.browser.msie && parseInt($.browser.version)==7){ return true }
		return false;
	}
	this.isIE8 = function(){
		if($.browser.msie && parseInt($.browser.version)==8){ return true }
		return false;
	}
	this.isIE9 = function(){
		if($.browser.msie && parseInt($.browser.version)==9){ return true }
		return false;
	}
	this.isiPad = function(){
		var r = navigator.userAgent.match(/iPad/i) != null;
		if(r==true){
			$("#whole-page").css("overflow","hidden");
		}
		return r;
	}
	this.isAndroid = function(){
		return navigator.userAgent.match(/android/i) != null;
	}
	this.isTouchScreen = function(){		
		if(this.isiPad() || this.isAndroid()){ // TODO: update with other touch screen browsers as support is added (we don't support android, but it can't hurt to include it)
			return true;
		}
		return false;
	}
}

$.namespace("leutil.ui.animateScrollTo", new function(){
	var thisRef = this;
	this.transition = function(scrollToLocation){
		scrollToPosition = $(scrollToLocation).position();		
		$('html,body').animate({scrollTop:scrollToPosition.top},1000);
	}			
});
if(!leutil){ var leutil = {}; }
if(!leutil.ui){ leutil.ui = {}; }
leutil.ui.Carousel = function(element,settings)
{
	if(!settings){
		settings ={}
	}
	this.element = element; //reference to the carousel container <div>

	this.numberToShow = (settings.numberToShow) ? settings.numberToShow:3; //number of images to show at one time
	this.scrollBySet = (settings.scrollBySet) ? settings.scrollBySet:false; //scrolling occurs by numberToShow, rather than 1 at a time
	this.trueCarousel = (settings.trueCarousel) ? settings.trueCarousel:false; //scrolling loops back to the beginning when the end is reached
	this.horizontalScroll = (settings.horizontalScroll) ? settings.horizontalScroll:true; //layout is horizontal if true, vertical if false
	this.hideText = (settings.hideText) ? settings.hideText:false; //show or hide text related to image
	this.alwaysShowText = (settings.alwaysShowText) ? settings.alwaysShowText:false; //always show text, complete override
	this.doubleControls = (settings.doubleControls) ? settings.doubleControls:false; //show double controls, on both sides of the carousel;
	this.dropShadows = (settings.dropShadows) ? settings.dropShadows:false;//by default the drop shadows are turned off.
	
	this.imageWidth = (settings.imageWidth) ? settings.imageWidth:80; //width of image
	this.imageHeight = (settings.imageHeight) ? settings.imageHeight:121; //height of image
	this.hoverWidth = (settings.hoverWidth) ? settings.hoverWidth:94; //width of image when in hovered state
	this.hoverHeight = (settings.hoverHeight) ? settings.hoverHeight:139; //height of image when in hovered state
	this.imageMargin = (settings.imageMargin) ? settings.imageMargin:10; //right and bottom margin of an image
	this.hoverMargin = (settings.hoverMargin) ? settings.hoverMargin:12; //margin used for hover shadow
	this.paddingForButtons = (settings.paddingForButtons) ? settings.paddingForButtons:31; //right and bottom padding space on the containing <div>
	this.textBuffer = (settings.textBuffer) ? settings.textBuffer:0; //buffer if text is always on
	this.truncateLimit = (settings.truncateLimit) ? settings.truncateLimit:45; //when text is always shown, at what character do we truncate it and add ...?
	this.truncateOnCharacter = (settings.truncateOnCharacter) ? settings.truncateOnCharacter:20; //when text is always shown, at what character do we decide to truncate on text instead of space?

	this.animationSpeed = (settings.animationSpeed) ? settings.animationSpeed:700; //speed of movement animation in milliseconds
	this.hoverSpeed = (settings.hoverSpeed) ? settings.hoverSpeed:75; //speed of the hover animation in milliseconds

	this.defaultsFromCSS = (settings.defaultsFromCSS) ? settings.defaultsFromCSS:true; //try to get default settings from the container's CSS classes
	this.timeoutCount = (settings.timeoutCount) ? settings.timeoutCount:0; //number of retries to load completed
	this.timeoutInterval = (settings.timeoutInterval) ? settings.timeoutInterval:500; //time to give the Ajax request to build the carousel
	this.timeoutMaxTries = (settings.timeoutMaxTries) ? settings.timeoutMaxTries:10; //number of times to check to see if there is data for the carousel

	this.carousel = new Array();
	this.currentlyShowing = (settings.currentlyShowing) ? settings.currentlyShowing: null;
	this.currentPosition = (settings.currentPosition) ? settings.currentPosition: 0;
	this.animationInProgress = (settings.animationInProgress) ? settings.animationInProgress: false;

	this.init();
}

leutil.ui.Carousel.prototype.truncate = function(myElement)
{
	var myText = $(myElement).html();
	if (myText.length > this.truncateLimit)
	{
		myText = myText.substring(0, this.truncateLimit);

		myText = myText.split("").reverse().join("");
		var lastSpaceAt = myText.indexOf(" ");
		myText = myText.split("").reverse().join("");

		if (lastSpaceAt > -1)
		{
			var tempText = myText.substring(0, this.truncateLimit - lastSpaceAt - 1);
			if (tempText.length >= this.truncateOnCharacter)
				myText = tempText;
		}

		myText += "...";

		return myText;
	}
}

leutil.ui.Carousel.prototype.duplicateControls = function()
{
	var additionalHTML = "";
	additionalHTML += "<a href=\"#\" class=\"previous_button previous_button_secondary\"><span>Show Previous</span></a>";
	additionalHTML += "<a href=\"#\" class=\"next_button next_button_secondary\"><span>Show Next</span></a>";

	return additionalHTML;
}

leutil.ui.Carousel.prototype.addHoverHTML = function()
{
	$(this.element).children(".images_container").children(".hover_container").remove();
	var hoverContainerHTML = "<div class=\"hover_container\"><div class=\"hover_text\"></div><div class=\"top_left_border\"></div><div class=\"top_right_border\"></div><div class=\"bottom_left_border\"></div><div class=\"bottom_right_border\"></div></div>";
	$(this.element).children(".images_container").append(hoverContainerHTML);
}

leutil.ui.Carousel.prototype.cleanUp = function(parentRef, myRef)
{
	if (parentRef.horizontalScroll)
	{
		if ($(myRef).position().left < 0 || $(myRef).position().left >= (parentRef.imageWidth + parentRef.imageMargin) * parentRef.numberToShow )
			$(myRef).css("left", -(parentRef.imageWidth + parentRef.imageMargin) * 2);
	}
	else
	{
		if ($(myRef).position().top < 0 || $(myRef).position().top >= (parentRef.imageHeight + parentRef.imageMargin) * parentRef.numberToShow )
			$(myRef).css("top", -(parentRef.imageHeight + parentRef.imageMargin) * 2);
	}
}

leutil.ui.Carousel.prototype.next = function()
{
	var parentRef = this;

	if (this.animationInProgress || this.currentPosition >= this.carousel.length - this.numberToShow)
		return;
	else
	{
		this.animationInProgress = true;
		var last = this.currentlyShowing.length - 1;

		//Images to slide out of frame
		if (this.horizontalScroll)
		{
			if (this.scrollBySet)
			{
				for (var i = 0; i < this.currentlyShowing.length; i++)
					$(this.currentlyShowing[i]).animate({left: $(this.currentlyShowing[i]).position().left - (this.imageWidth + this.imageMargin) * (this.numberToShow), opacity: 0}, parentRef.animationSpeed, function(){ parentRef.cleanUp(parentRef, this); });
			}
			else
			{
				$(this.currentlyShowing[0]).animate({left: $(this.currentlyShowing[0]).position().left -(this.imageWidth + this.imageMargin) * (this.numberToShow + 1), opacity: 0}, parentRef.animationSpeed, function(){});
				for (var i = 1; i < this.currentlyShowing.length; i++)
				{
					$(this.currentlyShowing[i]).animate({left: $(this.currentlyShowing[i]).position().left - (this.imageWidth + this.imageMargin)}, parentRef.animationSpeed, function(){});
					this.currentlyShowing[i - 1] = this.currentlyShowing[i];
				}
			}
		}
		else
		{
			if (this.scrollBySet)
			{
				for (var i = 0; i < this.currentlyShowing.length; i++)
					$(this.currentlyShowing[i]).animate({top: $(this.currentlyShowing[i]).position().top - (this.imageHeight + this.imageMargin + this.textBuffer) * (this.numberToShow), opacity: 0}, parentRef.animationSpeed, function(){ parentRef.cleanUp(parentRef, this); });
			}
			else
			{
				$(this.currentlyShowing[0]).animate({top: -(this.imageHeight + this.imageMargin + this.textBuffer) * (this.numberToShow + 1), opacity: 0}, parentRef.animationSpeed, function(){});
				for (var i = 1; i < this.currentlyShowing.length; i++)
				{
					$(this.currentlyShowing[i]).animate({top: $(this.currentlyShowing[i]).position().top -(this.imageHeight + this.imageMargin + this.textBuffer)}, parentRef.animationSpeed, function(){});
					this.currentlyShowing[i - 1] = this.currentlyShowing[i];
				}
			}
		}

		//Images to bring into frame
		if (this.scrollBySet)
		{
			for (var i = this.numberToShow - 1; i >= 0; i--)
			{
				this.currentlyShowing[i] = this.carousel[this.currentPosition + this.numberToShow];
				this.currentPosition++;
				if (this.currentlyShowing[i] != null)
				{
					if (this.horizontalScroll)
					{
						$(this.currentlyShowing[i]).css({'left':((this.imageWidth + this.imageMargin) * (this.numberToShow - 1)) + ((this.imageWidth + this.imageMargin) * (this.numberToShow - i)), 'opacity':'0'});
						$(this.currentlyShowing[i]).css("display", "block");
						$(this.currentlyShowing[i]).animate({left: 0 + (this.imageWidth + this.imageMargin) * (this.numberToShow - (i + 1)), opacity: 1}, parentRef.animationSpeed, function(){parentRef.animationInProgress = false;});
					}
					else
					{
						$(this.currentlyShowing[i]).css({'top':((this.imageWidth + this.imageHeight + this.textBuffer) * (this.numberToShow - 1)) + ((this.imageHeight + this.imageMargin) * (this.numberToShow - 1 - i)), 'opacity':'0'});
						$(this.currentlyShowing[i]).css("display", "block");
						$(this.currentlyShowing[i]).animate({top: 0 + (this.imageHeight + this.imageMargin + this.textBuffer) * (this.numberToShow - (i + 1)), opacity: 1}, parentRef.animationSpeed, function(){parentRef.animationInProgress = false;});
					}
				}
			}
		}
		else
		{
			this.currentlyShowing[last] = this.carousel[this.currentPosition + this.numberToShow];

			if (this.horizontalScroll)
				$(this.currentlyShowing[last]).css({'left':(this.imageWidth + this.imageMargin) * this.numberToShow, 'opacity':'0'});
			else
				$(this.currentlyShowing[last]).css({'top':(this.imageHeight + this.imageMargin + this.textBuffer) * this.numberToShow, 'opacity':'0'});

			$(this.currentlyShowing[last]).css("display", "block");

			if (this.horizontalScroll)
				$(this.currentlyShowing[last]).animate({left: ($(this.currentlyShowing[last]).position().left - (this.imageWidth + this.imageMargin)), opacity: 1}, parentRef.animationSpeed, function(){parentRef.animationInProgress = false;});
			else
				$(this.currentlyShowing[last]).animate({top: ($(this.currentlyShowing[last]).position().top - (this.imageHeight + this.imageMargin + this.textBuffer)), opacity: 1}, parentRef.animationSpeed, function(){parentRef.animationInProgress = false;});

			this.currentPosition++;
		}

		if (this.currentPosition > 0)
			$(this.element).children(".previous_button").removeClass("disabled_previous_button");
		if (this.currentPosition >= this.carousel.length - this.numberToShow)
			$(this.element).children(".next_button").addClass("disabled_next_button");
	}
}

leutil.ui.Carousel.prototype.previous = function()
{
	var parentRef = this;

	if (this.animationInProgress || this.currentPosition == 0)
		return;
	else
	{
		this.animationInProgress = true;
		var last = this.currentlyShowing.length - 1;

		//Images to slide out of frame
		if (this.horizontalScroll)
		{
			if (this.scrollBySet)
			{
				for (var i = 0; i < this.currentlyShowing.length; i++)
				{
					if (this.currentlyShowing[i] != null)
						$(this.currentlyShowing[i]).animate({left: $(this.currentlyShowing[i]).position().left + (this.imageWidth + this.imageMargin) * (this.numberToShow), opacity: 0}, parentRef.animationSpeed, function(){ parentRef.cleanUp(parentRef, this); });
				}
			}
			else
			{
				$(this.currentlyShowing[last]).animate({left: $(this.currentlyShowing[last]).position().left + (this.imageWidth + this.imageMargin) * (this.numberToShow + 1), opacity: 0}, parentRef.animationSpeed, function(){});
				for (var i = this.currentlyShowing.length - 2; i >= 0 ; i--)
				{
					$(this.currentlyShowing[i]).animate({left: $(this.currentlyShowing[i]).position().left + (this.imageWidth + this.imageMargin)}, parentRef.animationSpeed, function(){});
					this.currentlyShowing[i + 1] = this.currentlyShowing[i];
				}
			}
		}
		else
		{
			if (this.scrollBySet)
			{
				for (var i = 0; i < this.currentlyShowing.length; i++)
				{
					if (this.currentlyShowing[i] != null)
						$(this.currentlyShowing[i]).animate({top: $(this.currentlyShowing[i]).position().top + (this.imageHeight + this.imageMargin + this.textBuffer) * (this.numberToShow), opacity: 0}, parentRef.animationSpeed, function(){ parentRef.cleanUp(parentRef, this); });
				}
			}
			else
			{
				$(this.currentlyShowing[last]).animate({top: $(this.currentlyShowing[last]).position().top + (this.imageHeight + this.imageMargin + this.textBuffer) * (this.numberToShow + 1), opacity: 0}, parentRef.animationSpeed, function(){});
				for (var i = this.currentlyShowing.length - 2; i >= 0 ; i--)
				{
					$(this.currentlyShowing[i]).animate({top: $(this.currentlyShowing[i]).position().top + (this.imageHeight + this.imageMargin + this.textBuffer)}, parentRef.animationSpeed, function(){});
					this.currentlyShowing[i + 1] = this.currentlyShowing[i];
				}
			}
		}

		//Images to bring into frame
		if (this.scrollBySet)
		{
			for (var i = this.currentlyShowing.length - 1; i >= 0; i--)
			{
				this.currentlyShowing[i] = this.carousel[--this.currentPosition];
				if (this.horizontalScroll)
				{
					$(this.currentlyShowing[i]).css({'left':-(this.imageWidth + this.imageMargin) * (this.numberToShow - i), 'opacity':'0'});
					$(this.currentlyShowing[i]).animate({left: (this.imageWidth + this.imageMargin) * i, opacity: 1}, parentRef.animationSpeed, function(){parentRef.animationInProgress = false;});
				}
				else
				{
					$(this.currentlyShowing[i]).css({'top':-(this.imageHeight + this.imageMargin + this.textBuffer) * (this.numberToShow - i), 'opacity':'0'});
					$(this.currentlyShowing[i]).animate({top: (this.imageHeight + this.imageMargin + this.textBuffer) * i, opacity: 1}, parentRef.animationSpeed, function(){parentRef.animationInProgress = false;});
				}
			}
		}
		else
		{
			this.currentlyShowing[0] = this.carousel[this.currentPosition - 1];

			if (this.horizontalScroll)
				$(this.currentlyShowing[0]).css({'left':-(this.imageWidth + this.imageMargin), 'opacity':'0'});
			else
				$(this.currentlyShowing[0]).css({'top':-(this.imageHeight + this.imageMargin + this.textBuffer), 'opacity':'0'});

			if (this.horizontalScroll)
				$(this.currentlyShowing[0]).animate({left: 0, opacity: 1}, parentRef.animationSpeed, function(){parentRef.animationInProgress = false;});
			else
				$(this.currentlyShowing[0]).animate({top: 0, opacity: 1}, parentRef.animationSpeed, function(){parentRef.animationInProgress = false;});

			this.currentPosition--;
		}

		if (this.currentPosition <= 0)
			$(this.element).children(".previous_button").addClass("disabled_previous_button");
		if (this.currentPosition < this.carousel.length - this.numberToShow)
			$(this.element).children(".next_button").removeClass("disabled_next_button");
	}
}

leutil.ui.Carousel.prototype.bindEvents = function()
{
	var parentRef = this;

	//try to unbind events in case of an AJAX reload of content
	$(this.element).children(".images_container").children("a").unbind();
	$(this.element).children(".previous_button").unbind();
	$(this.element).children(".next_button").unbind();

	$(this.element).children(".previous_button").click(
		function() {
			parentRef.previous();
			return false;
		}
	);

	$(this.element).children(".next_button").click(
		function() {
			parentRef.next();
			return false;
		}
	);

	if (!this.alwaysShowText && this.dropShadows == true)
	{
		$(this.element).children(".images_container").children("a").hoverIntent(
			function() {
				if (!parentRef.animationInProgress)
				{
					$(parentRef.element).children(".images_container").children(".hover_container").css("display", "none");
					$(parentRef.element).children(".images_container").css("z-index", 30);
					$(this).css("z-index", 10);
					$(this).css("overflow", "visible");
					$(parentRef.element).children(".previous_button, .next_button").css("z-index", 0);
					$(this).animate({
						height: parentRef.hoverHeight,
						width: parentRef.hoverWidth,
						marginTop: -((parentRef.hoverHeight - parentRef.imageHeight) / 2),
						marginBottom: -((parentRef.hoverHeight - parentRef.imageHeight) / 2),
						marginLeft: -((parentRef.hoverWidth - parentRef.imageWidth) / 2),
						marginRight: -((parentRef.hoverWidth - parentRef.imageWidth) / 2)
					}, parentRef.hoverSpeed, function() {
						$(parentRef.element).children(".images_container").children(".hover_container").css("left", $(this).position().left - ((parentRef.hoverWidth - parentRef.imageWidth) / 2));
						$(parentRef.element).children(".images_container").children(".hover_container").css("top", $(this).position().top - ((parentRef.hoverHeight - parentRef.imageHeight) / 2));
						$(parentRef.element).children(".images_container").children(".hover_container").children(".hover_text").html($(this).children("span").html());
						$(parentRef.element).children(".images_container").children(".hover_container").css("display", "block");
					});
				}
			},
			function() {
				if (!parentRef.animationInProgress)
				{
					$(parentRef.element).children(".images_container").children(".hover_container").css("display", "none");
					$(this).css("z-index", 0);
					$(this).animate({
						height: parentRef.imageHeight,
						width: parentRef.imageWidth,
						marginTop: 0,
						marginBottom: 0,
						marginLeft: 0,
						marginRight: 0
					}, parentRef.hoverSpeed, function() {
						$(parentRef.element).children(".images_container").children(".hover_container").css("display", "none");
						$(parentRef.element).children(".previous_button, .next_button").css("z-index", 20);
						$(parentRef.element).children(".images_container").css("z-index", 0);
					});
				}
			}
		);
	}
}

leutil.ui.Carousel.prototype.getDefaultValuesFromCSS = function()
{
	if ($(this.element).hasClass("show_1"))
		this.numberToShow = 1;
	else if ($(this.element).hasClass("show_2"))
		this.numberToShow = 2;
	else if ($(this.element).hasClass("show_3"))
		this.numberToShow = 3;
	else if ($(this.element).hasClass("show_4"))
		this.numberToShow = 4;
	else if ($(this.element).hasClass("show_5"))
		this.numberToShow = 5;
	else if ($(this.element).hasClass("show_6"))
		this.numberToShow = 6;
	else if ($(this.element).hasClass("show_7"))
		this.numberToShow = 7;
	else if ($(this.element).hasClass("show_8"))
		this.numberToShow = 8;
	else if ($(this.element).hasClass("show_9"))
		this.numberToShow = 9;
	else if ($(this.element).hasClass("show_10"))
		this.numberToShow = 10;

	if ($(this.element).hasClass("scroll_by_set"))
		this.scrollBySet = true;
	else
		this.scrollBySet = false;

	if ($(this.element).hasClass("vertical"))
		this.horizontalScroll = false;
	else if ($(this.element).hasClass("horizontal"))
		this.horizontalScroll = true;
	else
	{
		$(this.element).addClass("horizontal")
		this.horizontalScroll = true;
	}

	if ($(this.element).hasClass("true_carousel"))
		this.trueCarousel = true;
	else
		this.trueCarousel = false;

	if ($(this.element).hasClass("double_controls"))
		this.doubleControls = true;
	else
		this.doubleControls = false;

	if ($(this.element).hasClass("hide_text"))
		this.hideText = true;
	else
		this.hideText = false;

	if ($(this.element).hasClass("always_show_text"))
	{
		this.alwaysShowText = true;
		this.textBuffer = 100;
	}
	else
		this.alwaysShowText = false;
}

leutil.ui.Carousel.prototype.init = function()
{
	if ($(this.element).children(".images_container").children("a").length > 0)
	{
		var parentRef = this;
		
		$(this.element).siblings(".carousel_label").show();

		$(this.element).children(".previous_button").removeClass("disabled_previous_button");
		$(this.element).children(".next_button").removeClass("disabled_next_button");

		this.addHoverHTML();

		$(this.element).children(".images_container").children(".hover_container").children(".hover_text").css("top", this.hoverHeight);

		if (this.defaultsFromCSS)
			this.getDefaultValuesFromCSS();

		if (!this.horizontalScroll && this.doubleControls)
		{
			$(this.element).append(this.duplicateControls());
		}
		else
		{
			$(this.element).removeClass("double_controls");
		}

		$(this.element).children(".previous_button").css("display", "block");
		$(this.element).children(".next_button").css("display", "block");

		if (this.hideText && !this.alwaysShowText)
		{
			$(this.element).children(".images_container").children(".hover_container").children(".hover_text").hide();
		}

		if (this.alwaysShowText)
		{
			$(this.element).find("u").each(function() {
				$(this).html(parentRef.truncate(this));
			});
		}

		this.currentlyShowing = new Array(this.numberToShow);

		if (this.horizontalScroll)
		{
			$(this.element).css("width", (this.imageWidth + this.imageMargin) * this.numberToShow + this.paddingForButtons );
			$(this.element).css("height", this.hoverHeight + this.textBuffer + (2 * this.hoverMargin));
		}
		else
		{
			$(this.element).css("width", (this.imageWidth + this.imageMargin) + this.paddingForButtons );
			$(this.element).css("height", ((this.imageHeight + this.imageMargin) * this.numberToShow) + this.paddingForButtons + (this.textBuffer * this.numberToShow) );
		}

		$(this.element).children(".images_container").children("a").each(function () {
			parentRef.carousel.push(this);
		});

		if (this.carousel.length <= 1 || this.carousel.length == this.numberToShow)
			$(this.element).children(".next_button").addClass("disabled_next_button");

		$(this.element).children(".previous_button").addClass("disabled_previous_button");

		if (this.carousel.length < this.numberToShow)
			this.numberToShow = this.carousel.length;

		for (var i = 0; i < this.numberToShow; i++)
		{
			this.currentlyShowing[i] = this.carousel[i];
			$(this.carousel[i]).show();
			if (this.horizontalScroll)
				$(this.carousel[i]).css("left", i * (this.imageWidth + this.imageMargin));
			else
				$(this.carousel[i]).css("top", i * (this.imageHeight + this.imageMargin + this.textBuffer));
		}

		$(this.element).children(".images_container").css("height", this.imageHeight);

		$(this.element).children(".images_container").children("a").css("width", this.imageWidth);
		$(this.element).children(".images_container").children("a").css("height", this.imageHeight + this.textBuffer);
		if (this.alwaysShowText)
			$(this.element).children(".images_container").children("a").children("img").css("height", this.imageHeight);

		$(this.element).children(".images_container").children(".hover_container").css("height", this.hoverHeight);
		$(this.element).children(".images_container").children(".hover_container").css("width", this.hoverWidth);

		$(this.element).children(".images_container").children(".hover_container").children(".top_left_border").css("height", this.hoverHeight);
		$(this.element).children(".images_container").children(".hover_container").children(".top_right_border").css("width", this.hoverWidth);
		$(this.element).children(".images_container").children(".hover_container").children(".bottom_left_border").css("width", this.hoverWidth);
		$(this.element).children(".images_container").children(".hover_container").children(".bottom_right_border").css("height", this.hoverHeight);

		this.bindEvents();
	}
	else
	{			
		var parentRef = this;
		$(this.element).children(".previous_button").css("display", "none");
		$(this.element).children(".next_button").css("display", "none"); 
		if (this.timeoutCount < this.timeoutMaxTries)
		{
			this.timeoutCount++;
			setTimeout (function() { parentRef.init(); }, parentRef.timeoutInterval );
		}
	}
}
if(!leutil){ var leutil = {}; }
if(!leutil.ui){ leutil.ui = {}; }
leutil.ui.characterCounter = function(textAreaSelector){
	var debug = false;
	var $this = $(textAreaSelector);	
	
	if($this.length > 0 && $this.data("isCharacterCounter")!= true){ // prevent multiple binding / execution
		$this.data("isCharacterCounter",true); // prevent double initialization
		var html = {
			$watermark:		$this.siblings('.custom-textarea-watermark'),
			$instructions:	$this.parent().parent().find("p"),
			$charCount:		$this.parent().parent().find("p").find("span.current"),
			$widthChecker:	$this.parent().siblings(".textarea-width-checker"),
			$trace:			$('<div id="tracer" style="position:absolute; left:-25%; top:-210px; width:150%; height:200px; border:4px solid #999999; background-color:#FFFFFF; font-family:courier,mono-space; z-index:3;" ></div>')
		}
		if(debug == true){
			$this.before(html.$trace); // use this to create preview window
		}
		var settings = {
			rows:	$this.attr("rows"),
			cols:	$this.attr("cols"),
			maxChars: this.rows * this.cols,
			letterWidth: html.$widthChecker.outerWidth()
		}
		var visibleValue;
		var submitValue;
		var isSubmitReady = false;
				
		$this.css({width: settings.letterWidth * settings.cols + 2});
		if($this.val() != ''){ html.$watermark.hide(); }
		
		$this.bind("focus blur keydown keyup",function(e){				
			if(e.type=="focus"){ // hide watermark
				html.$watermark.hide();
				
				// on user focus, swap back to the value the user specifically typed
				if(isSubmitReady && $this.val()!=''){
					$this.val(visibleValue);		
				}
				
				isSubmitReady = false;
			}
			else if(e.type=="blur"){ // show watermark if value is null
				if($this.val()== ''){
					html.$watermark.show();
				}
				// on user leave focus, insert cariage returns between lines that is needed by server validation
				var result = leutil.ui.charCounterTest($this.val(),settings.rows,settings.cols);
				visibleValue = $this.val();
				submitValue = '';
				for(var i=0; i<result.lines.length; i++){
					if(i!=0){ submitValue +='\n'; }
					submitValue+=$.trim(result.lines[i]);
				}
				$this.val(submitValue);
				isSubmitReady = true;
			}
			else if(e.type=="keydown"){ 				
				// test against result of user action and disable keypresses that will break rules	
				var key = window.event ? e.keyCode : e.which;
				var newChar = '';
				var range = $this.getSelection(); // gets cursor selection of chars in text area
				var result;

				// detect key press type
				if(key == 13){ newChar = '\n';} // prevent user from use of enter key
				else if(key == 32){ newChar = ' '; }
				else if(key == 8){ newChar = 'bSpace'; }
				else if(key == 46){ newChar = 'delete'; }
				else if(key <=45 || (key >= 91 && key <=93) || (key>=112 && key<=145)){	newChar = ''; }
				else{ newChar = 'X'; } // doesn't matter what the character is as long as it isn't a space or line break.
							
				if(newChar !== '' && $this.val() !== ''){ // ignore keys that don't affect the number of characters in the text field
					result = leutil.ui.charCounterTest(
						leutil.ui.charCounterTestTextGenerator(newChar,$this.val(),range),
						settings.rows,
						settings.cols);					
					
					if(result.error == true){
						e.preventDefault();
						if($this.data('errorMessage')){						
							clearTimeout($this.data('errorMessage'));
						}
						html.$instructions.addClass("custom-textarea-error");
						$this.data('errorMessage',setTimeout(function(){
							html.$instructions.removeClass("custom-textarea-error");
						},3000));
					}
					if(debug == true){
						var temp = 'Char counter debug window (test):<br/>';
						temp+=('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX').substring(0,settings.cols)+'<br/>';
						for(var i=0; i<result.lines.length; i++){
							temp+=result.lines[i].replace(/ /g,'_')+' : '+result.reasons[i]+'<br/>';
						}
						temp+='<br/>ERROR TEXT: <br/>';
						temp+=result.text.replace(/\n/g,'<br/>').replace(/ /g,'_');
						html.$trace.html(temp);
					}
				}
				html.$charCount.html($this.val().replace(/\n/g, '').length);
			}
			else if(e.type=="keyup"){ 
				html.$charCount.html($this.val().replace(/\n/g, '').length);
			}
		});
	}
	else if( $this.data("isCharacterCounter")== true){ // use to update watermark display for pre-created fields that have their values updated manually by JS later
		var value = $this.val();
		if ($.trim(value) == "") {
			$this.siblings('.custom-textarea-watermark').show();
		} else {
			$this.siblings('.custom-textarea-watermark').hide();
		}
	}
}




leutil.ui.charCounterTestTextGenerator = function(newChar,text,range){
	// generate testText to determine if user action will result in breaking the rules
	var r = '';
	if(text){
		r = text;
		if(newChar == 'bSpace'){
			if(range.length > 0){
				r = text.substring(0,range.start)+text.substring(range.start+range.length);
			}
			else{
				r = text.substring(0,range.start-1)+text.substring(range.start);
			}
		}
		else if(newChar == 'delete'){
			if(range.length > 0){
				r = text.substring(0,range.start)+text.substring(range.start+range.length);
			}
			else{
				r = text.substring(0,range.start)+text.substring(range.start+1);
			}
		}
		else if(newChar){
			r = text.substring(0,range.start)+newChar+text.substring(range.start+range.length);
		}		
	}
	return r;
}




leutil.ui.charCounterTest = function(text,rows,cols){
	var r = {
		lines:[],
		error:false,
		text:'',
		reasons:[] // used to help debug
	}
	var index = cols;
	var autoWrapIndex = -1;
	var manualWrapIndex = -1;
	var indexOffset = 0; // used to ignore end of line spaces as characters
	
	for(var i=0; i<rows; i++){
		if(text && text != ''){
			index = text.length;
			autoWrapIndex = text.lastIndexOf(" ",cols-1)+1;
			manualWrapIndex = text.indexOf('\n');			
			indexOffset = 0;
			r.reasons[i] = 'text.length';
			
			var temp = ' (i'+index+', a'+autoWrapIndex+', m'+manualWrapIndex+')';
			if(manualWrapIndex >= 0 && manualWrapIndex <= index){
				index = manualWrapIndex;
				indexOffset = 1;
				r.reasons[i] = 'manual wrap';
			}
			if(index > cols && autoWrapIndex > 0 && autoWrapIndex < index){
				index = autoWrapIndex;
				indexOffset = 0;
				r.reasons[i] = 'auto wrap';
			}			
			if(index>cols){ // word > length of line
				r.error = true;
				r.text = "ERROR: Single word > cols";
				break;
			}
			if(i==rows-1 && manualWrapIndex >=0){
				r.error = true;
				r.text = "ERROR: no carriage return on last line";
			}
			r.reasons[i]+=temp;
			r.lines[i] = text.substring(0,index);
			
			if(index == text.length){
				text = '';
			}
			else{
				text = text.substring(index+indexOffset);
			}
		}
		else{ // no text left to parse
			break;
		}
	}
	if(text != ''){
		r.error = true;
		r.text = text;
	}
	return r;
}

/*
var modal = leutil.ui.modalHandler.show({
	content: myContent,    // REQUIRED: jQuery element, DOM element, DOM id, HTML string
	header: myHeader, 	   // optional: jQuery element, DOM element, DOM id, HTML string
	footer: myFooter, 	   // optional: jQuery element, DOM element, DOM id, HTML string
	width: 250,			   // optional: int (Width of modal. Default is 250)
	cssClass: "myClass",   // optional: string (CSS class to append to parent element to style unique modals)
	onShow: null, 		   // optional: function, array of functions (default is null)
	onHide: null, 		   // optional: function, array of functions (default is null)
	dialogue: false, 	   // optional: bool (Set behavior to dialogue, no cancel ability, must close with specific action. Default is false)
	fullscreen: false, 	   // optional: bool (Set display to fullscreen modal. Used by prodview image viewer)	
	cacheable: false,	   // optional: bool (Determines if element is stored for quick re-open after it is closed. Default is false)
	scrollable: true,	   // optional: bool (Determines if content is vertically scrollable or not. Default is true)
	overlayClickable: true,// optional: bool (Determines if the modal can be closed by clicking the transparent overlay beneath it. Default is true)
	shadowSize: 43		   // optional: int  (Used for math around positioning, should be updated if CSS for a modal is updated)
}); // returns the modal JQuery element

modal.trigger("hide"); 		 // hide the modal
modal.trigger("update");	 // reposition/resize modal
modal.trigger("show"); 		 // show a modal that is pre-built and cached

leutil.ui.modalHandler.updateAll(); // trigger repositioning on all active modals
leutil.ui.modalHandler.hideAll(); 	// hide all active modals
leutil.ui.modalHandler.hide(modal); // alternate method to hide modal

*/
if(!leutil){ var leutil = {}; }
if(!leutil.ui){ leutil.ui = {}; }
leutil.ui.modalHandler = new function (){
	var thisRef = this;
	this.modalList = [];	
	this.templates = {
		$base: $('<div class="le-modal-wrapper">' +
				'<div class="le-modal-overlay"></div>' +
				'<div class="le-modal" tabIndex="-1">' +
					'<div class="le-modal-nw le-modal-shadow"></div>' +
					'<div class="le-modal-ne le-modal-shadow"></div>' +
					'<div class="le-modal-n le-modal-shadow"></div>' +
					'<div class="le-modal-w le-modal-shadow"></div>' +
					'<div class="le-modal-e le-modal-shadow"></div>' +
					'<div class="le-modal-sw le-modal-shadow"></div>' +
					'<div class="le-modal-se le-modal-shadow"></div>' +
					'<div class="le-modal-s le-modal-shadow"></div>' +
					'<a href="#" class="le-modal-close"><span>close</span></a>' +
				'</div></div>'),
		$scrollpane: $('<div class="le-modal-content-scrollpane"></div>')
	}
	this.queries = {
		window: "div.le-modal",
		overlay: "div.le-modal-overlay",
		closeButton: "a.le-modal-close",
		altCloseButton: ".le-modal-close-alt, .le-modal-alternate-close",
		shadow: "div.le-modal-shadow"
	}
	
	// START live event binding for performance
	$(".le-modal-wrapper .le-modal-close-alt, .le-modal-wrapper .le-modal-alternate-close").live("click",function(e){
		$(this).parents(".le-modal-wrapper").trigger("hide");
	});
	$(".le-modal-wrapper "+this.queries.closeButton+", .le-modal-wrapper "+this.queries.shadow+", .le-modal-wrapper "+this.queries.overlay).live("click",function(e){
		var modal = $(this).parents(".le-modal-wrapper");
		if(modal.data && modal.data("settings") && !modal.data("settings").dialogue){	
			if(modal.data("settings").overlayClickable && $(this).hasClass("le-modal-overlay")){
				modal.trigger("hide");
			}
			else if(!$(this).hasClass("le-modal-overlay")){
				modal.trigger("hide");
			}		
			e.preventDefault();
		}	
	});	
	$(".le-modal-wrapper, .le-modal-wrapper a, .le-modal-wrapper button").live("click",function(e){		
		var modal = ($(this).hasClass("le-modal-wrapper"))?$(this):$(this).parents(".le-modal-wrapper");
		clearTimeout(modal.data("updateTimer"));		
		modal.data("updateTimer",setTimeout(function(){
			modal.trigger("update");
		},200));
	})
	$(".le-modal-wrapper select, .le-modal-wrapper input:checkbox, .le-modal-wrapper input:radio").live("change",function(e){
		var modal = $(this).parents(".le-modal-wrapper");
		clearTimeout(modal.data("updateTimer"));
		modal.data("updateTimer",setTimeout(function(){
			modal.trigger("update");
		},200));
	})
	
	var inProcess = false; // prevent multiple calls to same modal (fast clicker guy)
	var levelCounter = 0; // used to layer modals on top one another
	var defaultShadowSize = 43;
	
	// grab content, determine if cached or needs to be built, then display
	this.init = function(myModal){
		if(!myModal || !myModal.content){ return null; }
		
		if(inProcess == false){
			inProcess = true;
			myModal = this.parseContent(myModal);
			myModal = this.show(myModal);
			inProcess = false;
			return myModal;
		}
		
		return null;
	}	
	// grab content, determine if it can be cached, and then if it is already cached
	this.parseContent = function(myModal){
		if(!myModal && !myModal.content){ return null; }
		
		// handle different types of content: string, DOM, jQuery, id
		if(typeof myModal.content == "string"){ // ID or html string
			if(myModal.content.length < 100 && myModal.content.indexOf("<")==-1){ // assume id
				if(document.getElementById(myModal.content)){ 
					myModal.content = $("#"+myModal.content);
				}
				else{ // not found by Id, html string instead	
					myModal.content = $(myModal.content);
				}
			}
			else{ // html string
				myModal.content = $(myModal.content);			
			}
		}
		else{ // DOM or JQuery
			myModal.content = $(myModal.content);
		}
		
		if(myModal.content.data("modalIndex")){
			myModal = this.modalList[myModal.content.data("modalIndex")];
		}
		else{
			myModal = this.build(myModal);
			myModal = this.registerEvents(myModal);
			if(this.validateModal(myModal) == false){ return null };					
			this.modalList.push(myModal);			
			$("body").prepend(myModal);
		}
		return myModal;
	}	
	this.build = function(myModal){
		if(!myModal && !myModal.content){ return null; }
		
		var modal = this.templates.$base.clone();
		if(myModal.cssClass){ modal.addClass(myModal.cssClass); }
		
		// move settings from creation object to new modal
		modal.data("settings",{			
			cacheable: myModal.cacheable,
			fullscreen: myModal.fullscreen,
			dialogue: myModal.dialogue,
			overlayClickable: (myModal.overlayClickable === false)?myModal.overlayClickable:true,
			scrollable: (myModal.scrollable === false)?myModal.scrollable:true
		});
		var settings = modal.data("settings");

		// target position variables
		modal.data("position",{			
			top:0,
			left:0,
			width:(myModal.width)?myModal.width:250,
			shadowSize: (myModal.shadowSize)?myModal.shadowSize:defaultShadowSize,
			totalHeight:0,
			staticHeight:0,
			variableHeight:0,
			variableHeightIdeal:0,
			screenHeight:0,
			screenWidth:0,
			pageHeight:0,
			pageWidth:0,
			scrollTop:0
		});
		
		modal.data("state",{
			scrollable:false, // track display of scroll bar to adjust width and horizontal position accordingly
			opening:false,
			closing:false
		});
		
		modal.data("callbacks",{
			show:myModal.onShow,
			hide:myModal.onHide			
		});
		
		// Begin html construction		
		modal.data("html",{ // cache jquery objects
			$overlay: modal.find(this.queries.overlay),
			$window: modal.find(this.queries.window),
			$scrollpane: null,
			$content: myModal.content,
			$header: (myModal.header)?myModal.header:null,
			$footer: (myModal.footer)?myModal.footer:null,
			$closeButton: modal.find(this.queries.closeButton),
			$altCloseButton: null,
			$shadow: modal.find(this.queries.shadow)
		});	
		var html = modal.data("html");	
		
				
		// start assembling html chunks		
		if(html.$header){
			html.$header = $(html.$header);
			html.$window.append(html.$header);
		}
		if(html.$content.find("div.le-modal-content-scrollpane").length > 0){ 
			// custom scrollpane passed in through content html (quickview does this)
			settings.scrollable = true;		
			html.$window.append(html.$content);
			html.$scrollpane = html.$content.find("div.le-modal-content-scrollpane");			
			html.$content = html.$scrollpane.find("div.le-modal-content");	
		}
		else if(settings.scrollable){
			html.$scrollpane = this.templates.$scrollpane.clone();
			html.$scrollpane.append(html.$content);
			html.$window.append(html.$scrollpane);
		}		
		else{
			html.$window.append(html.$content);
		}
		if(html.$footer){
			html.$footer = $(html.$footer);
			html.$window.append(html.$footer);
		}
		html.$altCloseButton = html.$window.find(this.queries.altCloseButton);
		
		if(settings.cacheable){
			// used to identify a cached modal during parseContent
			myModal.content.data("modalIndex",this.modalList.length); 
		}
		if(settings.dialogue){
			html.$closeButton.remove();
		}
		
		return modal;
	}	
	this.registerEvents = function(myModal){
		if(this.validateModal(myModal) == false){ return null };
				
		// modal custom methods - must be called using myModal.trigger(methodName);
		myModal.bind("show", function(){ thisRef.show(myModal) }); 
		myModal.bind("hide", function(){ thisRef.hide(myModal) });  // over-rides default jquery method
		myModal.bind("update", function(){ thisRef.update(myModal) });  // reposition / size modal
				
		leutil.ui.window.addListener(function(){thisRef.update(myModal)});
		return myModal;
	}	
	this.show = function(myModal){	
		// if not pre-existing & setup modal, try initializing the modal
		if(this.validateModal(myModal) == false){ return this.init(myModal); };
		if(leutil.ui.browser.isIE6()){ 
			$("select").css("visibility","hidden");
			myModal.find("select").css("visibility","visible");
		}
		$("body").addClass("modal-active");
		var settings = myModal.data("settings");
		var html = myModal.data("html");
		var position = myModal.data("position");
		var state = myModal.data("state");
		
		state.opening = true;
		
		// increase level of modal to account for layering them as new are added
		levelCounter++;
		myModal.css("zIndex",500 + levelCounter);	
		
		// hide interior elements to make animation in smoother		
		if(html.$header){
			html.$header.fadeTo(0,0);
		}
		if(html.$scrollpane){
			html.$scrollpane.fadeTo(0,0);
		}
		else if(html.$content){
			html.$content.fadeTo(0,0);
		}
		if(html.$footer){
			html.$footer.fadeTo(0,0);
		}
		
		myModal.find(".le-modal-content-hide").removeClass("le-modal-content-hide");
		
		// update positioning variable for centering
		myModal.css({
			display:"block",
			opacity:0
		});
		
		// initialize UI components that need visibility / don't work with .live()
		leutil.ui.selectHandler.init();
		leutil.ui.watermarkHandler.init();
		
		if(settings.fullscreen){
			position.width = position.screenWidth - position.shadowSize;
		}
		html.$window.css("width",position.width+"px");
		
		this.update(myModal);
		html.$window.css({
			display:"block",
			left:position.left,
			top:position.top
		});
		if(html.$scrollpane){
			html.$scrollpane.css("height",Math.round(position.variableHeight/2));
		}
		// begin animation		
		myModal.css({
			height:(position.pageHeight>position.screenHeight)?position.pageHeight:position.screenHeight,
			width:(position.pageWidth>position.screenWidth)?position.pageWidth:position.screenWidth
		});
		myModal.fadeTo("fast",1);
		html.$window.animate({
			left:position.left,
			top:position.top
		}, "fast", function(){		
			thisRef.update(myModal);
			html.$window.animate({
				left:position.left,
				top:position.top
			},"fast");
			if(html.$scrollpane){
				html.$scrollpane.animate(
				{
					opacity:1,
					height:position.variableHeight
				},
				"fast",
				function(){thisRef.postShow(myModal)});
			}
			else if(html.$content){
				html.$content.fadeTo("fast",1,function(){thisRef.postShow(myModal)});
			}
			if(html.$header){
				html.$header.fadeTo("fast",1);
			}
			if(html.$footer){
				html.$footer.fadeTo("fast",1);
			}
		});
		
		return myModal;
	}
	this.postShow = function(myModal){
		if(this.validateModal(myModal) == false){ return null };
		
		myModal.data("html").$window.focus(); // set focus to the window per accessibility
		myModal.data("settings").isActive = true;
		
		var callbacks = myModal.data("callbacks").show;
		if(callbacks){
			if(callbacks.length){
				for(var i=0; i<callbacks.length; i++){
					callbacks[i](myModal);
				}
			}
			else{
				callbacks(myModal);
			}
		}
		myModal.data("state").opening = false;
	}	
	this.hide = function(myModal){
		$("body").removeClass("modal-active");
		if(this.validateModal(myModal) == false){ return null };
		window.leutil.ui.selectHandler.hideAll();
		window.leutil.ui.tooltipHandler.hideAll();
		
		//myModal.data("state").closing = true;
		if(myModal.data("settings").isActive){
			myModal.fadeTo("fast",0,function(){ thisRef.postHide(myModal); });
		}
		return myModal;
	}
	this.postHide = function(myModal){
		if(this.validateModal(myModal) == false){ return null };
		if(leutil.ui.browser.isIE6()){ 
			$("select").css("visibility","visible");
		}
		
		var settings = myModal.data("settings");
		var callbacks = myModal.data("callbacks").hide;
		//myModal.data("state").closing = false;
		settings.isActive = false;
		if(callbacks){
			if(callbacks.length){
				for(var i=0; i<callbacks.length; i++){
					callbacks[i](myModal);
				}
			}
			else{
				callbacks(myModal);
			}
		}		
		if(!settings.cacheable){
			// destroy modal if not cacheable
			myModal.remove();
			myModal = null;
		}
		else{
			myModal.css("display","none");
		}
	}
	this.hideAll = function(){
		for(var i = 0; i < this.modalList.length; i++){
			this.hide(this.modalList[i]);
		}
	}	
	this.update = function(myModal){
		if(this.validateModal(myModal) == false){ return null };
		
		var settings = myModal.data("settings");
		var html = myModal.data("html");
		var position = myModal.data("position");
		var state = myModal.data("state");
		
		// START math...  :(
		position.screenHeight = $(window).height();
		position.screenWidth = $(window).width();
		position.pageHeight = $(document).height();
		position.pageWidth = $(document).width();
		position.scrollTop = $(window).scrollTop();
		
		position.totalHeight = html.$window.height();
		position.variableHeightIdeal = html.$content.height();
		position.variableHeight = (html.$scrollpane)?html.$scrollpane.height():position.variableHeightIdeal;
		position.staticHeight = position.totalHeight - position.variableHeight;
		position.variableHeightMax = position.screenHeight - position.shadowSize - position.staticHeight;
		if(settings.scrollable){ // account for 20px padding around scroll pane
			position.variableHeightMax = position.variableHeightMax - 40;
		}
		if(position.variableHeightIdeal > position.variableHeightMax){
			// force modal to constrain height to available screen space
			state.scrollable = true;
			position.variableHeight = position.variableHeightMax;
		}
		else if(position.variableHeightIdeal <= position.variableHeight){ 
			// prevent modal from shrinking vertically & horizontally except during open
			state.scrollable = false;
			if(state.opening){
				position.variableHeight = position.variableHeightIdeal;
			}
		}
		else{
			//enable modal to expand to available space
			state.scrollable = false;
			position.variableHeight = position.variableHeightIdeal;
		}
		position.totalHeight = position.variableHeight + position.staticHeight;
		
		if(!settings.fullscreen){
			if(leutil.ui.browser.isIE() || leutil.ui.browser.isiPad()){ // IE doesn't like position:fixed even though 7 & 8 technically support it
				position.top = position.scrollTop + (position.screenHeight - position.totalHeight) / 2 - position.shadowSize;
			}
			else{
				position.top = (position.screenHeight - position.totalHeight) / 2 - position.shadowSize;
			}
				
			if(position.width > position.screenWidth){
				position.left = position.shadowSize / -2;
			}
			else{
				position.left = (((position.pageWidth<position.screenWidth)?position.pageWidth:position.screenWidth) - position.width) / 2 - position.shadowSize;
			}
			if(settings.scrollable){ // acount for scrollpane border/padding
				position.left = position.left - 15;
			}
			if(state.scrollable){ // account for content scroll bar
				position.left = position.left - 10;
			}
		}
		else{
			position.top = -20;
			if(leutil.ui.browser.isIE() || leutil.ui.browser.isiPad()){ // IE doesn't like position:fixed even though 7 & 8 technically support it
				position.top = position.top + position.scrollTop;
			}			
			position.left = -20;
			position.width = position.screenWidth - 40;
			position.variableHeight = position.screenHeight - 40;
			if(settings.scrollable){
				position.width = position.width - 60;	
				position.variableHeight = position.variableHeight - 40;
			}
			
		}
		
		// START display update				
		if(leutil.ui.browser.isIE() || leutil.ui.browser.isiPad()){ // IE doesn't like position:fixed even though 7 & 8 technically support it
			html.$window.css("position","absolute");
		}
		else{
			html.$window.css("position","fixed");
		}
		if(settings.scrollable){
			html.$content.css({
				width:position.width,
				overflow:"hidden"
			});
			html.$scrollpane.css("height",position.variableHeight);	
			
			if(state.scrollable){
				html.$scrollpane.css("overflow","auto");
				html.$scrollpane.css("width",position.width+20); //add width for vertical scrollbar
				html.$window.css("width",position.width+50);
			}
			else{
				html.$scrollpane.css("overflow","hidden");
				html.$scrollpane.css("width",position.width);
				html.$window.css("width",position.width+30);
			}		
		}
		// - only execute if opening / closing animations are executing
		if(!state.opening && !state.closing){	
			html.$window.stop().animate(
				{
					top:position.top,
					left:position.left
				},
				"fast", "swing");
		}
		return myModal;
	}
	this.updateAll = function(){
		for(var i = 0; i < this.modalList.length; i++){
			this.update(this.modalList[i]);
		}
	}
	this.validateModal = function(myModal){
		if(myModal && myModal.data &&  myModal.data("settings") && myModal.data("html") && myModal.data("position") && myModal.data("state")){ 
			return true;
		}
		return false; 
	}
}

$(".toggle-text-input, .fn-toggle-text-input").live("click", function(e){
	if(!$(this).data("html")){
		$(this).data("html", {
			passwordInput:($(this).siblings("input[type='password']").length == 0) ? $('#'+$(this).attr('data-password-id')) : $(this).siblings("input[type='password']"), 
			textInput: ($(this).siblings("input[type='text']").length == 0) ? $('#'+$(this).attr('data-password-text-id')) : $(this).siblings("input[type='text']")
		});
		
		// update value of password field whenever a keyup event occurs, needed for non-js form submits (ie. order-confirm)
		$(this).data("html").textInput.bind("keyup", function(){ 
			$(this).siblings("input[type='password']").val($(this).val());
		});
	}
	if($(this).data("html").passwordInput.is(":visible")){
		$(this).data("html").textInput.val($(this).data("html").passwordInput.val()).show().focus();
		$(this).data("html").passwordInput.hide();
		$(this).text('hide password');
	}
	else{
		$(this).data("html").passwordInput.val($(this).data("html").textInput.val()).show().focus();
		$(this).data("html").textInput.hide();
		$(this).text('show password');
	}
});
$.namespace("leutil.ui.processingHandlerInline", new function(){
	this.hide = function(myButton){
		myButton.siblings(".overlay-spinner").remove();
	}
	this.show = function(myButton,mySettings){
		// settings parameter to customize specific instances (prodview)
		var settings = {
			top:(mySettings && mySettings.top)?mySettings.top:3,
			left:(mySettings && mySettings.left)?mySettings.left:2,
			image:(mySettings && mySettings.image)?mySettings.image:"spinner_16x16.gif"
		}
		this.hide(myButton);
		myButton.after(($('<img class="overlay-spinner" src="/cos/images/'+settings.image+'" />')
			.css({'top':myButton.position().top+settings.top,'left':myButton.position().left+myButton.outerWidth(true)+settings.left})));	
	}
});
/*
leutil.ui.selecthandler.init(); // finds all appropriate selects and updates them with updated UI.

var select = leutil.ui.selectHandler.update(mySelect);
	mySelect // REQUIRED: JQuery or DOM <select> the faux select box is based upon
}); // returns the select wrapper JQuery element

select.trigger("update"); // force faux select to update it's display following changes to the true select beneath it, called from faux select as reference
$(mySelect).trigger("update"); // force faux select to update it's display following changes to the true select beneath it, called from real select as reference

leutil.ui.selecthandler.hideAll(); // hide all select menus

*/
if(!leutil){ var leutil = {}; }
if(!leutil.ui){ leutil.ui = {}; }
leutil.ui.selectHandler = new function(){
	var thisRef = this;
	this.selectList = []; // array of all faux select objects
	var overlayAdded = false;
	this.overlay = null;
	
	this.templates = {
		overlay:$('<div class="le-select-overlay" style="display:none;"></div>'),
		link:$('<a class="le-select"><span></span></a>'),
		menu:$('<ul class="le-select-menu" style="display:none;"></ul>'),
		menuItem:$('<li><a href="#"></a></li>')
	}
	
	this.queries = {
		searchString:".le-select-wrapper"
	}
	
	// START live event binding for performance
	$("a.le-select").live("click",function(e){		
		if($(this).parent().data && $(this).parent().data("state") && !$(this).parent().data("state").active){	
			thisRef.showMenu($(this).parent());
			$(this).siblings("select").focus();				
		}
		e.preventDefault();
	});
	$(".le-select-wrapper select").live("focus",function(){
		$(this).parent().addClass("le-select-wrapper-hilight");
	});
	$(".le-select-wrapper select").live("blur",function(){
		$(this).parent().removeClass("le-select-wrapper-hilight");
	});
	$(".le-select-wrapper select").live("keypress keydown keyup",function(e){	
		var select = $(this).parent();
		if(window.leutil.ui.browser.isMac()){
			var code;
			if (e.keyCode) code = e.keyCode;
			else if (e.which) code = e.which;
				
			if(code == 38 || code == 40){
				if(code == 38){
					$(this).val($(this).find(":selected").prev().attr("value"));
				}
				else{
					$(this).$input.val($(this).find(":selected").next().attr("value"));
				}
				thisRef.update(select);
				
				e.returnValue = false;
				return false;
			}
		}
		window.setTimeout(function(){ //delay so keydown event captures updated value
			var code;
			if (e.keyCode) code = e.keyCode;
			else if (e.which) code = e.which;
						
			thisRef.update(select);
			if((code == 9 || code == 13)){ // enter or tab key
				thisRef.hide(select);
			}
			else if(code!=16){ // if not shift key, prevents auto show for shift tabbing into field
				thisRef.update(select);
				if(select.data && select.data("state") && !select.data("state").active){ 
					thisRef.showMenu(select); 
				}
			}
		},50);
	});
	
	this.init = function(){
		if (leutil.ui.browser.isIE6() || leutil.ui.browser.isiPad()){ return null } // disable for i-pad and IE6
		
		$(this.queries.searchString).each(function(){
			thisRef.update($(this));
		});
	}

	this.update = function(mySelect){
		if (!mySelect || mySelect.width() == 0 || leutil.ui.browser.isIE6() || leutil.ui.browser.isiPad()){ return null } // disable for i-pad and IE6
		
		mySelect = $(mySelect); // guarantee jquery object
		if(!mySelect.hasClass("le-select-wrapper")){
			mySelect = mySelect.parent(".le-select-wrapper");
		}
		if(mySelect.length == 0){ return null; } // not found or invalid format
		
		this.addOverlay(); // add transparent overlay that is utilized for all selects (click off event)
		
		if(!mySelect.data("html")){ // if not built, build it
			mySelect = this.build(mySelect);
		}
		
		var position = mySelect.data("position");
		var html = mySelect.data("html");
		var state = mySelect.data("state");
		
		position.height = mySelect.height();
		if(position.height < 20){ position.height = 20; }
		position.width = mySelect.width() - 26; // leave room for padding and arrow icon
		
		html.$link.css({
			height: position.height,
			width: position.width
		});	
				
		mySelect = thisRef.updateSummary(mySelect);
		mySelect.data("value", html.$input.val());
				
		if(html.$input.attr("disabled") == true){
			state.disabled = true;
			html.$link.addClass("le-select-disabled");
		}
		else{
			state.disabled = false;
			html.$link.removeClass("le-select-disabled");
		}
		
		mySelect = this.hilightSelectedMenuItem(mySelect);
				
		return mySelect;
	}
	
	this.updateAll = function(myString){
		for(var i = 0; i < this.selectList.length; i++){
			this.update(this.selectList[i]);
		}
	}

	this.updateSummary = function(mySelect){
		var html = mySelect.data("html");
		
		var text = html.$input.find(":selected").text();
		var tempText = "";
		var matches = 0;
				
		text = leftRightText(text);		
		
		if(text.indexOf("|") != -1){ // if multi-line, see if first line is unique to use as summary, else use full summary
			tempText = (text.substring(0,text.indexOf("|"))).toLowerCase();
			html.$input.find("option").each(function(i){
				if($(this).text().toLowerCase().indexOf(tempText)!=-1){
					matches++;
				}
			});
			if(matches<=1){ // is unique
				text = tempText;
			}
		}
		
		text = $.trim(text).replace(/\n/g,"").replace(/\t/g,"").replace(/\s+/g, " "); //remove white space text
		
		// shorten long summaries that are not left right split with elipses (...), prevent IE7 (which struggles) from executing this relatively heavy cosmetic function
		if(text.indexOf("<b")==-1 && !window.leutil.ui.browser.isIE7()){			
			tempText = text;
			var widthTester = $("<span style=\"visibility:hidden; display:inline; white-space:nowrap;\"></span>");
			widthTester.html(text);	
			html.$link.append(widthTester);
			var maxWidth = html.$summary.width() - 12;
			var minWidth = maxWidth - 20;
			var testWidth = widthTester.width();
			var index = 0;
			var stopper = 5;
			
			if(testWidth > maxWidth){ // elipses needed
				index = Math.ceil(text.length * maxWidth / testWidth)+1; // guestimate to get close, then add or remove letters until correct
				while(testWidth < minWidth || testWidth > maxWidth){	
					tempText = text.substring(0,index);
					widthTester.html(tempText);
					testWidth = widthTester.width();
					if(testWidth < minWidth){ index++; }else{ index--; }					
					stopper--; // end loop after specific tries for optimization
					if(stopper <=0){break;}
				}
				text = tempText + "..."
			}
			widthTester.remove();
		}
		
		html.$summary.html(text);
		return mySelect;
	}
	
	var leftRightText = function(myText){
		if(myText && myText.indexOf(". . . .")!=-1){
			myText = myText.split(". . . .");
			if(myText.length<2){	
				myText = myText.join(". . . .");
			}
			else{
				myText = '<b style="float:left;">'+myText[0]+'</b>' +
					'<b style="float:right;">'+myText[1]+'</b>';
			}
		}
		return myText;
	}

	this.build = function(mySelect){
		mySelect.data("html", {
			$link: null,
			$summary: null,
			$input: mySelect.find("select"),
			$menu: null,
			$menuItems: null
		});
		mySelect.data("position", {
			offsetTop: 0,
			offsetBottom: 0,
			height: 0,
			width: 0,
			menuHeight: 0,
			menuWidth: 0,
			heightAbove: 0,
			heightBelow: 0,
			screenHeight: 0,
			screenWidth: 0,
			scrollTop: 0,
			heightAvailable: 0
		});
		mySelect.data("state", {
			active: false,
			disabled: false,
			value: null,
			menuAlignment: "left"
		});
		// align menu that is larger 
		if(mySelect.hasClass("le-select-align-right")){
			mySelect.data("state").menuAlignment = "right";
		}
		
		var html = mySelect.data("html");
		html.$link = this.templates.link.clone();
		html.$summary = html.$link.find("span");
		mySelect.append(html.$link);
		
		this.selectList.push(mySelect);
		return this.registerEvents(mySelect);
	}
	
	this.registerEvents = function(mySelect){		
		var html = mySelect.data("html");
		var state = mySelect.data("state");
		
		// expose to .update(mySelect) to enable re-drawing 
		// faux select after altering the real select
		mySelect.bind("update", function(){
			thisRef.update(mySelect);
		});
		html.$input.bind("update", function(){ 
			thisRef.update(mySelect);
		});
		html.$input.bind("change",function(){
			thisRef.update(mySelect);
		});
		
		return mySelect;
	}
	
	this.showMenu = function(mySelect){
		var html = mySelect.data("html");
		var state = mySelect.data("state");
		var position = mySelect.data("position");
		var temp;
		var isLeftRightText = false;
		
		if(state.disabled){ return mySelect; }
		state.active = true;
		
		// build the html for the menu
		if(html.$menu){ html.$menu.remove(); }
		html.$menu = this.templates.menu.clone();
		
		// create each menu item, and bind it's click to update the value of the select
		html.$input.find("option").each(function(i){
			var option = $(this);
			temp = thisRef.templates.menuItem.clone();
			var text = option.text().replace(/\|/g,"<br />");
			
			text = leftRightText(text);
			if(text.indexOf("<b")!=-1){
				isLeftRightText = true;
			}
			temp.find("a").html(text)
				.data("value", option.val())
				.bind("click",function(e){
					thisRef.hideAll();
					html.$input.val(option.val());
					html.$input.change();
					e.preventDefault();
				});
			html.$menu.append(temp);
		});
		html.$menuItems = html.$menu.find("a");
		
		mySelect = this.hilightSelectedMenuItem(mySelect);
		
		// set default display properties and attach menu to DOM
		this.overlay.css({
			display: "block",
			width: "100%",
			height: $(document).height()
		});	
		html.$menu.css({
			visibility: "hidden",
			display: "block",
			height: "auto",
			width: "auto",
			overflow: "hidden"
		});
		$("body").append(html.$menu);
			
		// calcluate positioning
		position.offsetTop = mySelect.offset().top;
		position.offsetLeft = mySelect.offset().left;	
		position.displayHeight = mySelect.height();
		position.displayWidth = mySelect.width();
		position.screenHeight = $(window).height();
		position.screenWidth = $(window).width();
		position.scrollTop = $(window).scrollTop();

		// get height of menu + available screen space relative to the select
		position.menuHeight = html.$menu.height();		 
		position.heightBelow = position.screenHeight - (position.offsetTop - position.scrollTop + position.height) - 5;
		position.heightAbove = position.offsetTop - position.scrollTop - 5;
		position.menuWidth = (position.displayWidth - 1 > html.$menu.width())?position.displayWidth - 1:html.$menu.width();
		if(leutil.ui.browser.isIE7() && isLeftRightText){
			position.menuWidth = position.displayWidth;
		}
		
		// set height and position top of menu + handle scrollable menu
		if(position.heightAbove > position.heightBelow && position.menuHeight > position.heightBelow){ // menu above select box
			position.heightAvailable = position.heightAbove;
			if(position.menuHeight > position.heightAvailable){
				position.heightAvailable = position.heightAvailable - 10;
				position.menuWidth;
				html.$menu.css({
					width: position.menuWidth,
					height: position.heightAvailable,
					top: (position.scrollTop + 14)+"px",
					overflow: "auto"
				});
			}
			else{
				html.$menu.css({
					width: position.menuWidth,
					height: position.menuHeight,
					top: (position.offsetTop - position.menuHeight - 1)+"px",
					overflow: "hidden"
				});
			}
		}
		else{ // menu below select box
			position.heightAvailable = position.heightBelow;
			if(position.menuHeight > position.heightAvailable){
				position.heightAvailable = position.heightAvailable - 10;
				position.menuWidth;
				html.$menu.css({
					width: position.menuWidth,
					height: position.heightAvailable,
					top: (position.offsetTop + position.height + 3)+"px",
					overflow: "auto"
				});
			}
			else{
				html.$menu.css({
					width: position.menuWidth,
					height: position.menuHeight,
					top: (position.offsetTop + position.height + 3)+"px",
					overflow: "hidden"
				});
			}
		}
				
		// set x position & display menu
		if((position.menuWidth + position.offsetLeft > position.screenWidth) || state.menuAlignment == "right"){ // if menu goes out of screen area
			html.$menu.css({
				left: (position.offsetLeft - (position.menuWidth - position.displayWidth)) + "px",
				visibility: "visible"
			});
		}
		else{ // default
			html.$menu.css({
				left: (position.offsetLeft) + "px",
				visibility: "visible"
			});
		}
		
		return mySelect;
	}
	
	this.hilightSelectedMenuItem = function(mySelect){
		if(mySelect.data("state").active == false){ return null; }
		var html = mySelect.data("html");
		var position = mySelect.data("position");		
		var selectedOffset = 0;
		
		html.$menuItems.each(function(){
			if($(this).data("value") == mySelect.data("value")){
				$(this).addClass("selected");
				selectedOffset = $(this).parents("li").position().top + html.$menu.scrollTop();
			}
			else{
				$(this).removeClass("selected");
			}
		});
		
		// scroll menu to hilight correct item where applicable		
		if(selectedOffset > 0 && position.heightAvailable < position.menuHeight){
			var target = selectedOffset;
			mySelect.data("target",target);
			if(position.menuHeight - selectedOffset < position.heightAvailable){
				target = position.menuHeight - position.heightAvailable;
			}
			clearTimeout(mySelect.data("timer"));
			mySelect.data("timer", setTimeout(function(){ 
				html.$menu.stop().scrollTop(target);
			},200));
		}
		return mySelect;
	}
	this.hide = function(mySelect){
		if(mySelect && mySelect.data && mySelect.data("state") && mySelect.data("state").active){
			mySelect.data("state").active = false;
			mySelect.data("html").$menu.remove();
		}
		else{
			mySelect = null;
		}
		this.overlay.css("display","none");
	}
	this.hideAll = function(){ 
		for(var i=0; i<this.selectList.length; i++){
			this.hide(this.selectList[i]);
		}
	}
	this.addOverlay = function(){
		if(!overlayAdded){	
			this.overlay = this.templates.overlay.clone();
			$("body").prepend(this.overlay);
			this.overlay.bind("click",function(){ thisRef.hideAll() });
			overlayAdded = true;
		}
	}
}
$(document).ready(function(){
	leutil.ui.selectHandler.init();
});

/*
var tooltip = leutil.ui.tooltipHanlder.show({
	button: $("a.myButton"),// REQUIRED: JQuery or DOM element the tooltip is attached to
	text: "Don't do that!",	// REQUIRED: string (html is allowed, but note it is dropped in a <p> tag. If null is passed, will hide all tooltips instead)
	type: "error", 			// optional: string ("error", "warning", "default", or custom class. Default is "default")
	orientation: "bottom" 	// optional: string ("bottom", "top", "left" & "right". Default is "bottom". If space is not available, will go with opposite instead)
}); // returns the tooltip JQuery element

tooltip.trigger("hide"); // remove the tooltip

leutil.ui.tooltipHandler.hide(myTooltipOrButton); //alternate method to remove a specific tooltip
leutil.ui.tooltipHandler.hideAll(); // hide all tooltips

*/
if(!leutil){ var leutil = {}; }
if(!leutil.ui){ leutil.ui = {}; }
leutil.ui.tooltipHandler = new function(){
	var thisRef = this;
	if(leutil.ui.window){ // hide all tooltips whenever screen is resized or moved
		leutil.ui.window.addListener(function(){
			thisRef.hideAll();
		});
	}
	
	this.tooltipList = [];
	this.templates = {
		base: $('<div class="le-tooltip"><p class="le-tooltip-content"></p><span class="le-tooltip-n"></span><span class="le-tooltip-ne"></span><span class="le-tooltip-e"></span><span class="le-tooltip-se"></span><span class="le-tooltip-s"></span><span class="le-tooltip-sw"></span><span class="le-tooltip-w"></span><span class="le-tooltip-nw"></span><span class="le-tooltip-arrow-down le-hide"><span></span></span><span class="le-tooltip-arrow-up le-hide"><span></span></span><span class="le-tooltip-arrow-left le-hide"><span></span></span><span class="le-tooltip-arrow-right le-hide"><span></span></span></div>')
	}
	
	//this.delayTime = 200; // used to prevent tooltip from displaying in touch screen before click event can fire
		
	this.show = function(myTooltip){
		if(!myTooltip.text || !myTooltip.button || $(myTooltip.button).length != 1){ return null; } //check required fields	
	
		this.hideAll();				
		var myTooltip = this.build(myTooltip);
		
		if(leutil.ui.browser.isTouchScreen()){ // delay launch of tooltip in touch screen so that hover event doesn't prevent click event
			myTooltip.data("html").$button.bind("mouseup.tooltip", function(){
				thisRef.display(myTooltip);
				$(this).unbind(".tooltip");
			});
			/*setTimeout(function(){
				thisRef.display(myTooltip);
				},delayTime);*/
		}
		else{
			this.display(myTooltip);
		}

		return myTooltip;
	}
	
	this.build = function(myTooltip){
		var tooltip = this.templates.base.clone();

		tooltip.data("html", {
			$button: myTooltip.button,
			$text: tooltip.find("p.le-tooltip-content").html(myTooltip.text)
		});
		var html = tooltip.data("html");
		
		tooltip.data("position", {
			height: 0,
			width: 0,
			left: 0,
			top: 0,
			screenHeight: 0,
			screenWidth: 0,
			pageHeight: 0,
			pageWidth: 0,
			scrollTop: 0
		});
		var position = tooltip.data("position");

		tooltip.data("state", {
			orientation: "bottom"
		});
		
		tooltip.data("settings", {
			type: (myTooltip.type)?myTooltip.type:"default",
			orientation: (myTooltip.orientation)?myTooltip.orientation:"bottom"
		});
		var settings = tooltip.data("settings");

		if(settings.type.toLowerCase() == "error"){
			tooltip.addClass("le-tooltip-error");
		}
		else if(settings.type.toLowerCase() == "warning"){
			tooltip.addClass("le-tooltip-warning");
		}
		else if(settings.type.toLowerCase() != "default"){ //custom class passed in
			tooltip.addClass(settings.type);
		}		
		if(settings.orientation == "left" || settings.orientation == "right"){
			tooltip.addClass("le-tooltip-vertical");
		}

		if(html.$button.data("ttid") != null){ // remove pre-existing tooltip attached to button if applicable
			this.hide(html.$button);
			html.$button.data("ttid",null);
		}
		html.$button.data("ttid",this.tooltipList.length); // tie button to tooltip to enable hide method to be called from button
		
		tooltip.css({
			visibility: "hidden",
			display: "none"
		});
		this.tooltipList.push(tooltip);
		return tooltip;
	}
		
	this.display = function(myTooltip){
		var html = myTooltip.data("html");
		var position = myTooltip.data("position");
		var settings = myTooltip.data("settings");
		var state = myTooltip.data("state");
		
		$("body").prepend(myTooltip);
		myTooltip.css("display","block");
		
		position.height = myTooltip.height();
		position.width = myTooltip.width();
		position.screenHeight = $(window).height();
		position.screenWidth = $(window).width();
		position.scrollTop = $(window).scrollTop();

		if(settings.orientation == "top" || settings.orientation == "bottom"){
			
			if(settings.orientation == "top"){
				state.orientation = "top";
				position.top = Math.round(html.$button.offset().top - position.height) - 2;
				if(position.top < position.scrollTop){ // not enough space above, go below
					position.top = Math.round(html.$button.offset().top + html.$button.innerHeight()) + 2;
					state.orientation = "bottom";
				}
			}
			else if(settings.orientation == "bottom"){
				state.orientation = "bottom";
				position.top = Math.round(html.$button.offset().top + html.$button.innerHeight()) + 2;
				if(position.top + position.height > position.scrollTop + position.screenHeight){ // not enough space below, go above
					position.top = Math.round(html.$button.offset().top - position.height) - 2;
					state.orientation = "top";
				}
			}

			if(state.orientation == "top"){
				if(leutil.ui.browser.isiPad()){ position.top = position.top + 10; } // correct alignment for ipad
				myTooltip.find(".le-tooltip-arrow-down").removeClass("le-hide");
				myTooltip.find(".le-tooltip-arrow-up, .le-tooltip-arrow-left, .le-tooltip-arrow-right").addClass("le-hide");
			}
			else if(state.orientation == "bottom"){
				if(leutil.ui.browser.isiPad()){ position.top = position.top - 10; } // correct alignment for ipad
				myTooltip.find(".le-tooltip-arrow-up").removeClass("le-hide");
				myTooltip.find(".le-tooltip-arrow-down, .le-tooltip-arrow-left, .le-tooltip-arrow-right").addClass("le-hide");
			}

			position.left = Math.round(html.$button.offset().left + html.$button.innerWidth()/2 - position.width/2) - 1; // negative 1 for border
		}
		else{ // show tooltip beside button
			if(settings.orientation == "right"){
				
			}
			else if(settings.orientation == "left"){
				
			}
		}

		if(leutil.ui.browser.isiPad()){ // TODO be prepared to remove this if iPad corrects this behavior in their browser
			position.top = position.top - position.scrollTop;			
		}	
		if(leutil.ui.browser.isTouchScreen()){
			setTimeout(function(){
				thisRef.hide(myTooltip);
				}, 2500);
		}

		myTooltip.css({
			top: position.top,
			left: position.left,
			visibility: "visible"
		});
	}
	
	this.hide = function(myTooltipOrButton){
		if(myTooltipOrButton.data("ttid") || myTooltipOrButton.data("ttid") === 0){
			myTooltipOrButton = this.tooltipList[myTooltipOrButton.data("ttid")];
		}
		if(myTooltipOrButton.data("html")){
			var index = myTooltipOrButton.data("html").$button.data("ttid");
			myTooltipOrButton.data("html").$button.data("ttid",null);		
			this.tooltipList[index].remove();
			this.tooltipList[index] = null;	
		}
		return null;
	}	
	
	this.hideAll = function(){
		for(var i=0; i<this.tooltipList.length; i++){
			if(this.tooltipList[i]){
				this.hide(this.tooltipList[i]);
			}
		}
	}
}

if(!leutil){ var leutil = {}; }
if(!leutil.ui){ leutil.ui = {}; }
leutil.ui.watermarkHandler = new function(){
	var thisRef = this;
	this.watermarkList = [];
	this.init = function(){
		// will need to be called whenever new watermarks fields are added to the page
		$("span.watermark-field input, .fn-watermark input").each(function(){
			if($(this).data("watermark")!=true){
				thisRef.update($(this));					
				thisRef.watermarkList.push($(this));
			}	
			$(this).bind("focus",function(e){
				$(this).closest('.watermark-field, .fn-watermark').addClass("watermark-field-set");
			});
			$(this).bind("blur",function(e){
				if($.trim($(this).val()) == ""){
					$(this).closest('.watermark-field, .fn-watermark').removeClass("watermark-field-set");
				}
			});	
			$(this).data("watermark",true);
		});
	}
	this.update = function(myField){
		if(!myField){ return null; }
		if(myField.val() != ""){
			myField.closest('.watermark-field, .fn-watermark').addClass("watermark-field-set");
		}
		else{
			myField.closest('.watermark-field, .fn-watermark').removeClass("watermark-field-set");
		}
	}
	this.updateAll = function(){
		for(var i=0; i<this.watermarkList.length; i++){
			this.update(this.watermarkList[i]);
		}
	}
	
	// ie7 hack. CSS that should put the watermark text beneath a transparent input doesn't work, so set click event to put focus to the input
	$("span.watermark-field, .fn-watermark").click(function(){
		$(this).find("input").focus();
	});
}

if(!leutil) var leutil = {}; 
leutil.net = {
	URLExists: function(urlPar) {
		return ($.ajax({type:'HEAD', url:urlPar, async:false}).status == 200);
    }
}

leutil.gomez = {
	nameEvent: function(name){
		if(gomez != null && gomez != undefined && gomez.nameEvent != null && gomez.nameEvent != undefined){
			gomez.nameEvent(name);
		}
	}
}

leutil.string = { 
	// return a string left padded with zeros
    lpad: function(str, length) {  
    	while (str.length < length) {
    		str = '0' + str;
    	}
    	return str;
    },
    trimLeadingZeros : function(srcString) {
		return srcString.replace(/^0*/,"");
	}
};
	
	new function($) {
	    $.fn.getCursorPosition = function() {
	        var pos = 0;
	        var input = $(this).get(0);
	        // IE Support
	        if (document.selection) {
	            input.focus();
	            var sel = document.selection.createRange();
	            var selLen = document.selection.createRange().text.length;
	            sel.moveStart('character', -input.value.length);
	            pos = sel.text.length - selLen;
	        }
	        // Firefox support
	        else if (input.selectionStart || input.selectionStart == '0')
	            pos = input.selectionStart;

	        return pos;
	    }
	} (jQuery);

	
leutil.toogleIds = new (function() {
	this.checkAndToggle = function(prefix, productNumber) {										
		var productPageId  = prefix + productNumber;
		var bkupprefix =  (prefix == "QV_") ? "qv" + productNumber: "pp" + productNumber;

		if ($("#" + productPageId).length > 0) {
			$($("#" + productPageId)[0]).attr("backedup", bkupprefix)
			doToggle($("#" + productPageId)[0]);
		}	
		else if ($("div[backedup=" + bkupprefix + "]").length > 0) {
			doToggle($("div[backedup=" + bkupprefix + "]")[0]);
		}

	}
	
	var doToggle = function(element) {
	  toogleId(element);
	  $(element).children().each(function() {
		  doToggle(this);
	  	}
	  )
	}

	var toogleId = function(element){
		var id = element.id;
		var backupId = element.backupId;
	
		if(id != null && id != undefined && id != "" && id != "null"){
			element.backupId = id;
			element.id = null;
		}else if(backupId != null && backupId != undefined && backupId != "" && backupId != "null"){
			element.backupId = null;
			element.id = backupId;
		}
	
	}
})();
   
var com;
if(com == undefined){
	com = new Object();
}
if(com.landsend == undefined){
	com.landsend = new Object();
}
if(com.landsend.persistentBag == undefined){
	com.landsend.persistentBag = new Object();
}

com.landsend.persistentBag.view = function(){
	
	this.updateBagQuantityNav = function(quantity){
		$("#pBagQ").html(quantity);
	}
}

com.landsend.persistentBag.controller = new function(){
	
	var ns = com.landsend.persistentBag;
	var view = new ns.view();
	var thisRef = this;
	var bagQuantityName = "pBagQ";
	
	var init = function(){
		$(document).ready(thisRef.updateBagDisplay);
	}
	
	this.updateBagDisplay = function(){
		var bagQuantity = $.cookie(bagQuantityName);
		if(bagQuantity == null || bagQuantity == undefined || bagQuantity == 0){
			bagQuantity = "";
		} else {
			bagQuantity = "(" + bagQuantity + ")";
		}
		view.updateBagQuantityNav(bagQuantity);
	}

	init();
}();
var com;
if(com == undefined){
	com = new Object();
}
if(com.landsend == undefined){
	com.landsend = new Object();
}
if(com.landsend.school == undefined){
	com.landsend.school = new Object();
}



com.landsend.school.SchoolLookupService = new function(){
	var thisSchoolLookupService = this;
	var schoolNs = com.landsend.school;
	var schoolSearchController = null;
	var schoolCheckListController = null;
	
	this.launchSchoolSearchDialog = function(){
		var firstTimeLaunch = false;
		if (schoolSearchController == null){
			schoolSearchController = new schoolNs.SchoolSearchController();
			schoolSearchController.init();
			firstTimeLaunch = true;
		} 
		if (schoolCheckListController != null){schoolCheckListController.setRequestActive(false);}
		if (schoolSearchController != null){schoolSearchController.setRequestActive(true);}
		schoolSearchController.launchSchoolSearchDialog(firstTimeLaunch);
	}
	
	this.launchSchoolDressCodeDialog = function(schoolNumber){
		if (schoolCheckListController == null){
			schoolCheckListController = new schoolNs.SchoolCheckListController();
		}
		if (schoolSearchController != null){schoolSearchController.setRequestActive(false);}
		if (schoolCheckListController != null){schoolCheckListController.setRequestActive(true);}		
		schoolCheckListController.getCheckList(schoolNumber);
	}
}();


com.landsend.school.SchoolSearchSelection = function(){
	this.schoolLocation = "USA";
	this.schoolCountry = null;
	this.schoolState = null;	
	this.schoolCity = null;
	this.schoolName = null;
	
	this.preferredSchoolNumber = null;
	
	this.schoolNumberSearchAgain = false;
	
	this.selectedNonCustomSchoolNumber = null;
}


com.landsend.school.SchoolSearchView = function(controller){
	var schoolSearchController = controller;
	var thisSchoolSearchView = this;
	var modal = null;	
	
	var schoolSearchDivContainerId = "SS_SchoolSearchContainer";	
	
	this.injectHtml = function(searchContentHtml){
		if (document.getElementById(schoolSearchDivContainerId)) {
			$("#" + schoolSearchDivContainerId).html("");
		} else {
			$("body").append("<div id = '" + schoolSearchDivContainerId + "' class='school-uniform-modal le-modal-content-hide'></div>");
		}
		$('#' + schoolSearchDivContainerId).append(searchContentHtml);
	}
	
	this.showMe = function(){
		var divIdToShow = $("#" + schoolSearchDivContainerId);
		modal = leutil.ui.modalHandler.show({
			content:divIdToShow,
			cssClass:"school-uniform-modal-wrapper",
			width:570,
			cacheable:true,
			onShow:searchPopupOpenCallback,
			onHide:searchPopupCloseCallback
		});
	}
	
	var searchPopupOpenCallback = function(){	
		schoolSearchController.searchOpened();		
	}
	
	var searchPopupCloseCallback = function(){
		schoolSearchController.searchClosed();
		modal = null;
	}
	
	this.registerEvents = function(){
		$("#schoolRegionSearchTab").live('click', schoolRegionTabSelect);
		$("#schoolNumberSearchTab").live('click', schoolNumberTabSelect);
		$("#locationDD select").live('change', schoolLocationSelect);
		$("#stateDD select").live('change', schoolStateProvinceSelect);
		$('#provinceDD select').live('change', schoolStateProvinceSelect);
		$('#countryDD select').live('change', schoolCountrySelect);
		$('#cityDD select').live('change', schoolCitySelect);
		$("#nameDD input").live('change', schoolNameSelect);
		$('#schoolRegionSearchTabBody').live('submit', findSchoolByRegionButtonSelect);
		
		$('#schoolCode').live('change', schoolNumberSelect);
		$('#schoolNumberSearchTabBody').live('submit', findSchoolByNumberButtonSelect);
		
		//  Search results section events. 		
		$('#schoolResultsSearchAgain').live('click', schoolResultsSearchAgainSelect);
		$('.school-search-results-list input').live('change', schoolSelect);
		$('.school-result-dress-code-link').live('click', showDressCodePdfSelect);
		$('.shopCustomSchool').live('click', shopCustomSchoolSelect);
		$('.shopNonCustomSchool').live('click', shopNonCustomSchoolSelect);
		
		
		//Search success page events.
		$('#shopCustomSchoolSuccessPageClose').live('click', showNonCustomSchoolPage);
	}
	
	
	var schoolRegionTabSelect = function(event){
		schoolSearchController.selectSchoolRegionTab();
		event.preventDefault();
	}
	
	var schoolNumberTabSelect = function(event){
		schoolSearchController.selectSchoolNumberTab();
		event.preventDefault();
	}
	
	var schoolLocationSelect = function(){		
		schoolSearchController.selectSchoolLocation(this.value);	
	}
	
	this.setSchoolLocation = function(schoolLocationValue){
		if (schoolLocationValue == null){
			$("#schoolCountry")[0].selectedIndex = 0;
		} else {
			$("#schoolCountry").val(schoolLocationValue);
		}
		leutil.ui.selectHandler.update($('#schoolCountry'));
	}
	
	var schoolCountrySelect = function(){
		schoolSearchController.selectSchoolCountry((this.selectedIndex > 1 ? this.value : null));
	}
	
	this.setSchoolCountry = function(schoolCountry){
		if (schoolCountry == null){
			$('#selCountry')[0].selectedIndex = 0;
		} else{
			$('#selCountry').val(schoolCountry);
		}
		leutil.ui.selectHandler.update($('#selCountry'));
	}
	
	var schoolCitySelect = function(){
		schoolSearchController.selectSchoolCity((this.selectedIndex > 1 ? this.value : null));
	}
	
	this.setSchoolCity = function(city){
		if (city == null){
			$('#schoolCity')[0].selectedIndex = 0;
		} else {
			$('#schoolCity').val(city);
		}
		leutil.ui.selectHandler.update($('#schoolCity'));
	}
	
	var schoolStateProvinceSelect = function(){
		schoolSearchController.selectSchoolStateProvince((this.selectedIndex > 1 ? this.value : null));
	}
	
	this.setSchoolState = function(state){
		if (state == null){
			$('#schoolState')[0].selectedIndex = 0;
		} else {
			$('#schoolState').val(state);
		}
		leutil.ui.selectHandler.update($('#schoolState'));
	}

	this.setSchoolProvince = function(province){
		if (province == null){
			$('#schoolProvince')[0].selectedIndex = 0;
		} else {
			$('#schoolProvince').val(province);
		}
		leutil.ui.selectHandler.update($('#schoolProvince'));
	}
	
	var schoolNameSelect = function(){
		schoolSearchController.selectSchoolName(this.value);
	}
		
	this.setSchoolName = function(schoolName){
		$('#schoolName').val((schoolName == null ? "" : schoolName));
	}
	
	var schoolNumberSelect = function(){
		schoolSearchController.selectSchoolNumber(this.value);
	}
	
	this.setSchoolNumber = function(schoolNumber){
		$('#schoolCode').val((schoolNumber == null ? "" : schoolNumber));
	}
	
	var findSchoolByRegionButtonSelect = function(event){
		schoolSearchController.processSchoolSearch();
		event.preventDefault();
	}
	
	var findSchoolByNumberButtonSelect = function(event){
		schoolSearchController.processSchoolNumberSearch();
		event.preventDefault();
	}
	
	var schoolResultsSearchAgainSelect = function(event){
		schoolSearchController.selectSchoolResultsSearchAgain();
		event.preventDefault();
	}
	
	var schoolSelect = function(){
		var schoolNumber = this.id.split('_')[1];
		$('div.school-result-options').css('visibility', 'hidden');	
		$('ul.school-search-results-list input').removeAttr("checked");
		
		
		$('#schoolSelect_' + schoolNumber).attr("checked","checked");
		$('#school-result-options-' + schoolNumber).css('visibility', 'visible');
	}
	
	var showDressCodePdfSelect = function(event){
		var schoolCode = this.id.split('_')[4];   //dress_code_pdf_link<%=schools.get(i).getCode()%>
		$.cookie("customSchoolNumber",null,{path: '/'});
		$.cookie("schoolNumber",schoolCode,{path: '/'});
		event.preventDefault();
		window.open("/pdfs/school/"+schoolCode+".pdf");
	}
	
	var shopCustomSchoolSelect = function(event){
		schoolSearchController.selectShopCustomSchool();		
		// We do not want to prevent the default behaviour here, becuase the link behind the button should take the user to the
		// index page for the custom school.
	}
	
	var shopNonCustomSchoolSelect = function(event){
		var schoolNumber = this.id.split('_')[2];
		var schoolName = $('#school_name_' + schoolNumber).html();
		$('#SS_SchoolSearchCriteria').hide();
		$('#SS_SchoolSearchResults').hide();
		$('#SS_SchoolSuccess').show();
		schoolSearchController.selectShopNonCustomSchool(schoolNumber, schoolName);
		event.preventDefault();
	}
	
	
	var showNonCustomSchoolPage = function(event){
		var customSchoolStoreNum = $.cookie("customSchoolNumber");
		schoolSearchController.showNonCustomSchoolPage();
		if(customSchoolStoreNum == null) {	
			leutil.ui.modalHandler.hide(modal);
		}
	}
	
	this.showSearchCriteria = function(){	
		$('#SS_SchoolSearchCriteria').show();
		$('#SS_SchoolSuccess').hide();
		$('#SS_SchoolSearchResults').hide();
		$('#SS_SchoolSearchResults').children().remove();		
		if(modal && modal.trigger){
			modal.trigger("update");
		}
	}
	
	this.showResults = function(responseHtml){
		$('#SS_SchoolSearchResults').children().remove();
		$('#SS_SchoolSearchResults').append(responseHtml);

		// Add code to activate the dress code pdf link.
		$('.school-result-dress-code-link').each(showDressCodeLinkIfExists);
	 
		$('#SS_SchoolSearchResults').show();        
	       
		$('#SS_SchoolSearchCriteria').hide();
		$('#SS_SchoolSuccess').hide();

	} 
	
	var showDressCodeLinkIfExists = function(){
		var idParts = this.id.split('_');
		var schoolNumber = idParts[4];
		if (URLExists("/pdfs/school/" + schoolNumber + ".pdf")){
			$('#dress_code_' + schoolNumber).css('display', 'block');	
			$('#please_call_' + schoolNumber).css('display', 'none');
		} else {
			$('#dress_code_' + schoolNumber).css('display', 'none');
			$('#please_call_' + schoolNumber).css('display', 'block');
		}
	}
	
	this.loadCities = function(data, cityName) {
		doDebug("loadCities");
		var schoolState = $("#schoolCity")[0];
		schoolState.length = 2;
		if (data !== null && typeof data == 'object') {
			
			for (var i=0; i<data.length; i++) {
				var el = document.createElement("option");
				schoolState.appendChild(el);
				el.value = data[i];
	           	el.text = data[i];
	           	if (data[i] == cityName) {
	           		el.selected = true;
	           	}
			}		
		}
	}
	
	
	var displayErrorMsg = function(errorMsg){
		if(errorMsg){
			var button = $("#findSchoolByRegionButton");
			if($("#schoolNumberSearchTabBody").css("display")=="block"){
				button = $("#findSchoolByNumberButton");
			}
			leutil.ui.tooltipHandler.show({
				text: errorMsg,
				button: button,
				type: "error"
			});
			
			button.unbind(".tooltipOut").bind("mouseout.tooltipOut", function(e){
				$(this).unbind(".tooltipOut");
				leutil.ui.tooltipHandler.hide(button);
			});
			
			// hide tooltip on timeout as well as button mouseout in case of submit through enter key
			setTimeout(function(){
				leutil.ui.tooltipHandler.hide(button);
			}, 	10000);
		}
	}
	
	this.displayStateError = function(errMsg){
		$("#stateDD").addClass("school-field-error");
		$("#cityDD, #nameDD, #provinceDD, #countryDD, #schoolCodeDD").removeClass("school-field-error");
		displayErrorMsg(errMsg.text);
	}
		
	this.displayProvinceError = function(errMsg){
		$("#provinceDD").addClass("school-field-error");
		$("#cityDD, #nameDD, #stateDD, #countryDD, #schoolCodeDD").removeClass("school-field-error");
		displayErrorMsg(errMsg.text); 
	}
	
	this.displayCountryError = function(errMsg){
		$("#countryDD").addClass("school-field-error");
		$("#cityDD, #nameDD, #provinceDD, #stateDD, #schoolCodeDD").removeClass("school-field-error");
		displayErrorMsg(errMsg.text);
	}
	
	this.displayNameError = function(errMsg){		
		$("#nameDD").addClass("school-field-error");
		$("#cityDD, #stateDD, #provinceDD, #countryDD, #schoolCodeDD").removeClass("school-field-error");
		displayErrorMsg(errMsg.text);
	}
	
	this.displaySchoolNumberError = function(errMsg){
		$('#schoolCodeDD').addClass("school-field-error");
		displayErrorMsg(errMsg.text);
	}
	
	this.hideErrLblAndMessages = function() {
		$("#nameDD, #cityDD, #stateDD, #provinceDD, #countryDD, #schoolCodeDD").removeClass("school-field-error");
		leutil.ui.tooltipHandler.hide($("#findSchoolByRegionButton"));
	}
	
	this.showRegionSearchTab = function(){
		$("#schoolRegionSearchTab").addClass("selected");
		$("#schoolRegionSearchTabBody").css("display","block");
		$("#schoolSearchTitle")
			.html("Search by School Name")
			.addClass("school-search-by-name-title")
			.removeClass("school-search-by-number-title");
		
	}
	
	this.hideRegionSearchTab = function(){
		$("#schoolRegionSearchTab").removeClass("selected");
		$("#schoolRegionSearchTabBody").css("display","none");
	}
	
	this.showSchoolNumberSearchTab = function(){
		$("#schoolNumberSearchTab").addClass("selected");
		$("#schoolNumberSearchTabBody").css("display","block");
		$("#schoolSearchTitle")
			.html("Search by School Number")
			.addClass("school-search-by-number-title")
			.removeClass("school-search-by-name-title");
	}
	
	this.hideSchoolNumberSearchTab = function(){
		$("#schoolNumberSearchTab").removeClass("selected");
		$("#schoolNumberSearchTabBody").css("display","none");
	}
	
	this.showState = function(enabled){
		$("#stateDD").css("display","block");
		if(!enabled){
			$("#stateDD select").attr("disabled","disabled");
		}
		else{
			$("#stateDD select").removeAttr("disabled");
		}
		leutil.ui.selectHandler.update($("#stateDD select"));
	}
	
	this.hideState = function(){
		$("#stateDD").css("display","none");
	}
	
	this.showProvince = function(enabled){
		$("#provinceDD").css("display","block");
		if(!enabled){
			$("#provinceDD select").attr("disabled","disabled");
		}
		else{
			$("#provinceDD select").removeAttr("disabled");
		}
		leutil.ui.selectHandler.update($("#provinceDD select"));
	}
	
	this.hideProvince = function(){
		$("#provinceDD").css("display","none");
	}
	
	this.showCountry = function(enabled){
		$("#countryDD").css("display","block");
		if(!enabled){
			$("#countryDD select").attr("disabled","disabled");
		}
		else{
			$("#countryDD select").removeAttr("disabled");
		}
		leutil.ui.selectHandler.update($("#countryDD select"));
	}
	
	this.hideCountry = function(){
		$("#countryDD").css("display","none");
	}
	
	this.showCity = function(enabled){
		$("#cityDD").css("display","block");
		if(!enabled){
			$("#cityDD select").attr("disabled","disabled");
		}
		else{
			$("#cityDD select").removeAttr("disabled");
		}
		leutil.ui.selectHandler.update($("#cityDD select"));
	}
	
	this.hideCity = function(){
		$("#cityDD").css("display","none");
	}
	
	this.emptyCityDroplist = function(){
		$("#cityDD select").html('<option value="empty" selected>Select One (optional)</option>' +
			'<option value="">----------------</option>');
	}
	
	this.disableSchoolName = function() {
		$("#nameDD input").attr("disabled","disabled");
		$("#nameDD").addClass("school-field-disabled");
	}

	this.enableSchoolName = function() {
		$("#nameDD input").removeAttr("disabled");
		$("#nameDD").removeClass("school-field-disabled");
	}
}

com.landsend.school.SchoolSearchController = function(){
	var thisSchoolSearchController = this;
	var schoolSearchView = null;
	var schoolSearchSelection = null;
	var currentSearchTab = null;   //Either RegionTab or NumberTab
	var isRequestActive = false;
	
	var selectedNonCustomSchool = null;
	
	this.init = function(){
		schoolSearchSelection = new com.landsend.school.SchoolSearchSelection();
		schoolSearchView = new com.landsend.school.SchoolSearchView(this);
		registerEvents();
	}
	
	this.setRequestActive = function(isActive){
		isRequestActive = isActive;
	}	
	
	this.launchSchoolSearchDialog = function(firstTimeLaunch){
		if (firstTimeLaunch){
			$.ajax({
				   async:true,
				   url: "/pp/SchoolSearch.html",
				   success:handleSchoolSearchHtmlResponse,
				   error:handleSchoolSearchHtmlError,
				   timeout:10000
				 });
		} else {
			schoolSearchView.showMe();
		}	
		return false;
		
	}
	
	var handleSchoolSearchHtmlResponse = function(schoolSearchHtml){
		if (isRequestActive){
			schoolSearchView.injectHtml(schoolSearchHtml);
			schoolSearchView.showMe();
		}
	}
	
	var handleSchoolSearchHtmlError = function(){
		if(isRequestActive){
			var errorHtml = 		'<div style="backgorund-color:#D6E1EB">';
			errorHtml = errorHtml + "There was an error retrieving the school search popup.";		
			errorHtml = errorHtml + "For immediate assistance, please call 1-800-963-4816.";
			errorHtml = errorHtml + "</div>"
			schoolSearchView.injectHtml(errorHtml);
			schoolSearchView.showMe();
		}
	}
	
	var registerEvents = function(){
		schoolSearchView.registerEvents();
	}
	
	this.searchOpened = function(){
		currentSearchTab = null;
		this.selectSchoolRegionTab();
		this.resetRegionTab();
		this.resetSchoolNumberTab();
		selectedNonCustomSchool = null;
	}
	
	this.searchClosed = function(){
		currentSearchTab = "RegionTab";
		this.selectSchoolRegionTab();
		this.resetRegionTab();
		this.resetSchoolNumberTab();
		if (selectedNonCustomSchool != null) {
			this.showNonCustomSchoolPage();
		}
		selectedNonCustomSchool = null;
	}
	
	this.selectShopCustomSchool = function(){
		var schoolNumber = this.id.split('_')[2];
		$.cookie("schoolNumber",null,{path: '/'});
		$.cookie("customSchoolNumber",schoolNumber,{path: '/'});
	}
	
	this.selectShopNonCustomSchool = function(schoolNumber, schoolName){
		selectedNonCustomSchool = schoolNumber;
		this.schoolWebAnalyticsController.sendShopSchoolEvent(schoolNumber, schoolName);
	}
	
	this.showNonCustomSchoolPage = function(){ 
		var customSchoolStoreNum = $.cookie("customSchoolNumber");
		$.cookie("customSchoolNumber",null,{path: '/'});
		$.cookie("schoolNumber",selectedNonCustomSchool,{path: '/'});
		if(customSchoolStoreNum != null) {			
			var fullUrl = window.location.href;
			var param = "schoolStoreNum";
			var regex=eval("/&?"+param+"=[^&]+/");
			fullUrl = fullUrl.replace(regex, "");
			window.location = fullUrl;
		} else {
			try {
				var buyGrids = com.landsend.productView.GlobalManager.getStandardBuyGrids();
				for(var y = 0;y < buyGrids.length; y++){
					buyGrids[y].valueAddedServicesController.schoolUniformController.selectFindSchool(selectedNonCustomSchool);
				}
			} catch (e) {
			}
		}
		selectedNonCustomSchool = null;
	}
	
	
	this.resetRegionTab = function(){
		schoolSearchSelection.schoolLocation = "USA";
		schoolSearchSelection.schoolCountry = null;
		schoolSearchSelection.schoolState = null;	
		schoolSearchSelection.schoolCity = null;
		schoolSearchSelection.schoolName = null;	
		schoolSearchSelection.schoolNumberSearchAgain = false;
		this.selectSchoolLocation(schoolSearchSelection.schoolLocation);
	}
	
	this.resetSchoolNumberTab = function(){
		schoolSearchSelection.preferredSchoolNumber = null;
		schoolSearchSelection.schoolNumberSearchAgain = false;
		this.selectSchoolNumber(schoolSearchSelection.preferredSchoolNumber);
	}
	
	this.selectSchoolResultsSearchAgain = function(){
		if (currentSearchTab == "RegionTab"){
			this.schoolWebAnalyticsController.sendSchoolNameSearchEvent(schoolSearchSelection.schoolNumberSearchAgain);
		} else {
			this.schoolWebAnalyticsController.sendSchoolNumberSearchEvent(schoolSearchSelection.schoolNumberSearchAgain);
		}		
		schoolSearchView.showSearchCriteria();
		schoolSearchSelection.schoolName = null;
		schoolSearchSelection.preferredSchoolNumber = null;
		schoolSearchView.setSchoolNumber(schoolSearchSelection.preferredSchoolNumber);			
		schoolSearchView.setSchoolName(schoolSearchSelection.schoolName);
	}	

	this.selectSchoolRegionTab = function(){
		schoolSearchView.hideErrLblAndMessages();
		schoolSearchView.showSearchCriteria();
		schoolSearchView.showRegionSearchTab();
		schoolSearchView.hideSchoolNumberSearchTab();
		if (currentSearchTab == null || currentSearchTab != "RegionTab"){ //If not clicking on the same tab again and again		
			if (schoolSearchSelection.schoolNumberSearchAgain){
				this.resetRegionTab();
			}
			this.schoolWebAnalyticsController.sendSchoolNameSearchEvent(schoolSearchSelection.schoolNumberSearchAgain);
		}
		currentSearchTab = "RegionTab";
	}
	
	
	this.selectSchoolNumberTab = function(){		
		schoolSearchView.hideErrLblAndMessages();
		schoolSearchView.showSearchCriteria();
		schoolSearchView.hideRegionSearchTab();
		schoolSearchView.showSchoolNumberSearchTab();
		if (currentSearchTab == null || currentSearchTab != "NumberTab"){ //If not clicking on the same tab again and again
			if (schoolSearchSelection.schoolNumberSearchAgain){
				this.resetSchoolNumberTab();
			}
			this.schoolWebAnalyticsController.sendSchoolNumberSearchEvent(schoolSearchSelection.schoolNumberSearchAgain);
		}
		currentSearchTab = "NumberTab";	
	}
	
	
	this.selectSchoolLocation = function(location){
		if (location != schoolSearchSelection.schoolLocation){
			schoolSearchView.hideErrLblAndMessages();			
		}
		schoolSearchView.setSchoolLocation(location);
		
		if (location == "USA"){
			schoolSearchSelection.schoolLocation = "USA";
			schoolSearchSelection.schoolCountry = "USA";
			schoolSearchView.showState(true); 
			schoolSearchView.hideProvince(); 
			schoolSearchView.hideCountry();
			schoolSearchView.showCity(false);
			schoolSearchView.disableSchoolName();
		} else if (location == "CAN") {
			schoolSearchSelection.schoolLocation = "CAN";
			schoolSearchSelection.schoolCountry = "CAN";
			schoolSearchView.hideCountry();
			schoolSearchView.hideState();
			schoolSearchView.showProvince(true);
			schoolSearchView.showCity(false);
			schoolSearchView.disableSchoolName();
		} else {
			schoolSearchSelection.schoolLocation = "INTL";
			schoolSearchSelection.schoolCountry = null;
			schoolSearchView.hideState();
			schoolSearchView.hideProvince();
			schoolSearchView.showCountry(true); 
			schoolSearchView.hideCity();
			schoolSearchView.disableSchoolName();
		}
		schoolSearchSelection.schoolState = null;
		schoolSearchSelection.schoolProvince = null;
		schoolSearchSelection.schoolCity = null;
		schoolSearchSelection.schoolName = null;
		
		schoolSearchView.setSchoolCountry(schoolSearchSelection.schoolCountry);
		schoolSearchView.setSchoolState(schoolSearchSelection.schoolState);
		schoolSearchView.setSchoolProvince(schoolSearchSelection.schoolProvince);
		schoolSearchView.setSchoolCity(schoolSearchSelection.schoolCity);
		schoolSearchView.setSchoolName(schoolSearchSelection.schoolName);
	}
	
	this.selectSchoolCountry = function(country){
		if (country != schoolSearchSelection.schoolCountry){
			schoolSearchView.hideErrLblAndMessages();
		}
		schoolSearchSelection.schoolCountry = country;
		
		schoolSearchView.setSchoolCountry(country);
		
		schoolSearchSelection.schoolState = null;
		schoolSearchSelection.schoolCity = null;
		schoolSearchSelection.schoolName = null;
		
		if (country == null){
			schoolSearchView.disableSchoolName();
		} else { 
			schoolSearchView.enableSchoolName();
		}
		schoolSearchView.setSchoolName(schoolSearchSelection.schoolName);
	}
	
	this.selectSchoolStateProvince = function(state){
		if (state != schoolSearchSelection.schoolState){
			schoolSearchView.hideErrLblAndMessages();
		}
		if (schoolSearchSelection.schoolLocation == "USA"){
			schoolSearchView.setSchoolState(state);
		} else if (schoolSearchSelection.schoolLocation == "CAN"){
			schoolSearchView.setSchoolProvince(state);
		}
		schoolSearchView.setSchoolCity(null);
		//schoolSearchView.setSchoolName(null);
		schoolSearchSelection.schoolState = state;
		schoolSearchSelection.schoolCity = null;
		//schoolSearchSelection.schoolName = null;
		
		if (state == null){
			schoolSearchView.showCity(false);
			schoolSearchView.disableSchoolName();
		} else {
			schoolSearchView.emptyCityDroplist();
			schoolSearchView.showCity(true);
			schoolSearchView.enableSchoolName();
			JSchoolFacade.loadAvailableSchoolCities(schoolSearchSelection.schoolLocation, state, {
				callback:loadCities,
				timeout:10000,
				errorHandler: function(msg){doDebug("crap:"+msg)}
			});
		}
	}
	
	this.selectSchoolCity = function(city){
		if (city != schoolSearchSelection.schoolCity){schoolSearchView.hideErrLblAndMessages();}
		schoolSearchView.setSchoolCity(city);
		//schoolSearchView.setSchoolName(null);
		schoolSearchSelection.schoolCity = city;
		//schoolSearchSelection.schoolName = null;
		schoolSearchView.enableSchoolName();
	}
	
	this.selectSchoolName = function(schoolName){
		if (schoolName != schoolSearchSelection.schoolName){schoolSearchView.hideErrLblAndMessages();}
		schoolSearchSelection.schoolName = schoolName;
		schoolSearchView.setSchoolName(schoolName);
	}
	
	this.selectSchoolNumber = function(schoolNumber){
		if (schoolNumber != schoolSearchSelection.preferredSchoolNumber){schoolSearchView.hideErrLblAndMessages();}
		schoolSearchSelection.preferredSchoolNumber = $.trim(schoolNumber);
		schoolSearchView.setSchoolNumber(schoolNumber);
	}
	
	var loadCities = function(data){
		schoolSearchView.loadCities(data, schoolSearchSelection.schoolCity);
	}
	
	var validateSchoolSearch = function(){
		var validCriteriaEntered = true;
		schoolSearchView.hideErrLblAndMessages();
		
		if (schoolSearchSelection.schoolLocation == "USA"){
			if (schoolSearchSelection.schoolState == null || schoolSearchSelection.schoolState == undefined){
				validCriteriaEntered = false;
				schoolSearchView.displayStateError(com.landsend.school.SchoolSearchMessages.findMessage(0));
			}
		} else if (schoolSearchSelection.schoolLocation == "CAN"){
			if (schoolSearchSelection.schoolState == null || schoolSearchSelection.schoolState == undefined){
				validCriteriaEntered = false;
				schoolSearchView.displayProvinceError(com.landsend.school.SchoolSearchMessages.findMessage(1));
			}
		} else if (schoolSearchSelection.schoolLocation == "INTL"){
			if (schoolSearchSelection.schoolCountry == null || schoolSearchSelection.schoolCountry == undefined){
				validCriteriaEntered = false;
				schoolSearchView.displayCountryError(com.landsend.school.SchoolSearchMessages.findMessage(2));
			}
		}
		
		if (validCriteriaEntered == true){
			var nameExp = /^([a-zA-Z0-9\s.]+)$/ ;
			var numExp = /[0-9]+/;
			if (schoolSearchSelection.schoolName != "" && schoolSearchSelection.schoolName != null && schoolSearchSelection.schoolName != undefined && !nameExp.test(schoolSearchSelection.schoolName)) {
				validCriteriaEntered = false;
				schoolSearchView.displayNameError(com.landsend.school.SchoolSearchMessages.findMessage(3));				
			}
		}
		return validCriteriaEntered;
	}
	
	
	this.processSchoolSearch = function(){
		//Run through the validation logic
		var validCriteriaEntered = validateSchoolSearch();
		if (validCriteriaEntered){
			//DWREngine.setAsync(false);
			//First check the number of schools that match this criteria.
			var lCountry = (schoolSearchSelection.schoolLocation == "INTL" ? schoolSearchSelection.schoolCountry :  schoolSearchSelection.schoolLocation);
			var lState = schoolSearchSelection.schoolState == null? "" : schoolSearchSelection.schoolState;
			var lName = (schoolSearchSelection.schoolName == null ? "" : schoolSearchSelection.schoolName);
			var lCity = (schoolSearchSelection.schoolCity == null || schoolSearchSelection.schoolCity == "" ? "empty" : schoolSearchSelection.schoolCity);
			
			JSchoolFacade.loadMatchingSchoolPrograms(lName, lCountry, lState, lCity, {
				callback:numSchoolsCallback,
				timeout:10000,
				errorHandler: schoolSearchResultsError
			});	
		}
	}
	
	var validateSchoolNumberSearchCriteria = function() {
		var valid = false;
		var numExp = /[0-9]{9}|[0-9]{10}/;

		if(numExp.test(schoolSearchSelection.preferredSchoolNumber) == true) {
			valid = true;
		} else {
			valid = false;
			schoolSearchView.displaySchoolNumberError(com.landsend.school.SchoolSearchMessages.findMessage(6));
		}
		return valid;
	}
	
	
	this.processSchoolNumberSearch = function(){
		var validCriteriaEntered = validateSchoolNumberSearchCriteria();
		if (validCriteriaEntered){
		    var schoolID = schoolSearchSelection.preferredSchoolNumber.substring(0,schoolSearchSelection.preferredSchoolNumber.length-1);
		    var checkDigit = schoolSearchSelection.preferredSchoolNumber.substring(schoolSearchSelection.preferredSchoolNumber.length-1);
		       JSchoolFacade.findSchoolBySchoolNumber(schoolID, checkDigit,{
		    		callback:schoolNumberSearchResultsResponse,
		    		timeout:10000,
		    		errorHandler: schoolSearchResultsError
		    	});	
		}
	}
	
	
	var schoolNumberSearchResultsResponse = function(request){
		var errorMsg = "";
		var schoolCode = $("#schoolCode")[0].value;
		
	    if (request !== null && typeof request == "object") {
	    	var resultsURL = "/pp/SchoolSearch.html?action=doSearchBySchoolNumber&schoolStoreNum="+schoolCode;
	    	$.ajax({
				   async:false,
				   url: resultsURL,
				   success:schoolSearchResultsResponse,
				   error:schoolSearchResultsError,
				   timeout:10000
				 });	    	
		} else {
			schoolSearchView.displaySchoolNumberError(com.landsend.school.SchoolSearchMessages.findMessage(6));
	    }
		return;
	}
	
	var numSchoolsCallback = function(data){
		var numSchoolResults = data.length;
		
		if (numSchoolResults < 1) {
			schoolSearchView.displayNameError(com.landsend.school.SchoolSearchMessages.findMessage(4));
			thisSchoolSearchController.schoolWebAnalyticsController.sendSchoolSearchResultsEvent(false);
		valid = false;
		} else if (numSchoolResults > 41) {
			schoolSearchView.displayNameError(com.landsend.school.SchoolSearchMessages.findMessage(5));
		} else {
			//Now we can go retrieve the results for the search criteria.
			var lCountry = (schoolSearchSelection.schoolLocation == "INTL" ? schoolSearchSelection.schoolCountry :  schoolSearchSelection.schoolLocation);
			var lState = schoolSearchSelection.schoolState == null? "" : schoolSearchSelection.schoolState;
			var lName = (schoolSearchSelection.schoolName == null ? "" : schoolSearchSelection.schoolName);
			var lCity = (schoolSearchSelection.schoolCity == null || schoolSearchSelection.schoolCity == "" ? "empty" : schoolSearchSelection.schoolCity);
			var resultsURL = "/pp/SchoolSearch.html?action=doSearch&countryCode="+lCountry+"&stateCode="+lState+"&cityName="+lCity+"&schoolName="+lName;
			$.ajax({
				   async:false,
				   url: resultsURL,
				   success:schoolSearchResultsResponse,
				   error:schoolSearchResultsError,
				   timeout:10000
				 });
		}
	}
	
	var schoolSearchResultsResponse = function(responseHtml){
	    schoolSearchSelection.schoolNumberSearchAgain = true;
		schoolSearchView.showResults(responseHtml);
		thisSchoolSearchController.schoolWebAnalyticsController.sendSchoolSearchResultsEvent(true);
	}	
	
	var schoolSearchResultsError = function(){
		var errorHtml = '<div style="backgorund-color:#D6E1EB" id="SS_SchoolSearchResults">';
		errorHtml = errorHtml + "There was an error retrieving the school results. Please ";		
		errorHtml = errorHtml + '<a href="#" id="schoolResultsSearchAgain">Search Again</a>';
		errorHtml = errorHtml + "and verify that you've entered your full school name correctly. Or, for immediate assistance, please call 1-800-963-4816.";
		errorHtml = errorHtml + "</div>"			
		schoolSearchView.showResults(errorHtml);		
	}
	
	this.schoolWebAnalyticsController = new function(){
		
		var s_overlayomtr;		
		
		var getNewOmnitureObj = function(){
			s_overlayomtr =s_gi(s_account);
			
			/************************** CONFIG SECTION **************************/
			/* You may add or alter any code config here. */
			s_overlayomtr.charSet="ISO-8859-1"
			/* Conversion Config */
			s_overlayomtr.currencyCode="USD"
			/* Link Tracking Config */
			s_overlayomtr.trackDownloadLinks=true
			s_overlayomtr.trackExternalLinks=true
			s_overlayomtr.trackInlineStats=true
			s_overlayomtr.linkDownloadFileTypes="exe,zip,wav,mp3,mov,mpg,avi,wmv,doc,pdf,xls"
			s_overlayomtr.linkInternalFilters="javascript:,lenet,levdr.mvm.com,leinternal.com,leusdv01,landsend.com,localhost,wwwqa,mvm.com"
			s_overlayomtr.linkLeaveQueryString=false
			s_overlayomtr.linkTrackVars="None"
			s_overlayomtr.linkTrackEvents="None"			
			
			s_overlayomtr.products="";
			s_overlayomtr.events="";
			s_overlayomtr.eVar21="";
			s_overlayomtr.channel="00013";
		}
		
		this.sendSchoolNameSearchEvent = function(searchAgain){
			getNewOmnitureObj();
			if (searchAgain){
				s_overlayomtr.pageName="Preferred School Number Search Again";
			} else {
				s_overlayomtr.pageName="Preferred School Number Search by Name";
			}
			s_overlayomtr.t();
		}
		
		this.sendSchoolNumberSearchEvent = function(searchAgain){
			getNewOmnitureObj();
			if (searchAgain){
				s_overlayomtr.pageName="Preferred School Number Search Again";
			} else {
				s_overlayomtr.pageName="Preferred School Number Search by Number";
			}
			s_overlayomtr.t();
		}
		
		this.sendSchoolSearchResultsEvent =function(resultsFound){
			getNewOmnitureObj();
			if (resultsFound){				
				s_overlayomtr.pageName="Preferred School Number Search Results";
			} else {
				s_overlayomtr.pageName="Preferred School Number Search No Results";
			}
			s_overlayomtr.t();
		}
		
		this.sendShopSchoolEvent =function(schoolNumber, schoolName){
			getNewOmnitureObj();
			s_overlayomtr.pageName="Preferred School Number Applied - General";
			s_overlayomtr.eVar21 = schoolNumber + "_" + schoolName;
			s_overlayomtr.t();
		}
	}	
}

com.landsend.school.SchoolSearchMessages = new function(){
	var Message = function(id,type,text, errorID){
		this.id = id;
		this.text = text;
		this.type = type; // 1 = error, 2 = warning, 3 = message
		this.errorID = errorID;
	}
	var message = new Array();
	message[0] = new Message(0,1,"Please select a state.", "stateError");
	message[1] = new Message(1,1,"Please select a province.", "stateError");
	message[2] = new Message(2,1, "Please select a country.", "stateError");
	message[3] = new Message(3,1, "Invalid characters. Please use only alpha/numeric characters.", "schoolNameError");
	message[4] = new Message(4,1, "No matching schools found.", "schoolNameError");
	message[5] = new Message(5,1, "Multiple schools found. To refine your search, please be as specific as possible.", "schoolNameError");
	message[6] = new Message(6,1, "The Preferred School Number is incorrect or invalid. Please verify it and re-enter or call 1-800-963-4816 for assistance.", "schoolCodeError"); 

	this.findMessage = function(id){
		var messageLu = message[id];
		if(messageLu != null || messageLu != undefined){
			return new Message(messageLu.id,messageLu.type,messageLu.text, messageLu.errorID);
		}
		return null;
	}
}


com.landsend.school.SchoolCheckListView = function() {
	var thisRef = this;
	var modal;
	this.show = function() {
		modal = leutil.ui.modalHandler.show({
			content:"QV_SchoolCheckList",
			cssClass:"school-uniform-modal-wrapper",
			width:660,
			cacheable:false,
			onShow:thisRef.registerEvents,
			onHide:thisRef.unregisterEvents
		});
	}
	
	this.injectHtml = function(html) {
		if ($("#QV_SchoolCheckList").length < 1) {
			var theHtml = "<div id='QV_SchoolCheckList' class='le-modal-content-hide'>" + html + "</div>";
			$("body").append(theHtml);
		}		
		else {
			$("#QV_SchoolCheckList").html(html);
		}
	}
	
	this.registerEvents = function(){
		modal.find("ul.school-uniform-list-menu a").bind("click",function(e){
			var target = $($(this).attr("href").substring($(this).attr("href").lastIndexOf("#"))); //ie7 returns full url string, not hash
			$(this).parents("ul.school-uniform-list-menu").find("a").removeClass("selected");
			$(this).addClass("selected");
			
			if(target.length>0){
				var top = target.position().top;
				modal.find("div.le-modal-content-scrollpane").animate({scrollTop:top},"fast");				
			}
			e.preventDefault();
		});
	}
	
	this.unregisterEvents = function(){
		modal.find("ul.school-uniform-list-menu a").unbind('click');
	}
}


com.landsend.school.SchoolCheckListController = function(){
	
	var checkListView = new com.landsend.school.SchoolCheckListView();
	var isRequestActive = false;
	
	
	this.setRequestActive = function(isActive){
		isRequestActive = isActive;
	}
	
	this.getCheckList = function(schoolNumber) {
		var requestURL = "/pp/SchoolChecklist.html?schoolStoreNum="+schoolNumber;
		 $.ajax({
			   async:true,
			   url: requestURL,
			   success:parseResponse,
			   error:handleError,
			   timeout:60000
			 });
	}
	
	var parseResponse = function(html) {	
		if (isRequestActive){
			checkListView.injectHtml(html);
			if($.browser.msie) { $('body').find('.print a').attr('onclick','').click(function(e){
				e.preventDefault();
				var mywindow = window.open('', '', 'height=400,width=600');				
				mywindow.document.write('<html><head><title></title></head><body >' + html + '</body></html>');      
				mywindow.document.close();      
				mywindow.print();  
				mywindow.close();    
				return true;});
			}
			checkListView.show();
		}
	}
	
	var handleError = function(msg) {
		if (isRequestActive){
			var errorHtml = 		'<div style="backgorund-color:#D6E1EB">';
			errorHtml = errorHtml + "<p>There was an error retrieving the dress code products for this school.</p>";
			errorHtml = errorHtml + "<p>Error is " + msg.statusText + "</p>";
			errorHtml = errorHtml + "<p>For immediate assistance, please call 1-800-963-4816.</p>";
			errorHtml = errorHtml + "</div>"			
			checkListView.injectHtml(errorHtml);
			checkListView.show();
		}
	}
}

