/** GLOBALS **/
if(!Array.indexOf){
    Array.prototype.indexOf = function(obj){
        for(var i=0; i<this.length; i++){
            if(this[i]==obj){
                return i;
            }
        }
        return -1;
    }
}
if(!Array.indexOfObject){
    Array.prototype.indexOfObject = function(obj, key){
    	var myObj = {};
    	myObj[key] = obj;
        for(var i=0; i<this.length; i++){
            if(this[i][key] === myObj[key]){
                return i;
            }
        }
        return -1;
    }
}
if(!Array.getObjectFromArray){
    Array.prototype.getObjectFromArray = function(obj, key){
    	var myObj = {};
    	myObj[key] = obj;
        for(var i=0; i<this.length; i++){
            if(this[i][key] === myObj[key]){
                return this[i];
            }
        }
        return -1;
    }
}

var logger = (function(){
	var _location = document.location.hostname.toLowerCase();
	var _canLog = (window.console) ? true : false;
	var _enabled = (_location.indexOf('qa.saksdirect') > -1 || _location.indexOf('preview.saksdirect') > -1 || _location.indexOf('devslot1.saksdirect.com') > -1 ) ? true : false;
	var _testing = (document.location.pathname.toLowerCase().indexOf('globalspecrunner.html') > -1) ? true : false;
	return {
		log : function(value){
			if(_canLog && (_enabled || _testing) )
				console.log(value);
		}
	};
})();

var sksGlobalAjax = (function($){
	var _requesting = false;
	
	var _defaultErrorHandler = function(response){
		logger.log('--- DEFAULT ERROR HANDLER ---');
		logger.log(response);
	};
	var _defaultCompleteHandler = function(jqXHR, textStatus){
		logger.log('--- DEFAULT COMPLETE HANDLER ---');
		_requesting = false;
	};
	
	var _saksAjax = function( _dataObject ) {
		if(!_requesting){
			_requesting = true;
	        $.ajax({
	            url : _dataObject.url,
	            type : _dataObject.type || 'GET',
	            dataType : _dataObject.dataType || 'json',
	            data : _dataObject.data,
	            success : _dataObject.success,
	            complete : (_dataObject.complete) ? function(){
	        		_dataObject.complete();
	        		_defaultCompleteHandler(); } : _defaultCompleteHandler,
	            error : _dataObject.error || _defaultErrorHandler
	        });
		}
    };
    
    return {
    	ajaxRequest : _saksAjax,
    	resetRequesting : function(){_requesting = false}
    };
})(jQuery);

/* shopping cart Item Count */
function loadNumItems() {
	var cookieName = 'saksBagNumberOfItems';
	var numItemCount = 'numItemsLink';

	var cookieValue = null;
	if (document.cookie && document.cookie != '') {
		var cookies = document.cookie.split(';');
		for ( var i = 0; i < cookies.length; i++) {
			var cookie = (cookies[i] || "").replace(/^\s+|\s+$/g, "");
			if (cookie.substring(0, cookieName.length + 1) == (cookieName + '=')) {
				cookieValue = decodeURIComponent(cookie
						.substring(cookieName.length + 1));
				break;
			}
		}
	}

	if (null == cookieValue) {
		date = new Date();
		date.setTime(date.getTime() + (365 * 24 * 60 * 60 * 1000));
		document.cookie = cookieName + "=0; expires=" + date.toUTCString()
				+ "; path=/";
		cookieValue = "0";
	}
	
	var theSamePageEl = document.getElementById(numItemCount);
	var itemNumbersElement = theSamePageEl != null ? theSamePageEl : parent.document.getElementById(numItemCount);
	itemNumbersElement.innerHTML = cookieValue + (cookieValue == 1 ? ' item' :' items');
}

/* top nav utils */
//used to get the site real estate (sre) queryParam 
function getRealEstate(queryKey) { 
    var value = null;
    var url = window.location.href;
    var queryParams = urlToQueryParam(url);
  
    if (queryParams != null){
        value = queryParams[queryKey];
	  }
  
    if (value == null || value === undefined)
        value = "";
  
    value = value.split('#')[0];
  return value;
}

function urlToQueryParam (input){
	var _params = {};
	if (input.indexOf('?') > -1)
		input = input.substring(input.indexOf('?') + 1);
 
	var e,
		a = /\+/g, 
		r = /([^&;=]+)=?([^&;]*)/g,
		d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
		q = input;
	while (e = r.exec(q))
		_params[d(e[1])] = d(e[2]);
    
	return _params;
}
// creates a cookie
function createCookie(name,value,days) 
{
    if (days) 
    {
		      var date = new Date();
				  date.setTime(date.getTime()+(days*24*60*60*1000));
				  var expires = "; expires="+date.toGMTString();
		  }
		  else var expires = "";
	    document.cookie = name+"="+value+expires+"; path=/";
}
			
// Gets and returns a cookie by name.	
function getCookie(name) 
{
    var nameEQ = name + "=";
		  var ca = document.cookie.split(';');
		  for(var i=0;i < ca.length;i++) 
    { 
		      var c = ca[i];
				  while (c.charAt(0)==' ') c = c.substring(1,c.length);
				  if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
		  }
				
    return null;
	}

	// Deletes a cookie by name.
function eraseCookie(name) 
{
	    createCookie(name,"",-1);
	}		
			
//String randomizer function to create a random string to insure no two users get the same Session ID.
	function randomString() 
{
	    var chars = "!0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz-";
			var string_length = 56;
			var s = '';
			for (var i=0; i<string_length; i++) 
    {
			    var rnum = Math.floor(Math.random() * chars.length);
					s += chars.substring(rnum,rnum+1);
			}
				
    return s;
	}
	
//used for endeca
function blurSearch(){
	if (document.endeca_search_form_one.SearchString.value==''){
		document.endeca_search_form_one.SearchString.value='Search';
	}
}
function focusSearch(){
	if (document.endeca_search_form_one.SearchString.value=='Search'){
		document.endeca_search_form_one.SearchString.value='';
	}
}


//used for saks bag overlay

var receiveReqNumItems;
var numItemsReturned;
var SaksBagImg;

function getNumberofItems(){
	receiveReqNumItems=getXmlHttpRequestObjectItems();
	loadNumItems();
}

function getObjItems(imgId){
	if(document.getElementById){
		return document.getElementById(imgId);
	}else if(document.getElementsByName){
		return document.getElementsByName(imgId);
	}else if(document.getElementsByTagName){
		return document.getElementsByTagName(imgId);
	}else if (document.all){
	   return document.all[imgId];
	}else{
		return false;
	}
}

function getXmlHttpRequestObjectItems() {
	if (window.XMLHttpRequest) {
		return new XMLHttpRequest(); //Not IE
	} else if(window.ActiveXObject) {
		return new ActiveXObject("Microsoft.XMLHTTP"); //IE
	} else {
		//alert("Your browser doesn't support AJAX.");
	}
}

//popup effects, fade in and expand
var sPath = window.location.pathname;
var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
ie5  = (document.all && document.getElementById && (navigator.userAgent.indexOf("Opera") < 0));
ns6 = (!document.all && document.getElementById || (navigator.userAgent.indexOf("Opera") >= 0));
opac = 0;
if (sPage.indexOf("Entry")> -1){MyLeft=0}else{MyLeft=0}

var docTitle = document.title;
if (docTitle.indexOf("Payment method") > -1) {
	myTop=141;
} else if (docTitle.indexOf("Search Sale") > -1) {
	myTop=141;
} else if (docTitle.indexOf("elite_mastercard_apply") > -1) {
	myTop=410;
} else {
	myTop=141;
}

//popup slide in code. include name of layer and its height+1 pixle in the call
var myHeight=1;
var layerOpened = false;
function slideIn(wchLayer,lyrHght,lyrTop,lyrLeft){
/*	if (lyrLeft != null){
		document.getElementById(wchLayer).style.left = lyrLeft;
	}else{
		document.getElementById(wchLayer).style.left = MyLeft;
	}
	if (lyrTop != null){
		document.getElementById(wchLayer).style.top = lyrTop;
	}*/
	if (isIE) {HidePullDown();}
	myOpen(wchLayer,lyrHght);
}

function myOpen(wchLayer,lyrHght){
	if(!layerOpened){
		jQuery('#' + wchLayer).slideDown(1500, function (){
			layerOpened = true;		
		});
		//Effect.BlindDown(wchLayer, { duration: 1.5, afterFinish: blindDownLayerFinished  });
	}
}

function slideOut(wchLayer){
	jQuery('#' + wchLayer).slideUp(1000, function (){
		layerOpened = false;
		if (isIE) {ShowPullDown();}	
	});
	//Effect.BlindUp(wchLayer, { duration: 1, afterFinish: blindUpLayerFinished  });
}

function blindDownLayerFinished (){

}

var blindUpLayerFinished = function(){

}

//end of slide in

//popup fade in. include name of layer
function fadeIn(wchLayer) {
	if (isIE) {HidePullDown();}
	if(opac != 100){
		opac+=4;
		if (ie5) document.getElementById(wchLayer).filters.alpha.opacity = opac;
		if (ie5) document.all[wchLayer].style.left = MyLeft;
		if (ie5) document.all[wchLayer].style.top = myTop;
		if (ns6) document.getElementById(wchLayer).style.MozOpacity = opac/100;
		if (ns6) document.getElementById(wchLayer).style.left = MyLeft;
		if (ns6) document.getElementById(wchLayer).style.top = myTop;
		setTimeout("fadeIn('"+wchLayer+"')", 25);
	}else{return;}
}

//find x for atribute driven banner (fix a safari issue called from btm nav)
function testMyX(obj){
obj=document.getElementById(obj);
var newY = findPos(obj);
document.getElementById('Layer1').style.left = newY[0];
}
//to place pop-up next to link that called it (mostly used for check-out)
function setLyr(obj,lyr)
{
	var newY = findPos(obj);
	var sPath = window.location.pathname;
	var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
	if((sPage.indexOf("Entry")> -1) || (sPage.indexOf("wac2_bc")> -1) || (sPage.indexOf("incubator_bc")> -1)){HomePage = true;}else{HomePage = false;}
	if (!HomePage) newY[1] -= 300;
	var x = new getObj(lyr);
	x.style.top = newY[1] + 'px';
}
function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}

function getObj(name)
{
if (document.getElementById)
{
	   this.obj = document.getElementById(name);
	   this.style = document.getElementById(name).style;
}
else if (document.all)
{
	   this.obj = document.all[name];
	   this.style = document.all[name].style;
}
else if (document.layers)
{
	   if (document.layers[name])
	   {
	   	this.obj = document.layers[name];
	   	this.style = document.layers[name];
	   }
	   else
	   {
	    this.obj = document.layers.testP.layers[name];
	    this.style = document.layers.testP.layers[name];
	   }
}
}

function popupwin(url, width, height, name){
if(name==null||name==""){
	var newWindow = window.open(url,"saksPopup","width=" + width + ",height=" + height + ",toolbar=no,location=no,scrollbars=yes,resizable=yes,menubar=no,status=no");
	newWindow.focus();	
}else{
	var newWindow = window.open(url,name,"width=" + width + ",height=" + height + ",toolbar=no,location=no,scrollbars=yes,resizable=yes,menubar=no,status=no");
	newWindow.focus();
}
}

function popupwinName(url, name, width, height){
	window.open(url,name,"width=" + width + ",height=" + height + ",toolbar=no,location=no,scrollbars=yes,resizable=yes,menubar=no,status=no");
}

function popupWinFixed(url, width, height){
window.open(url,"saksPopup","width=" + width + ",height=" + height + ",toolbar=no,location=no,scrollbars=no,resizable=no,menubar=no,status=no");
}

function popupWinFixed2(url, width, height, name){
	if( url.toLowerCase().indexOf('live_help.jsp') > -1 ){		
		if( url.indexOf('.jsp?') > -1 )
			url += '&refPath=' + encodeURIComponent(window.location.pathname + window.location.search);
		else
			url += '?refPath=' + encodeURIComponent(window.location.pathname + window.location.search);	
	}
	
	if(name==null||name==""){
		window.open(url,"saksPopup","width=" + width + ",height=" + height + ",toolbar=no,location=no,scrollbars=no,resizable=yes,menubar=no,status=no");
	} else {
		window.open(url,name,"width=" + width + ",height=" + height + ",toolbar=no,location=no,scrollbars=no,resizable=yes,menubar=no,status=no"); 
	}
}

function openInNewTab(obj, url){
	window.open(url,'_blank');
}

function chooseAndGo(myDropdown){
	if(myDropdown.options[myDropdown.selectedIndex].value){
		location.href = myDropdown.options[myDropdown.selectedIndex].value;
	}
	else{
		myDropdown.selectedIndex = 0;
	}
}

function enabledQLButtons(){
	lightwindowInit();
	if (DetectFlashVer(9, 0, 0) || getRealEstate("testJSvideo")){
		jQuery('.videoLink', '#saksBody').css('display','block');
		if(window.autoVideoRender)
			autoVideoRender.triggerVideoOnLoad();
	}
}

function setQuickLookOmniture(omniture_Pgnm,ominture_prodinfo, EditorialSRE){
	s.pageName=omniture_Pgnm;	
	s.channel="productArray";
	s.events="prodView";
	s.products=ominture_prodinfo;
	s.prop1="quicklook";
	s.eVar42=EditorialSRE;
	void(s.t());
}

function setVideoTemplateOmniture(omniture_Pgnm){
	s.pageName=omniture_Pgnm;	
	s.channel="editorial";
	s.prop1="video";
	void(s.t());
}

function checkPlayVideoOmniture(omniture_ProductID){
	s.products=";"+omniture_ProductID+";;;;evar28=Product Array";
	s.events='event12';
	void(s.t());
}


var ProductVideos = function() {
		var isiPad = false;
		if (window.Touch){
			isiPad = true;
		}
		//var testmp4 = "http://images.saksfifthavenue.com/images/products/04/247/0022/0424700223222/0424700223222R_274x329.mp4";
		//var testswf = "";
		var flashparams = {
			wmode: "transparent",
			play: "true",
			align: "middle",
			quality: "high",
			bgcolor: "#000000",
			menu: "false",
			name: "videoName",
			allowScriptAccess: "always"
		};
		var flashattrs = {
			styleclass: "vidcontainer"
		};
		return {
			showProductVideo: function(targID, vidFilePath, vwidth, vheight, swfPath){
				//vidFilePath=testmp4;
				//swfPath = testswf;
				if (isiPad){	//write in video tag
					var html5ID = targID+"_5";
					var vidHolder = this.getObjectIdInfo(targID);
					vidHolder.innerHTML = '<video id="'+html5ID+'" width="'+vwidth+'" height="'+vheight+'"><source src="'+vidFilePath+'" width="'+vwidth+'" height="'+vheight+'" /></video>';
					vidHolder.style.display = "block";
					vidHolder.className="vidcontainer";
					var vid = this.getObjectIdInfo(html5ID);  
					if (vid != null){	
						vid.src = vidFilePath;
						//alert(vid.src);
						if (vidFilePath.toLowerCase().indexOf(".flv") != -1){//can't play flv
							ProductVideos.hideVideo(targID);
						} else {
						vid.load();
						vid.play();
						vid.addEventListener('ended', function(e) {
							ProductVideos.hideVideo(targID);
							}, false);
						}//flv
					}//null
				} else { //write in flash tags
					swfobject.embedSWF(
						swfPath, 
						targID, 
						vwidth, vheight, 
						"9.0.0", "expressInstall.swf", {
							videopath: vidFilePath,
							divtarg: targID
						}, flashparams, flashattrs);
				}
	
			},
	
			removeListeners: function (videoID){
				this.getObjectIdInfo(videoID).onEnded = null;
			},
			hideVideo: function (id){
				if (isiPad){this.removeListeners(id+"_5");}
				this.getObjectIdInfo(id).style.display = "none";
			},
			getObjectIdInfo: function (videoElemId) {
				var elem = document.getElementById(videoElemId)
				if(document.getElementById) {
					elem = document.getElementById(videoElemId);
				} else if (document.all) {
					elem = document.all[videoElemId];
				}
				return elem;
			},
			isTouch: function(){
				return isiPad;
			}
		}
}();


function ShowHideSectionDiv(wchLayer,wchLayer2) {
	var e, e2, v, type;
	if( document.getElementById ){
		type = 1;
		e = document.getElementById( wchLayer );
		e2 = document.getElementById( wchLayer2 );
	}else if( document.all ){
		type = 2;
		e = document.all[wchLayer];
		e2 = document.all[wchLayer2];
	}else if( document.layers ){
		type = 3;
		e = document.layers[wchLayer];
		e2 = document.layers[wchLayer2];
	}

	var x = 0;
	for (var node=1; node < 99; node++){
		if(type == 1){
			if(document.getElementById("cat"+node+"a")){
				x++;
			}else{
				x++;
				break;
			}
		}else if(type == 2){
			if(document.all["cat"+node+"a"]){
				x++;
			}else{
				x++;
				break;
			}
		}else if(type == 3){
			if(document.layers["cat"+node+"a"]){
				x++;
			}else{
				x++;
				break;
			}
		}
	}
	var category_now;

	for (var node2=1; node2 < x; node2++){
		category_now = "cat"+node2+"a";
		category_now1 = "cat"+node2+"a1";
		if(category_now != wchLayer){
			if(type == 1){
				document.getElementById(category_now).style.display='none';
				document.getElementById(category_now1).className='leftNavText';
			}else if(type == 2){
				document.all[category_now].style.display='none';
				document.all[category_now1].className='leftNavText';
			}else if(type == 3){
				document.layers[category_now].style.display='none';
				document.layers[category_now1].className='leftNavText';
			}
		}
	}

	v = e.style;
	if(v.display==''&&e.offsetWidth!=undefined&&e.offsetHeight!=undefined){
		v.display = (e.offsetWidth!=0&&e.offsetHeight!=0)?'block':'none';
	}
	v.display = (v.display==''||v.display=='block')?'none':'block';
	if(v.display=='block'){
		e2.className='leftNavBold';
	}else{
		e2.className='leftNavText';
	}
}

/* show hide pull down */
function HidePullDown() {
	var sPath = window.location.pathname;
	var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
	//if (document.getElementsByName("ADD_CART_ITEM_ARRAY<>sku_id")!= null) {  //Product Detail pages
//			document.getElementsByName("ADD_CART_ITEM_ARRAY<>sku_id").style.visibility = "hidden";
//			}
	if (document.getElementById("leftNavBrands")!= null) {  //sections left nav drop down menu
			document.getElementById("leftNavBrands").style.visibility = "hidden";
			}
	if (document.getElementById("cboSortBy")!= null) {  //sections left nav drop down menu
			document.getElementById("cboSortBy").style.visibility = "hidden";
			}		
	if (document.getElementById("display")!= null) { //EndecaSearch results
			document.getElementById("display").style.visibility = "hidden";
			}
	if (document.getElementById("srt")!= null) {  //EndecaSearch results
			document.getElementById("srt").style.visibility = "hidden";
			}
	if ((document.getElementById("CREDIT_CARD<>cardBrand_cd")!= null)&& !(sPage.indexOf("qas_ver")> -1)&& !(sPage.indexOf("PayMethod")> -1)) {  //my account
			document.getElementById("CREDIT_CARD<>cardBrand_cd").style.visibility = "hidden";
			}
	if (document.getElementById("CART_ITEM_ARRAY<>shipToID")!= null) {  //check out for returned
			document.getElementById("CART_ITEM_ARRAY<>shipToID").style.visibility = "hidden";
			}
	if (document.getElementById("CART_ITEM_ARRAY<>shippingMethod")!= null) {  //check out for returned
			document.getElementById("CART_ITEM_ARRAY<>shippingMethod").style.visibility = "hidden";
			}
	if (document.getElementById("Line1")!= null) {  //check out for returned
			document.getElementById("Line1").style.visibility = "hidden";
			}
	//if ((document.multiship.elements[38].name.indexOf('CART_ITEM_ARRAY<>shippingMethod')>-1)) {  //check out for returned
			//document.multiship.elements[38].style.visibility = "hidden";
			//}
	if (document.getElementById("SHIP_TO_ADDRESS<>indGift")!= null) {  //check out and my account
			document.getElementById("SHIP_TO_ADDRESS<>indGift").style.visibility = "hidden";
			}
	if (document.getElementById("BILL_TO_ADDRESS<>indGift")!= null) {  //check out and my account
			document.getElementById("BILL_TO_ADDRESS<>indGift").style.visibility = "hidden";
			}
	if ((document.getElementById("CREDIT_CARD<>cardMonth_cd")!= null)&& !(sPage.indexOf("mng_CreditCard")> -1)) {  //check out
			document.getElementById("CREDIT_CARD<>cardMonth_cd").style.visibility = "hidden";
			}
	if ((document.getElementById("CREDIT_CARD<>cardYear_cd")!= null)&& !(sPage.indexOf("mng_CreditCard")> -1)) {  //check out
			document.getElementById("CREDIT_CARD<>cardYear_cd").style.visibility = "hidden";
			}
	if (document.getElementById("ADD_CART_ITEM_ARRAY<>sku_id")!= null) { //ProductDetail
			document.getElementById("ADD_CART_ITEM_ARRAY<>sku_id").style.visibility = "hidden";
			}
	if (document.getElementById("ADD_CART_ITEM<>sku_id")!= null) { //ProductDetail
			document.getElementById("ADD_CART_ITEM<>sku_id").style.visibility = "hidden";
			}
	if (document.getElementById("Title")!= null) { //email_collect_popup_main
			document.getElementById("Title").style.visibility = "hidden";
			}
	if (document.getElementById("monthDOB")!= null) { //email_collect_popup_main
			document.getElementById("monthDOB").style.visibility = "hidden";
			}
	if (document.getElementById("dayDOB")!= null) { //email_collect_popup_main
			document.getElementById("dayDOB").style.visibility = "hidden";
			}
	if (document.getElementById("store_codes")!= null) { //email_collect_popup_main
			document.getElementById("store_codes").style.visibility = "hidden";
			}
	if (document.getElementById("errN")!= null) { //EndecaSearch no results
			document.getElementById("errN").style.visibility = "hidden";
			}
	if (document.getElementById("ShopByPage")!= null) { //catalog
			document.getElementById("ShopByPage").style.visibility = "hidden";
			}
		}

	function ShowPullDown() {
	//if (document.getElementsByName("ADD_CART_ITEM_ARRAY<>sku_id")!= null) {
//			document.getElementsByName("ADD_CART_ITEM_ARRAY<>sku_id").style.visibility = "visible";
//			}
	if (document.getElementById("leftNavBrands")!= null) {
			document.getElementById("leftNavBrands").style.visibility = "visible";
			}
	if (document.getElementById("cboSortBy")!= null) {
			document.getElementById("cboSortBy").style.visibility = "visible";
			}		
	if (document.getElementById("display")!= null) {
			document.getElementById("display").style.visibility = "visible";
			}
	if (document.getElementById("srt")!= null) {
			document.getElementById("srt").style.visibility = "visible";
			}
	if (document.getElementById("CREDIT_CARD<>cardBrand_cd")!= null) {
			document.getElementById("CREDIT_CARD<>cardBrand_cd").style.visibility = "visible";
			}
	if (document.getElementById("CART_ITEM_ARRAY<>shipToID")!= null) {
			document.getElementById("CART_ITEM_ARRAY<>shipToID").style.visibility = "visible";
			}
	if (document.getElementById("CART_ITEM_ARRAY<>shippingMethod")!= null) {
			document.getElementById("CART_ITEM_ARRAY<>shippingMethod").style.visibility = "visible";
			}
	if (document.getElementById("Line1")!= null) {
			document.getElementById("Line1").style.visibility = "visible";
			}
	//if ((document.multiship.elements[38]!= null)&& (document.multiship.elements[38].name.indexOf('CART_ITEM_ARRAY<>shippingMethod')>-1)) {
			//document.multiship.elements[38].style.visibility = "visible";
			//}
	if (document.getElementById("SHIP_TO_ADDRESS<>indGift")!= null) {
			document.getElementById("SHIP_TO_ADDRESS<>indGift").style.visibility = "visible";
			}
	if (document.getElementById("BILL_TO_ADDRESS<>indGift")!= null) {
			document.getElementById("BILL_TO_ADDRESS<>indGift").style.visibility = "visible";
			}
	if (document.getElementById("CREDIT_CARD<>cardMonth_cd")!= null) {
			document.getElementById("CREDIT_CARD<>cardMonth_cd").style.visibility = "visible";
			}
	if (document.getElementById("CREDIT_CARD<>cardYear_cd")!= null) {
			document.getElementById("CREDIT_CARD<>cardYear_cd").style.visibility = "visible";
			}
	if (document.getElementById("ADD_CART_ITEM_ARRAY<>sku_id")!= null) {
			document.getElementById("ADD_CART_ITEM_ARRAY<>sku_id").style.visibility = "visible";
			}
	if (document.getElementById("ADD_CART_ITEM<>sku_id")!= null) {
			document.getElementById("ADD_CART_ITEM<>sku_id").style.visibility = "visible";
			}
	if (document.getElementById("Title")!= null) {
			document.getElementById("Title").style.visibility = "visible";
			}
	if (document.getElementById("monthDOB")!= null) {
			document.getElementById("monthDOB").style.visibility = "visible";
			}
	if (document.getElementById("dayDOB")!= null) {
			document.getElementById("dayDOB").style.visibility = "visible";
			}
	if (document.getElementById("store_codes")!= null) {
			document.getElementById("store_codes").style.visibility = "visible";
			}
	if (document.getElementById("errN")!= null) {
			document.getElementById("errN").style.visibility = "visible";
			}
	if (document.getElementById("ShopByPage")!= null) {
			document.getElementById("ShopByPage").style.visibility = "visible";
			}
		}

	function ShowAllPullDowns(){
		if(document.ordersum_ru){
			AllSelectsOnForm(document.ordersum_ru, "visible");
		}
		if(document.mngSaveShipping){
			AllSelectsOnForm(document.mngSaveShipping, "visible");
		}
		if(document.mngSaveBilling){
			AllSelectsOnForm(document.mngSaveBilling, "visible");
		}
		if(document.EditBillAddress){
			AllSelectsOnForm(document.EditBillAddress, "visible");
		}
		if(document.AddBillAddress){
			AllSelectsOnForm(document.AddBillAddress, "visible");
		}
		if(document.EditShipAddress){
			AllSelectsOnForm(document.EditShipAddress, "visible");
		}
		if(document.AddShipAddress){
			AllSelectsOnForm(document.AddShipAddress, "visible");
		}
		if(document.multiship){
			AllSelectsOnForm(document.multiship, "visible");
		}
		if(document.mngNewCard){
			AllSelectsOnForm(document.mngNewCard, "visible");
		}
		if(document.email_updates_collect){
			AllSelectsOnForm(document.email_updates_collect, "visible");
		}
		if(document.choosenPage){
			AllSelectsOnForm(document.choosenPage, "visible");
		}
	}

	function HideAllPullDowns(){
		if(document.ordersum_ru){
			AllSelectsOnForm(document.ordersum_ru, "hidden");
		}
		if(document.mngSaveShipping){
			AllSelectsOnForm(document.mngSaveShipping, "hidden");
		}
		if(document.mngSaveBilling){
			AllSelectsOnForm(document.mngSaveBilling, "hidden");
		}
		if(document.EditBillAddress){
			AllSelectsOnForm(document.EditBillAddress, "hidden");
		}
		if(document.AddBillAddress){
			AllSelectsOnForm(document.AddBillAddress, "hidden");
		}
		if(document.EditShipAddress){
			AllSelectsOnForm(document.EditShipAddress, "hidden");
		}
		if(document.AddShipAddress){
			AllSelectsOnForm(document.AddShipAddress, "hidden");
		}
		if(document.multiship){
			AllSelectsOnForm(document.multiship, "hidden");
		}
		if(document.mngNewCard){
			AllSelectsOnForm(document.mngNewCard, "hidden");
		}
		if(document.email_updates_collect){
			AllSelectsOnForm(document.email_updates_collect, "hidden");
		}
		if(document.choosenPage){
			AllSelectsOnForm(document.choosenPage, "hidden");
		}
	}

	function AllSelectsOnForm(formName, ShowOrHide){
		for (i=0; i<formName.elements.length; i++){
			if((formName.elements[i].type=="select-one") || (formName.elements[i].type=="select-multiple") || (formName.elements[i].type=="select")){
				formName.elements[i].style.visibility = ShowOrHide;
			}
		}
	}

	function showReplaceText(text){
		var brName = "colorSizeBR";
		var brFullID;
		for(i=0; i<7; i++){
			brFullID = brName+i;
			if(document.getElementById(brFullID)){
				document.getElementById(brFullID).innerHTML = text;
			}
		}
		
		brName = "colorSizePlainBR";
		for(j=0; j<7; j++){
			brFullID = brName+j;
			if(document.getElementById(brFullID)){
				document.getElementById(brFullID).innerHTML = text;
			}
		}
	}



/* quick view - FIS */
var saksModal = (function($){
	var _viewPortHandler = {
			_viewPortObj : {
				windowX : null,
				windowY : null,
				scrollX : null,
				scrollY : null,
				pageX : null,
				pageY : null
			},
			_getViewPort : function(){
				var newViewPort = $.extend({}, this._viewPortObj);
				newViewPort.windowX = (document.documentElement && document.documentElement.clientWidth) || window.innerWidth || self.innerWidth || document.body.clientWidth;
				newViewPort.windowY = (document.documentElement && document.documentElement.clientHeight) || window.innerHeight || self.innerHeight || document.body.clientHeight;
				newViewPort.scrollX = (document.documentElement && document.documentElement.scrollLeft) || window.pageXOffset || self.pageXOffset || document.body.scrollLeft;
				newViewPort.scrollY = (document.documentElement && document.documentElement.scrollTop) || window.pageYOffset || self.pageYOffset || document.body.scrollTop;
				newViewPort.pageX = (document.documentElement && document.documentElement.scrollWidth) ? document.documentElement.scrollWidth : (document.body.scrollWidth > document.body.offsetWidth) ? document.body.scrollWidth : document.body.offsetWidth;
				newViewPort.pageY = (document.documentElement && document.documentElement.scrollHeight) ? document.documentElement.scrollHeight : (document.body.scrollHeight > document.body.offsetHeight) ? document.body.scrollHeight : document.body.offsetHeight;
				return newViewPort;
			}
	};
	
	var _getContent = function(content, w, h, cntrId) {
			var view = _viewPortHandler._getViewPort();
			var _id = cntrId != null ? cntrId : "generic-modal";
			var _w = (w != null) ? w : 600;
			var _h = (h != null) ? h : 500;
			$("body").append('<div id="saksOverlay"/>').append('<div id="' + _id + '" class="cssRoot modal-container"/>');
			$("#saksOverlay").css({
				"height":view.pageY,
				"width":view.pageX,
				"opacity":.5
			});
			var _activeLayer = $("#"+_id);
			var layerTop = ((view.windowY - _h) / 2) + view.scrollY;
			if (layerTop < view.scrollY)
				layerTop = view.scrollY + 10;
			var layerLeft = (view.windowX - _w) / 2;
			_activeLayer.append(content).css({
				"height":'auto',
				"width":_w,
				"top":layerTop + "px",
				"left":layerLeft + "px"
			});
	};
	
	var _appendContent = function(content, w, h, cntrId) {
		$(cntrId).append(content);	
	};
	
	var _replaceContent = function(content, w, h, cntrId) {
		cntrId = (cntrId) ? cntrId : '#generic-modal';
		$(cntrId).empty().append(content);
	};
	
	var _resizeModalBox = function(w,h){
		$("#generic-modal").css("width",w);
		//$("#generic-modal").css("height",h);
	};
	
	var _centerModalBox = function(w,h,cntrId){
		var view = _viewPortHandler._getViewPort();
		var _w = $('#generic-modal').width();
		var _h = $('#generic-modal').height();
		$("#saksOverlay").css({
			"height":view.pageY,
			"width":view.pageX,
			"opacity":.5
		});
		var _activeLayer = $("#generic-modal");
		var layerTop = ((view.windowY - _h) / 2) + view.scrollY;
		if (layerTop < view.scrollY)
			layerTop = view.scrollY + 10;
		var layerLeft = (view.windowX - _w) / 2;
		_activeLayer.css({
			"height":'auto',
			"width":_w,
			"top":layerTop + "px",
			"left":layerLeft + "px"
		},1000);			
	}
	
	var _bindEvents = function(){
		$('.modal-close', '#generic-modal').click(function() {
			saksModal.destroy();
			if(window.layer)
				layer.closeToStep();
		});
	};
	
	var _putInModalBox = function(content, w, h, cntrId) {
		_replaceContent(content, w, h, cntrId);
		_resizeModalBox(w,h);
		_centerModalBox();
		_bindEvents();
	};
	
	var _launchModalBox = function(content, w, h, cntrId) {
		_getContent(content, w, h, cntrId);
		_bindEvents();
	};
	
	return{
		launchModalBox : _launchModalBox,
		putInModalBox : _putInModalBox,
		appendToModalBox : function(content, w, h, cntrId) {
			_resizeModalBox(w,h);
			_appendContent(content, w, h, cntrId);
			_centerModalBox();
			_bindEvents();
		},
		viewInModal : function(html, w, h){
			logger.log('view modal call');
			var _layerOpen = ($('#generic-modal').length == 1)? true : false;
			(_layerOpen) ? _putInModalBox(html, w, h) : _launchModalBox(html, w, h);
		},
		destroy : function(){
			$("#saksOverlay").remove();
			$("#generic-modal").remove();
		},
		replaceContent : function(content, w, h, cntrId){
			_replaceContent(content, w, h, cntrId);
		},
		resizeModalBox : function(w,h){
			_resizeModalBox(w,h);
		},
		refresh: function () {
			_centerModalBox();
		}
	};
})(jQuery);

var rfxInterface = (function($){
	var _rfx = null;
	
	return{
		getRFXInterface : function(){
			if(window.location.protocol.toLowerCase().indexOf('https') > -1)
				return null;
			
			if(!_rfx){
				logger.log('setting up RFX interface');
				_rfx = $('#rfx-ql-frame')[0].contentWindow.RICHFX;
			}
			
			return _rfx;
		}
	};
})(jQuery);

var saksQuickLook = (function($){

	var _clear = function() {return '<div class="clear"><!-- --></div>';};
	var _getImageRoot = function() {return "/static/images/";};
	
	var _quickLookSkuMessages = null;
	
	var _createQuickLookHTML = function(item) {
		var a = [];
		var ql = item;
		var soldOut = ql.itemSoldOut;
		var colors = ql.colors;
		var iframeSrc = ql.viewer;
		a.push('<div id="quicklook"><div id="quicklook-inner">');
		a.push('<div class="content-left">');
		if (iframeSrc)
			a.push('<div id="rfxParent"><iframe id="rfx-ql-frame" src="' + iframeSrc + '" frameborder="0" marginheight="0" marginwidth="0" scrolling="no"></iframe></div>');
		else if (item.images)
			a.push('<div id="quicklook-large-image"><img src="' + ql.images.large +' " alt="" /></div>');
		a.push('</div>');// /content-left
		a.push('<div class="content-right">');
		a.push('<div class="close-wrap"><a class="modal-close overlay-close">CLOSE</a><div class="clear"><!-- --></div></div>');
		a.push('<div class="content-right-inner">');
		a.push('<h1 class="item-name">');
		a.push(ql.productName);
		a.push('</h1><h2 class="item-shortDesc">');
		a.push(ql.shortDescription);
		a.push('</h2>');

		if(ql.productReviewSubmitable){
			var hostname = window.location.hostname;
			var reviewLandingURL = "http://" + hostname + "/main/productreview/ReviewLanding.jsp";
			
			a.push('<div id="star-rating">');
			if(ql.totalReviewCount === 0){
				a.push('<img src="/static/images/star_rating/'+ ql.reviewScore +'.gif" border="0" /><br/>');
				a.push('<span>Be The First to <a href="'+ql.reviewRedirectURL+'">Write a Review</a></span>');
			}else{
				a.push('<img src="/static/images/star_rating/'+ ql.reviewScore +'.gif" border="0" title="This product rates '+ ql.formatedReviewScore +' out of 5 stars from '+ ql.totalReviewCount +' customer reviews"/><br/>');
				a.push('<span><a href="javascript:popupwin(\'' + reviewLandingURL + '?prodCode=' + ql.productCode + '\', 740,460,'+ ql.productCode +');">' + ql.readReviewString +' </a></span>');
				a.push('<span style="margin:2px;"><img src="/media/images/product_review/list_bullet.gif" /></span>');
				a.push('<span><a href="'+ql.reviewRedirectURL+'">Write a Review</a></span>');
			}
			a.push('</div>');
		}

		a.push('<div class="item-sku">');
		a.push(ql.productCode);
		a.push('</div>');		
		a.push(_generateQLPrices(soldOut, ql));
		a.push(_generateFBLikeButton(ql.detailPage)); // QC#1334
		
		var tabWrapClass = "singleTab";
		if (colors.length > 0)
			tabWrapClass = "tab1on"; //check for other tabs and set active class if necessary
		a.push('<div id="item-tabs-wrap" class="' + tabWrapClass + '">');
		a.push('<div class="item-tab">');
		a.push('<a id="jsShowDescription">Description</a>');
		a.push('</div>');
		if (colors.length > 0) {
			a.push('<div class="item-tab">');
			a.push('<a id="jsShowColors">Colors</a>');
			a.push('</div>');
		}
		a.push(_clear());
		a.push('</div>');
		
		a.push('<div class="item-desc-wrap">');
		a.push(_generateProductInfo(ql));
		a.push(_generateSwatches(soldOut, colors, sksItemModel.getProductInfo('_isColorized')));
		a.push('</div>'); //#item-dec-wrap
		
		a.push('<div class="item-desc-bottom"><img src="' + _getImageRoot() + 'quicklook-desc-tab-bot.gif" alt=""></div>');
		a.push('<form name="edit_item_service" id="edit_item_service">');
		if (!soldOut && !ql.inOtherMembersCart) {
			a.push('<div class="quantity-input">');
			
			var currentQty = (ql.quantity) ? ql.quantity : 1;
			a.push('<label for="MainProductqtyToBuy0">QTY.<span class="asterisk">*</span></label><input type="text" name="itemQuantity" id="MainProductqtyToBuy0" class="qty-to-buy" size="2" value="' + currentQty + '" maxlength="2" />');
			
			a.push(_generateSizeColorDropDown(ql.skuVariants));
			
			a.push(_clear());
			a.push('</div>');//.quantity-input
		}
		if(!item){
			a.push('<div class="more-info"><a href="');
			a.push(ql.detailPage);
			a.push('">Full Product Details ></a></div>');
		}
		a.push('<div id="message-quicklook-foot" class="error">');

		var warningMessages = ql.messages;
		for (var i = 0; i < warningMessages.length; i++) {
			a.push('<p class="warning">' + warningMessages[i].message + '</p>');
		}
		a.push('</div>');		
			
		if(!ql.intlShippingRestricted){
			a.push('<div class="button-row">');
			
			if (!soldOut || ql.showFindInStoreLink) 
				a.push('<a class="detailsLinkStyle" href="' + ql.detailPage + '" target="_parent">Full Product Details ></a>');
			
			if(!soldOut && !ql.inOtherMembersCart && !ql.giftWithPurchase)
				a.push('<input id="jsAddToBag" type="image" border="0" title="ADD TO BAG" alt="ADD TO BAG" src="/static/images/btn/add-to-bag.gif" name="quicklook_checkout">');
			
			a.push( _generateItemAvailMessaging(soldOut, ql) );

			a.push('</div>');// /button-row
		} else {
			a.push('Sorry this item cannot be shipped internationally');
		}		
		
		a.push('</form>');
		a.push('</div>');// /content-right-inner 		
		a.push(_generateSharingButtons(ql.detailPage, ql.productName + ' - ' + ql.shortDescription)) // QC#1334
		a.push('</div>');// /content-right
		a.push(_clear());
		a.push('</div></div>');// /quicklook-inner /quicklook
		return a.join('');
	};
	
	 var _generateItemAvailMessaging = function(soldOut, ql){
		 var a = [];

		 /**if(ql.findInStoreEnabled){
			**a.push('<div class="availability-container">');
			**if(!soldOut){ // IN STOCK
			**	if(ql.showFindInStoreLink){ // FIS TRUE
			**		a.push('<div>Also available <a id="jsFindInStoreQL">in store.</a></div>');
			**	}
			**}else{ // SOLD OUT
			**	if(ql.showFindInStoreLink){ // FIS TRUE
			**		a.push('<div>Only available <a id="jsFindInStoreQL">in store.</a></div>');
			**	}else{ //FIS FALSE
			**		a.push('<div>Sorry, this item is not available.</div>');
			**	}
			**}
			**a.push('</div>');
		 **}else if(soldOut){
			** a.push('<div class="availability-container">Sorry, this item is no longer available online.</div>');
		 }**/
		 
		 if(soldOut)
			 a.push('<div class="availability-container">Sorry, this item is not available.</div>');
		 
		 if(ql.inOtherMembersCart)
			 a.push('<div id="in-other-members-cart">'+ql.inOtherMembersCartMsg+'</div>');
		 
		 return a.join('');
	 };
	
	// BEGIN QC#1334
	
	/**
	 * 	Returns the HTML snippet required to generate the FB like button. 
	 * 	@private
	 * 	@param p {String} URL to the product's PD webpage.
	 * 	@method _generateFBLikeButton(p)
	 * 	@returns {String}
	 */
	
	var _generateFBLikeButton = function (p) {
		var a = [],
			i = p.indexOf( '?' ),
			l = p.length,
			clean_url = p.substr( 0, i >= 0 ? i : l ), 
			product_id = p.match( /PRODUCT%3C%3Eprd_id=[0-9]+/i ),
			product_id = product_id != null ? product_id[0] : '',
			canonical_url = clean_url + '?' + product_id;
			
		a.push('<div class="fb-like-button">');		
    	a.push('<fb:like href="' + canonical_url + '" send="false" layout="button_count" width="220" show_faces="false"></fb:like>');
    	a.push('</div>');
    	return a.join('');
	}
	
	/**
	 * 	Returns the HTML snippet required to generate the Product Sharing buttons.
	 * 	@private
	 * 	@param p {String} URL to the product's PD webpage.
	 *  @param n {String} Product whole name
	 * 	@method _generateSharingButtons(p)
	 * 	@returns {String}
	 */
	
	var _generateSharingButtons = function (p, n) {
		var a = [], 			
			i = p.indexOf( '?' ),
			l = p.length,
			clean_url = p.substr( 0, i >= 0 ? i : l ), 
			product_id = p.match( /PRODUCT%3C%3Eprd_id=[0-9]+/i ),
			product_id = product_id != null ? product_id[0] : '',
			canonical_url = clean_url + '?' + product_id;
		
		a.push('<div id="share-product">');
		
		a.push('<h6>Share</h6>');
		
		a.push('<div class="share-button-container">');
		
		// mail to friend button
		a.push('<div class="email-container share-button">');
		a.push('<a class="email-button" target="_blank" href="https://www.saksfifthavenue.com/main/ComposeTAF.jsp?' + product_id + '"></a>');		
		a.push('</div>');
		
		// custom twitter button
		a.push('<div class="twitter-container share-button">');		
		a.push('<a href="https://twitter.com/share?url=' + encodeURI(canonical_url) + '&text=' + encodeURI( n + ' | Saks Fifth Avenue') + '" class="twitter-custom-button"></a>');
		a.push('</div>');
		
		// g-plusone button
		a.push('<div class="plusone-container share-button">');
		a.push('<div class="g-plusone" data-href="' + canonical_url + '" data-size="medium" data-annotation="none"></div>');
		a.push('</div>');
		
		a.push('</div>');		
		
		a.push('</div>');	
		
		return a.join('');
	}
	
	/**
	 *	dynamically parse twitter, facebook and google+1 buttons from HTML snippet in QuickLook container. If
	 *	social frameworks are not available they will be loaded on demand.
	 *	@param context {jQuery Selection Object} context where buttons are located
	 *	@returns {Void} 
	 */
	
	var _parseSocialSharingButtons = (function(){
	
		/**
		 * load a single script node based on the given <options> and appends it to the
		 * document head. If a <callback> function is available in <options> it is executed
		 * once the script is loaded.
		 * @param options {Object}
		 * 	- src {String} script location
		 * 	- asynch {Boolean} whether to load the script asynchronously
		 * 	- callback {Function} executed when the script is loaded
		 * 	- bind {Object} object to bind as this in the callback function
		 * 	- args {Array} arguments to pass to the callback function
		 * @return void
		 */
		
		function loadScript (options) {
			var head = document.head || document.getElementsByTagName('head')[0],
				node = document.createElement('script');
			
			node.setAttribute('type', 'text/javascript');
			node.setAttribute('asynch', !!options.asynch);
			node.setAttribute('src', options.src);
			
			/* IE */
			
			node.onreadystatechange = function() {
				if ( (node.readyState == 'complete' || node.readyState == 'loaded') && typeof options.callback == 'function' )
					options.callback.apply( options.bind || null, options.args || [] );
			}
			
			/* Everyone Else */
			
			node.onload = function() {
				if ( typeof options.callback == 'function' )
					options.callback.apply( options.bind || null, options.args || [] );
			}
			
			node.onerror = function () {
				if ( typeof options.callback == 'function' )
					options.callback.apply( options.bind || null, options.args || [] );
			}
			
			head.appendChild(node);
		}
		
		/**
		 * load one or more script nodes based on the given <options> and appends them to the
		 * document head. If a <callback> function is available in <options> it is executed
		 * once all scripts are loaded.
		 * @param options {Object}
		 * 	- src {Mixed} script location
		 * 	- asynch {Boolean} whether to load the script asynchronously
		 * 	- callback {Function} executed when the script is loaded
		 * 	- bind {Object} object to bind as this in the callback function
		 * 	- args {Array} arguments to pass to the callback function
		 * @return void
		 */
		
		function loadScripts (options) {			
			var items = typeof options.src != 'string' ? Array.prototype.slice.call( options.src ) : [ options.src ],
				length = items.length, i,
				check = function() {
					if ( !(--length) && typeof options.callback == 'function' )
						options.callback.apply( options.bind || null, options.args );
				}
			
			for (i = 0; i < length; i++) {				
				loadScript({ src: options.src[i], asynch: options.asynch, callback: check });				
			}
		}		
		
		/**
		 * parses the social API items in quicklook
		 * @param context {jQuery} jQuery selection as context with social items
		 * @return void
		 */
		
		function parse ( context ) {			
			var FB = window.FB, gapi = window.gapi;
			
			if ( FB && FB.XFBML && FB.XFBML.parse ) {					
				context.find('.fb-like-button').each(function () {
					FB.XFBML.parse(this);
				});
			}
			
			if ( gapi && gapi.plusone && gapi.plusone.go ) {
				context.find('.plusone-container').each(function () {
					gapi.plusone.go(this);
				});					
			}
			
			context.find('a.twitter-custom-button').click(function(event){					
				event.preventDefault();
				
				var width = 550, height = 420,
					left = (screen.width / 2) - (width / 2), 
					top = (screen.height / 2) - (height / 2);
				
				window.open(this.href, 'Tweet', 'width=' + width + ', height=' + height + ', top=' + top + ', left=' + left);
			});
		}
		
		/**
		 * Returned as the function that initializes the parsing of social buttons in 
		 * quicklook. It does some preliminary checks prior to attempting to parse the
		 * sharing buttons in the given context.
		 * @param context {jQuery} jQuery selection as context with social items
		 * @return void 
		 */
		
		return function (context) {
			
			var missingAPI = [];
			var win = window;			
			
			if ( !win.FB ) {
				missingAPI.push('https://connect.facebook.net/en_US/all.js');
				
				// code ran when FB SDK is initialized
				
				if ( !win.fbAsyncInit ) {				
					win.fbAsyncInit = function() {
				  		FB.init({
					      	appId      : '112579470003', // Saks App ID
					      	status     : true, // check login status
					      	cookie     : true, // enable cookies to allow the server to access the session
					      	xfbml      : true, // parse XFBML
					      	channel	   : '/static/html/channel.js'
					    });
				  	};
				}
				
				if ( !document.getElementById('fb-root') ) {
					var fb_root = document.createElement('div');
				  	fb_root.id = 'fb-root';
				  	document.body.appendChild(fb_root);
				}
			}
			
			if ( !win.gapi ) missingAPI.push('https://apis.google.com/js/plusone.js');
			
			if ( missingAPI.length ) loadScripts({src: missingAPI, asynch: true, callback: parse, args: [context]});
			else parse(context)
		}
		
	})();
	
	// END QC#1334
	
	var _generateSizeColorDropDown = function(optArr){
		var messageArr = [];//holds sku specific warnings
		var a = [];
		a.push('');
		if(optArr.length){
			if (optArr.length > 1) {
				a.push('<select name="sku_id" class="vars-to-buy">');
				for (var i=0; i<optArr.length; i++) {
					var valStr = (optArr[i].value) ? optArr[i].value : '';
					var displayStr = (optArr[i].display) ? optArr[i].display : '';
					
					if (optArr[i].disabled=="true")
						a.push('<optgroup data-key="'+optArr[i].color+'" style="font-style:normal; font-weight:lighter; color:red" label="' + displayStr + '" value="' + valStr + '"');
					else
						a.push('<option data-key="'+optArr[i].color+'" value="' + valStr + '"');
					
					if (optArr[i].selected)
						a.push(' selected="selected"');
					if (optArr[i].message) {
						a.push(' class="hasMessage"');
						messageArr.push(optArr[i].message);
					} else {
						messageArr.push("");
					}
					a.push('>');
					a.push(displayStr);
					
					if (optArr[i].disabled=="true")
						a.push('</optgroup>');
					else
						a.push('</option>');
	
				}
				a.push('</select>');
			} else {
				a.push('<input type="hidden" name="sku_id" value="' + optArr[0].value + '">');
				messageArr.push((optArr[0].message) ? optArr[0].message : "");
			}
		}
		_quickLookSkuMessages = messageArr;
		return a.join('');
	};
	
	var _generateQLPrices = function(soldOut, ql){
		logger.log('GENERATING QUICK LOOK PRICES');
		var a = [];
		a.push('');
		if (!soldOut || ql.showFindInStoreLink){
			
			if(ql.onSaleFlag) {
				a.push('<span class="product-price">');
				a.push(ql.listPriceLabel);
				a.push('&nbsp;');
				a.push(ql.formattedListPrice);
				a.push('</span>');
				
				if (ql.skuPricedDifferent) {
					a.push('<p style="height: 0; margin-top: 0;"/>');
					a.push('<span class="blackBold11" style="font-weight:bold;">');
				} else {
					a.push('<span class="blackBold11" style="font-weight:bold; padding-left:5px;">');
				}
				
				a.push(ql.salePriceLabel);
				a.push('&nbsp;');
				a.push('<span class="product-sale-price">');
				a.push(ql.formattedSalePrice);
				a.push('</span></span>');		
			} else {
				a.push('<span class="product-price" style="font-weight:bold;">');
				a.push(ql.formattedListPrice+'</span>');
			}
		}
		return a.join('');
	};
	
	var _getHighDemandHTML = function(limit){
		return "<br /><br />DUE TO HIGH DEMAND, A CUSTOMER MAY ORDER NO MORE THAN "+limit+" UNITS OF THIS ITEM EVERY THIRTY DAYS. <br />" ;
	};
	
	var _generateProductInfo = function(ql){
		var a = [];
		a.push('');
		
		a.push('<div id="content-description" class="tabs-content">');
		a.push('<div class="product-description">');
		a.push(ql.productDescription);
		
		if(ql.purchaseLimitThreshold)
			a.push(_getHighDemandHTML(ql.purchaseLimitThreshold));
		
		a.push('</div>');
		
		if (ql.additionalInformation) {
			a.push('<div class="product-additional">');
			a.push('<h6>Additional Information</h6>');
			a.push(ql.additionalInformation);
			a.push('</div>');
		}
		a.push('</div>');
		return a.join('');
	}
	
	var _generateSwatches = function(soldOut, colors, isClickable){
		logger.log('GENERATING QUICK LOOK SWATCHES');
		logger.log('isClickable --> '+isClickable);
		var a = [];
		a.push('');
		if (!soldOut) {
			if (colors.length > 0) {
				a.push('<div id="content-colors" class="tabs-content');
				if(isClickable)
					a.push(' swatchToggle"');
				else
					a.push('"');

				a.push('style="display:none;">');
				var count = 0;
				for (var i=0; i<colors.length; i++) {
					var styleClass = (count == 0) ? "color-swatch first" : "color-swatch";
					if (colors[i].colorPath && colors[i].colorPath != "") {
						a.push('<div class="');
						a.push(styleClass);
						a.push('" key="'+i+'">');
						a.push('<img src="');
						a.push(colors[i].colorPath);
						a.push('" alt="');
						a.push(colors[i].name);
						a.push('" title="');
						a.push(colors[i].name);
						a.push('"></div>');
					} else {
						a.push('<div class="');
						a.push(styleClass);
						a.push('" key="'+i+'" style="background-color:#');
						a.push(colors[i].color);
						a.push(';">');
						a.push('<img src="');
						a.push(_getImageRoot());
						a.push('spacer.gif" alt="');
						a.push(colors[i].name);
						a.push('"></div>');
					}
					if (count == 3)
						count = 0;
					else
						count++;
				}
				a.push(_clear());
				a.push('</div>'); //#content-colors
			}
		}
		return a.join('');
		
	};
	
	var _bindQuickLookCommon = function(parent){
		logger.log('bind quick look common');
		$("#jsShowDescription", parent).click(function() {
			$("#item-tabs-wrap", parent).removeClass("tab2on").addClass("tab1on");
			$(".tabs-content", parent).hide();
			$("#content-description", parent).show();
		});
		
		$("#jsShowColors", parent).click(function() {
			$("#item-tabs-wrap", parent).removeClass("tab1on").addClass("tab2on");
			$(".tabs-content", parent).hide();
			$("#content-colors", parent).show();
		});
		
		$("[name=sku_id]", parent).change(function() {
			logger.log('drop down change');
			var messageDiv = $("#message-quicklook-foot", parent);
			messageDiv.empty();
			var qlSkuMsgs = saksQuickLook.getQuickLookSkuMessages();
			if (qlSkuMsgs[this.selectedIndex] != "")
				messageDiv.append(qlSkuMsgs[this.selectedIndex]);
			
			if(sksItemModel.getProductInfo('_isColorized')){
				var data = $(this).find('option:selected').attr('data-key');
				if(data){
					var colorization = sksItemModel.getProductInfo('_colorization').getObjectFromArray(data, 'name');
					var rfx = rfxInterface.getRFXInterface();
					if(rfx && colorization)
						rfx.api("productImage", "imageZoom").changeMedia(colorization.mediaId, colorization.mediaBackup);
				}
			}
			
		});
		
		var swatchContainer = $("#content-colors", parent);
		if(swatchContainer.hasClass('swatchToggle')){
			$("div.color-swatch", swatchContainer).click(function(){
				logger.log("-- COLOR SWATCH CLICK --");
				var colorization = sksItemModel.getProductInfo('_colorization')[parseInt($(this).attr('key'))];
				var rfx = rfxInterface.getRFXInterface();
				if(rfx && colorization)
					rfx.api("productImage", "imageZoom").changeMedia(colorization.mediaId, colorization.mediaBackup);	
			});
		}

		saksFindInStore.bindFISQLElements(parent);
	};
	
	var _bindQuickLook = function(parent) {
		_bindQuickLookCommon(parent);
		
		$("#jsAddToBag", parent).click(function(e){
			logger.log('Add to bag on QL click');
			e.preventDefault();
			var validData = QLFISValidator.getValidData($(this).attr('id'));
			if( validData )
				saksQuickLook.quickLookAddToBag(validData);
			else
				return false;
		});
	};
	
	var _config = {
		quicklookview : {
			data : { bmForm : 'product_array_quick_look_service' },
			success : function(json){
				logger.log('Quick look success');
				sksItemModel.setProductInfo('_productCode', json.productCode);
				sksItemModel.setProductInfo('_colorization', json.colors);
				sksItemModel.setProductInfo('_isColorized', json.colorizationInd);
				
				saksModal.viewInModal(_createQuickLookHTML(json), 468, 460);
				
				var ql = $('#quicklook');
				
				_bindQuickLook(ql);				
				_parseSocialSharingButtons(ql); // QC#1334
				
				omnitureManager.ping('quicklook', json);
			},
			complete : function(data){}
		},
		
		addtobag : {
			url : '/checkout/checkout.jsp',
			data : { bmForm : 'add_saks_suggests_item_service_product_array' },
			success : function(json){
				logger.log('Quick look ADD TO BAG success');
				if (json.errors) {
				} else {
					logger.log('break down QL after add to bag');
					if (json.errorMessages.length == 0){
						SaksBagOpen('SaksBagOverlay');
						saksModal.destroy();
					}
					else{	
						/** TO DO CHECK WHAT THE EHLL THIS IS **/
						_config.quicklookview.success(json);
						if (json.inOtherMembersCart == false && json.itemSoldOut == false)
							$('#message-quicklook-foot').text(json.errorMessages[0].message).css({"color":"#C81B1B", "font-weight":"bold"});;
					}
				
				}
			}
		}
	};
	
	return{
		onLoad : function(parent){
			requestManager.registerRequest(_config);
			this.bindQuickLookElements(parent);
		},
		bindQuickLookElements : function(parent){
			logger.log('onload of QL');
			parent = (parent) ? parent : $('#saksBody');

			$('.jsModalBox', parent).click(function(){
				logger.log('quick look PA click');
				var keyArray = $(this).attr('key').split('|');
				saksQuickLook.api.getQuicklook(keyArray[0], keyArray[1]);
				return false;
			});
		},
		
		getProductQuickLook : function( _data ){
			sksItemModel.setProductInfo('_productCode', _data.productCode);
			sksGlobalAjax.ajaxRequest( requestManager.getRequestParams('quicklookview', _data) );
		},
		quickLookAddToBag : function( _data ){
			sksGlobalAjax.ajaxRequest( requestManager.getRequestParams('addtobag', _data) );
		},

		generateItemAvailMessaging : _generateItemAvailMessaging,
		generateSwatches : _generateSwatches,
		generateQLPrices : _generateQLPrices,
		generateProductInfo : _generateProductInfo,
		generateSizeColorDropDown : _generateSizeColorDropDown,
		getQuickLookSkuMessages : function(){
			return _quickLookSkuMessages;
		},
		
		generateFBLikeButton: _generateFBLikeButton,
		generateSharingButtons: _generateSharingButtons,		
		parseSocialSharingButtons: _parseSocialSharingButtons,		
		bindQuickLookCommon : _bindQuickLookCommon,
		
		api :{
			getQuicklook : function(productCode, esreValue){
				sksItemModel.setProductInfo('_esreValue', ((esreValue) ? esreValue : null) );
				saksQuickLook.getProductQuickLook({ productCode : productCode });
			}
		}
	};
})(jQuery);

var sksItemModel = (function($){
	var _currentProduct = {
		_element : null,
		_productInfo : {
			_productCode : null,
			_productName : null,
			_skuCode : null,
			_shortDescription: null,
			_price : null,
			_quantity : null,
			_size : null,
			_color : null,
			_colorization : null,
			_isColorized : null,
			_imagePath : null,
			_size : null,
			_upc : null,
			_esreValue : null
		}		
	};
	
	var _saveFindInStoreProductInfo = function(data){
		logger.log('SAVING FIS LAYER PRODUCT INFO FROM JSON');
		_currentProduct._productInfo._productCode = data.quickLook.productCode;
		_currentProduct._productInfo._productName = data.quickLook.productName;
		_currentProduct._productInfo._skuCode = (data.quickLook.skuVariants && data.quickLook.skuVariants.length === 1) ? data.quickLook.skuVariants[0].value : null;
		_currentProduct._productInfo._shortDescription = data.quickLook.shortDescription;
		
		_currentProduct._productInfo._listPrice = data.quickLook.formattedListPrice;
		_currentProduct._productInfo._salePrice = data.quickLook.formattedSalePrice;
		_currentProduct._productInfo._listPriceLabel = data.quickLook.listPriceLabel;
		_currentProduct._productInfo._salePriceLabel = data.quickLook.salePriceLabel;
		_currentProduct._productInfo._onSaleFlag = data.quickLook.onSaleFlag;
		_currentProduct._productInfo._skuPricedDifferent = data.quickLook.skuPricedDifferent;	
		
		_currentProduct._productInfo._quantity = data.quickLook.quantity;
		_currentProduct._productInfo._imagePath = data.quickLook.images.reserveInStoreSize;
		_currentProduct._productInfo._isColorized = data.quickLook.colorizationInd;
		_currentProduct._productInfo._colorization = data.quickLook.colors;
		logger.log(_currentProduct._productInfo);
	};
	
	 var _saveStoreResultsProductInfo = function(data){
		 logger.log('SAVING STORE RESULTS PRODUCT INFO FROM JSON');
		_currentProduct._productInfo._size = data.size;
		_currentProduct._productInfo._color = data.color;
		_currentProduct._productInfo._upc = data.upcCode;
	 };
	 
	 return{
		 saveFindInStoreProductInfo : _saveFindInStoreProductInfo,
		 saveStoreResultsProductInfo : _saveStoreResultsProductInfo,
		 getProductInfoObject : function(){
		 	return _currentProduct._productInfo;
	 	 },
		 getProductInfo : function(key){
		 	return _currentProduct._productInfo[key];
	 	 },
	 	 setProductInfo : function(key, value){
	 		_currentProduct._productInfo[key] = value;
	 	 },
	 	 getElement : function(){
	 		 return _currentProduct._element;
	 	 },
	 	 setElement : function(element){
	 		_currentProduct._element = element;
	 		return _currentProduct._element;
	 	 }
	 };
})(jQuery);

var saksFindInStore = (function($){
	var _SPLITER= '--';
	var _SIZE_COLOR_PREFIX = 'pdSizeColor';
	
	var _currentStoreLocatorQuery = null;
	var _printPageElement = null;
	var _disableFISLayer = false;
	
	var _distanceVals = [10,25,50,100];
	var _getDistanceDropDown = function(radius){
		var str = '<select name="radius" id="radius">';
		for(i=0;i<=_distanceVals.length-1;i++){
			var selected = (radius == _distanceVals[i]) ? 'selected' : '';
			str = str + '<option value="' + _distanceVals[i] + '" ' + selected +'>' + _distanceVals[i] + ' Miles</option>';
		}
		str = str + '</select>';
		return str;
	};

	var _createFindInStoreHTML = function(item){
		logger.log('BUILDING FIND IN STORE LAYER HTML');
		var a = [];
		var ql = item.quickLook;
		var up = item.userPreferences;
		var colors = ql.colors;
		var soldOut = ql.itemSoldOut;
		var onProdArrayPage = location.pathname.indexOf("ProductArray.jsp");
		var onEndecaSearchPage = location.pathname.indexOf("EndecaSearch.jsp");
		
		a.push('<div id="findInStore">');
		a.push('<div id="titlebar"><h1>FIND IN STORE</h1><div id="titlebar-right">');
		
		if(onProdArrayPage > -1 || onEndecaSearchPage > -1){
			a.push('<a id="backToProductDetail">Back To Product Detail</a><span class="separator">|</span>');
		}
		
		a.push('<div class="close-wrap reverse"><a class="modal-close overlay-close">CLOSE</a></div></div></div>');
		a.push('<div class="content-left">');
		a.push('<div id="quicklook-large-image"><img id="MainImage" src="'+sksItemModel.getProductInfo('_imagePath')+'" alt="" width="180" height="240" /></div>');
		a.push('<div id="MainImageColor"></div>');
		a.push('</div>');//end content-left
		a.push('<div class="content-mid">');
		a.push('<div class="errorMsgPage"></div>');
		a.push('<h2>PRODUCT INFORMATION:</h2>');
		a.push('<b>' + ql.productName + '</b>');
		a.push('<br/>');
		a.push(ql.shortDescription);
		a.push('<br/>');
		
		a.push('<div class="item-price">');
		if(ql.onSaleFlag) {
			a.push('<span class="product-price">');
			a.push(ql.listPriceLabel);
			a.push('&nbsp;');
			a.push(ql.formattedListPrice);
			a.push('</span>');
			
			if (ql.skuPricedDifferent) {
				a.push('<p style="height: 0; margin-top: 0;"/>');
				a.push('<span class="blackBold11" style="font-weight:bold;">');
			} else {
				a.push('<span class="blackBold11" style="font-weight:bold; padding-left:5px;">');
			}
			
			a.push('<span class="blackBold11" style="font-weight:bold;">');
			a.push(ql.salePriceLabel);
			a.push('&nbsp;');
			a.push('<span class="product-sale-price">');
			a.push(ql.formattedSalePrice);
			a.push('</span></span></span>');		
		} else {
			a.push('<span class="product-price" style="font-weight:bold;">');
			a.push(ql.formattedListPrice+'</span>');
		}
		a.push('</div>');		
		
		a.push('<div class="item-sku">'+ ql.productCode + '</div>');
		var currentQty = (ql.quantity) ? ql.quantity : 1;
		a.push('<div id="quantity" class="quantity-input FISInputs"><label for="MainProductqtyToBuy0">QTY</label><input type="text" name="itemQuantity" id="MainProductqtyToBuy0" class="qty-to-buy" size="2" value="' + currentQty + '" maxlength="2" /></div>');
		a.push('<div id="qtyError" class="errorsbold"></div><div class="clearfix"></div>');
		

		a.push('<div id="selectColor" class="FISInputs">');

		a.push(saksQuickLook.generateSizeColorDropDown(ql.skuVariants));

		a.push('<div class="clearfix"></div>');
		a.push('</div>');//.quantity-input
			
		a.push('<div id="colorSizeError" class="errorsbold"></div><div class="clearfix"></div>');
		
		a.push('<div id="swatch-widget">');
		a.push('<div id="swatch-arrow-left" class="swatch-arrows" ><img src="/static/images/leftArrow.gif"></div>');
		a.push('<div id="swatch-container"><div id="swatch-inner">');
		for (var i=0; i<colors.length; i++) {
			if (colors[i].colorPath && colors[i].colorPath != "") {
				a.push('<div class="swatch-obj">');
				a.push('<img src="'+colors[i].colorPath+'" alt="'+colors[i].name+'" title="'+colors[i].name+'">');
				a.push('<div class="text">'+colors[i].name+'</div>');
				a.push('</div>');
			} else {
				a.push('<div class="swatch-obj">');
				a.push('<div class="flat-swatch" style="background-color:#'+colors[i].color+';" ></div>');
				a.push('<div>'+colors[i].name+'</div>');
				a.push('</div>');
			}
		}	
		a.push('<div class="clearfix"></div>');
		a.push('</div><div class="clearfix"></div></div>');
		a.push('<div id="swatch-arrow-right" class="swatch-arrows" ><img src="/static/images/rightArrow.gif"></div>');
		a.push('<div class="clearfix"></div>');
		a.push('</div>'); //swatch-widget
				
		a.push('</div>');//end content-mid
		a.push('<div class="content-right"><h2>STORE AVAILABILITY:</h2>');
		a.push('<div id="zipcode" class="FISInputs"><label>Zip Code</label>');
		a.push('<input type="text" name="zip" id="zip" value="'+up.zipCode+'" maxlength="5" /></div>');

		a.push('<div id="zipcodeError" class="errorsbold"></div><div class="clearfix"></div>');
		a.push('<div id="distanceToStore" class="FISInputs"><label>Distance To Store:</label>');

		a.push(_getDistanceDropDown(up.radius));
		a.push('</div>');
		a.push('<img src="/static/images/btn/button_white_submit.png" id="btnSubmit" alt="SUBMIT" title="SUBMIT">');
		a.push('<div class="content-right-messages"></div>')
		a.push('<div id="FIS-error"></div>');
		a.push('</div>');//end content right
		a.push('<div class="clearfix"></div>')
		a.push('<div id="stores-print-this-page"><a class="iconPrint">Print This Page</a></div>');
		a.push('</div>');//end findInStore
		return a.join('');
	};
	
	var _disclaimerHTML = '<div class="disclaimer"><b>Please Note: </b> This reflects current availability but our store inventory is always changing.  Prices and promotions may vary in stores.</div>';

	var _getDateTime = function(){
		var d = new Date();
		var curr_date = d.getDate();
		var curr_month = d.getMonth() + 1;
		var curr_year = d.getFullYear();
		var curr_hour = d.getHours();
		var curr_min = d.getMinutes();
		curr_min = (curr_min < 10) ? "0" + curr_min : curr_min;
		var formattedDate = curr_month + "/" + curr_date + "/" + curr_year + " " + curr_hour + ":" + curr_min + " ET";
		return formattedDate;
	};
	
	var _createFindInStoreResultsHTML = function(item) {
		logger.log('BUILDING STORE RESULTS HTML');
		var a = [];
		var sd = item.storeDetails;	
		var up = item.userPreferences;

		var d=new Date();
		
		a.push('<div id="findInStoreResults">');
		a.push('<div id="fisWrapper">');
		a.push('<div id="resultsRecap">YOUR SELECTION IS AVAILABLE IN ' + item.storesWithInventorySize + ' OF ' + item.totalStoresSize + ' STORES (Inventory information below as of ');
		if(item.timestamp)
			a.push(item.timestamp + ')</div>');
		else
			a.push(')</div>');
		a.push('<div id="itemRecap"><b>' + sksItemModel.getProductInfo('_productName') + ' </b>'+ sksItemModel.getProductInfo('_shortDescription') + ' ' + item.displayablePrice + '; ' + sksItemModel.getProductInfo('_productCode') + '; <b>Size: </b>' + sksItemModel.getProductInfo('_size') + '; <b>Color: </b>' + sksItemModel.getProductInfo('_color') + '; <b>Quantity: </b>'+sksItemModel.getProductInfo('_quantity')+'; <b>UPC: </b>' + sksItemModel.getProductInfo('_upc') + '</div>');
	
		for (var i=0; i<item.storeDetails.length; i++) {
			var ci = sd[i].contactInfo;
			var lastStyle = ( (i == item.storeDetails.length-1) || ((i+1)%3 === 0) ) ? "lastResult" : "";
			a.push('<div id="store'+i+'" class="result '+lastStyle+'"><span>');
			a.push('<div class="storeName"><a href="http://'+document.location.hostname+sd[i].homePageURL+'" target="_blank">' + sd[i].storeName + '</a></div>');
			a.push(ci.addressLine1 +'<br/>');
			a.push(ci.city + ', ' + ci.state + ' ' + ci.zipCode + '<br/>');
			a.push(ci.invPhoneNumber + '<br/>');
			a.push('<b>Distance</b>: '+ sd[i].location.distance + ' ' + sd[i].location.distanceUnit + '<br/>');
			a.push('<strong class="fis-'+sd[i].inventoryAvailabilityMessage.toLowerCase().replace(/ /g,'')+'">' + sd[i].inventoryAvailabilityMessage + '</strong><br/>');
			a.push('</span></div>');
		}

		a.push('</div>');//end findInStore
		return a.join('');
	};
	
	var _bindFindInStoreResults = function(){
		logger.log('Binding Find In Store Results events');
	}
	var isTouchDevice = function() {
		try {
		document.createEvent("TouchEvent");
		return true;
		} catch (e) {
		return false;
		}
	} 
	
	var _bindFindInStore = function(parent, data){

		$("#btnSubmit", parent).click(function(e) {
			logger.log('FIND IN STORE - SUBMIT STORE REQUEST CLICK');
			var elem = $(this);
			var validData = QLFISValidator.getValidData(elem.attr('id'), sksItemModel.getProductInfoObject());
			if( validData ){
				elem.attr('src','/static/images/icon/waiting.gif');
				saksFindInStore.getFIStoreResults({
					productCode : validData.id,
					itemQuantity : validData.qty,
					sku_id : validData.sku_id,
					zipCode : validData.zip,
					radius : validData.radius
				});
			}
		});
		
		$("#backToProductDetail", parent).click(function() {
			saksQuickLook.getProductQuickLook({ productCode : $('.item-sku').text() });
		});
		
		_printPageElement.click(function(e){
			e.preventDefault();
			window.print();
		});
		
		$("[name=sku_id]", parent).change(function() {
			logger.log('FIS -- drop down change');
			
			if(sksItemModel.getProductInfo('_isColorized')){
				var data = $(this).find('option:selected').attr('data-key');
				if(data){
					var colorization = sksItemModel.getProductInfo('_colorization').getObjectFromArray(data, 'name');
					if(colorization)
						$('#MainImage').attr('src',colorization.mediaPath);
				}
			}
			
		});
		
		!function($){
			var _leftArrow = $('#swatch-arrow-left');
			var _rightArrow = $('#swatch-arrow-right');
			var _swatchContainer = $('#swatch-container');
			var _swatchInner = $('#swatch-inner');
			var _allSwatches = $('.swatch-obj', _swatchContainer);
			
			var _totalInnerWidth = 0; 
			_allSwatches.each(function(index){
				_totalInnerWidth += $(this).outerWidth();
			});
			_swatchInner.css('width', _totalInnerWidth+3);
			
			if(_totalInnerWidth > 240){
				_leftArrow.show();
				_rightArrow.show();
			}
			var _currentPosition = _swatchInner.css( "left").split('px')[0];
			var _rightstop = -(_swatchInner.width() - _swatchContainer.width());
		
			var _scrollerOff = true;
			var _currentDirection = '-';
			var _timer = 10;
			var _distance = 1;
			var _interval = null;
			
			var _doScroll = function(){
				if(_currentDirection === '+' && parseInt(_swatchInner.css('left')) >= 0){
					clearInterval(_interval);
					_interval = null;
				}else if (_currentDirection === '-' && parseInt(_swatchInner.css('left')) <= _rightstop){
					clearInterval(_interval);
					_interval = null;
				}else{
					var newPosition = (_currentDirection === '+') ? (_currentPosition + _distance) : (_currentPosition - _distance);
					_currentPosition = newPosition;
					_swatchInner.css( "left", newPosition+'px');
				}
			};
			
			_leftArrow.hover(function(){
					if(_scrollerOff && parseInt(_swatchInner.css('left')) < 0){
						_scrollerOff = false;
						_currentDirection = '+';
						_doScroll();
						_interval = setInterval(_doScroll,_timer);
					}
				},function(){
					if(_interval){ 
						clearInterval(_interval);
						_interval = null;
					}	
					_scrollerOff = true;
				});
			
			_rightArrow.hover(function(){
				if(_scrollerOff && parseInt(_swatchInner.css('left')) > _rightstop){
					_scrollerOff = false;
					_currentDirection = '-';
					_doScroll();
					_interval = setInterval(_doScroll,_timer);
				}
				
			},function(){
				if(_interval){ 
					clearInterval(_interval);
					_interval = null;
				}
				_scrollerOff = true;
			});
			
		}($);
	};

	var _errorMessages = {
			'Invalid Zip Code' : function(){ 
				return '<div class="errorsbold"><span>Please enter a valid 5 digit US Zip Code.</span></div>';
			},
			'No Stores Found' : function(){
				return '<p class="errorsbold">Your selection is not available in any store within ' + _currentStoreLocatorQuery.radius + ' miles of '+ _currentStoreLocatorQuery.zipCode + '.<br/><br/>Please adjust your search criteria and try again.</span>';
			},
			'Not this item' : function(){
				return '<div class="errorsbold"><span>FIND IN STORE service is not available for this item.</span></div>';
			},
			'default' : function(){ 
				return '<div class="errorsbold"><span>FIND IN STORE service is not available at this time.</span></div>';
			}		
	};
	
	var _getErrorMessaging = function(errorReason){
		if(_errorMessages[errorReason])
			return _errorMessages[errorReason]();
		else
			return _errorMessages['default']();
	};
	
	var _removeOldResults = function(){$('#findInStoreResults').remove();};
	
	var _config = {
		fislayer : {
			data : { bmForm : 'saks_find_in_store_quick_look_service' },
			success : function(json){
				logger.log('Find in store layer success handler 123 123');
				
				_disableFISLayer = (!json.quickLook.skuVariants.length) ? true : false;
				
				sksItemModel.saveFindInStoreProductInfo(json);
				saksModal.viewInModal(_createFindInStoreHTML(json), 779,350);
				
				_printPageElement = $('#stores-print-this-page');
				
				if(_disableFISLayer)
					saksModal.replaceContent(_getErrorMessaging('Not this item'),779,350,'#FIS-error');
				else 
					_bindFindInStore($('#findInStore'),json);
				
				omnitureManager.ping('findinstore', json);
			},
			complete : function(json){}
		},	
		fisStoreResults : {
			data : { bmForm : 'get_stores_with_inventory' },
			success : function(json){
				logger.log('---SUCCESS HANDLER FOR STORE RESULTS---');
				
				_removeOldResults();
				saksModal.resizeModalBox(779,350);
				
				if(_printPageElement)
					_printPageElement.hide();
				
				if(json['errorReason']){
					logger.log('---ERROR CODE RETURNED ON RESULTS---');
					saksModal.replaceContent(_getErrorMessaging(json['errorReason']),779,350,'#FIS-error');
				}else if(json['storesWithInventorySize'] === 0){
					logger.log('---ZERO STORES RETURNED---');
					saksModal.replaceContent(_getErrorMessaging('No Stores Found'),779,350,'#FIS-error');
				}else{
					logger.log('---STORES RETURNED---');
					sksItemModel.saveStoreResultsProductInfo(json);
					
					saksModal.appendToModalBox(_createFindInStoreResultsHTML(json), 779, 600,'#generic-modal');
					saksModal.replaceContent(_disclaimerHTML,779,600,'#FIS-error');
					
					_bindFindInStoreResults();
					
					if(_printPageElement)
						_printPageElement.show();
					
					omnitureManager.ping('findinstoreresults', json);
				}
			},
			error : function(){
				logger.log('---STORE RESULTS ERROR HANDLER---');
				saksModal.replaceContent(_getErrorMessaging('default'),779,350,'#FIS-error');
			},
			complete : function(json){
				$('img#btnSubmit').attr('src','/static/images/btn/button_white_submit.png');
			}
		}
	};
	
	return{
		onLoad : function(parent){
			requestManager.registerRequest(_config);
			this.bindFISElements(parent);
		},
		
		bindFISElements : function(parent){
			parent = (parent) ? parent : $('#saksBody');
			
			$('.jsFindInStorePD', parent).click(function(){
				logger.log('product page click on FIND IN STORE');
				//saksFindInStore.setFISRequestContext('productDetail');
				
				// get clicked on element	
				var element = sksItemModel.setElement($(this));
				sksItemModel.setProductInfo('_productCode', element.attr('key'));
				
				//get id
				var elemID = element.attr('id');
				var commonID = elemID.split(_SPLITER).pop();
				
				//get QTY
				sksItemModel.setProductInfo('_quantity', $('#'+commonID).val() || 1);
		
				logger.log('from product detail to find in store layer QTY: '+sksItemModel.getProductInfo('_quantity'));
				
				//get SKU code
				var sizeColorValue = $('select option:selected', '#' + _SIZE_COLOR_PREFIX + _SPLITER + commonID).val();
				sksItemModel.setProductInfo('_skuCode', sizeColorValue || null );
				logger.log('from product detail to find in store layer SKU: '+sksItemModel.getProductInfo('_skuCode'));
				
				//call address
				saksFindInStore.getFISLayer({
					productCode : sksItemModel.getProductInfo('_productCode'),
					itemQuantity : sksItemModel.getProductInfo('_quantity'),
					sku_id : sksItemModel.getProductInfo('_skuCode')
				});
	
				return false;
			});			
		},
		bindFISQLElements : function(parent){
			logger.log('binding FIS QL ELEMENTS');
			
			$("#jsFindInStoreQL").click(function(e) {
				logger.log('FIS QUICK LOOK BUTTON CLICK');
				//saksFindInStore.setFISRequestContext('quicklook');
				
				var validData = QLFISValidator.getValidData($(this).attr('id'));
				if( validData ){
					saksFindInStore.getFISLayer({
						productCode : validData.id,
						itemQuantity : validData.qty,
						sku_id : validData.sku_id
					});
				}
			});
		},
		
		getFISLayer : function( _data ){
			sksGlobalAjax.ajaxRequest(  requestManager.getRequestParams('fislayer', _data) );
		},
		getFIStoreResults : function( _data ){
			_currentStoreLocatorQuery = _data;
			sksGlobalAjax.ajaxRequest( requestManager.getRequestParams('fisStoreResults', _data) );
		},
		calculateSkuValue : function(parent){
			logger.log('getting current UPC/SKU INPUT: either user selected or default');
			
			var userSelectedSku = $('.vars-to-buy option:selected', parent).val();
			if(userSelectedSku){
				logger.log('userSelectedSku 1 ---> '+userSelectedSku);
				return userSelectedSku;
			}else{
				userSelectedSku = $('input[name=sku_id]', parent).val();
				if(userSelectedSku){
					logger.log('userSelectedSku 2 ---> '+userSelectedSku);
					return userSelectedSku;
				} else {
					logger.log('current default sku---> '+sksItemModel.getProductInfo('_skuCode'));
					return sksItemModel.getProductInfo('_skuCode');
				}
			}			
		}
	};
})(jQuery);


var reserveWaiter = (function($){
	var _layer = null;
	var _waitHTML = '<div id="reserve-waiting"></div>';
	var _waiter = null;
	var _wait = function(){
		var _waiter = $('#reserve-waiting');
		if(!_waiter || _waiter.length === 0){
			_layer.css('opacity','0.6').append(_waitHTML);
			_waiter = $('#reserve-waiting');
			_waiter.show();
		}else
			_waiter.show();
			
	};
	
	return {
		display : function(){
			if(!_layer || _layer.length === 0){
				_layer = $('#generic-modal').children();
				_wait();
			}else
				_wait();
		},
		hide : function(){
			_layer.css('opacity','1');
			_waiter.hide();
		}
	};
})(jQuery);

var pageManager = (function(){
	var _pageType = document.location.href.toLowerCase();
	return{
		isPageType : function(value){
			if(_pageType.indexOf(value) > -1) return true;
		}
	};
})();

var timeStamper = (function(){
	var _generateStamp = function(){
		return new Date().getTime();
	};
	return{
		stamp : function(){
			return _generateStamp();
		}
	};
})();

var omnitureManager = (function($){
	var _trackingType = {
		_send : function(params){
			logger.log('--- SENDING DATA TO OMNITURE ---');
			var data = $.extend({}, this, params);
			logger.log(data);
			s.pageName = (data['pageName']) ? data['pageName'] : '';
			s.channel = (data['channel']) ? data['channel'] : '';
			s.prop1 = (data['prop1']) ? data['prop1'] : '';
			s.events = (data['events']) ? data['events'] : '';
			s.products = (data['products']) ? data['products'] : '';
			s.eVar42 = (data['eVar42']) ? data['eVar42'] : '';
			s.prop1 = (data['prop1']) ? data['prop1'] : '';
			void(s.t());
		},
		quicklook :{
			setup : function(dataObject){
				var params = {};
				if(dataObject){
					params.pageName = 'quicklook:' + dataObject.productName + ':' + dataObject.shortDescription;
					params.products = ';' + dataObject.productCode +';;;;evar4=Regular:' + dataObject.productName;
					params.eVar42 = ( sksItemModel.getProductInfo('_esreValue') ) ? sksItemModel.getProductInfo('_esreValue') : '';
				}
				logger.log('quick look omniture setup');
				logger.log(params);
				return params;
			},
			defaults: {
				channel : 'productArray',
				events : 'prodView',
				prop1 : 'quicklook'
			}
		},
		findinstore :{
			setup : function(dataObject){
				return {};
			},
			defaults: {
				pageName : 'find in store:landing',
				channel : 'productArray',
				events : 'event41',
				prop1 : 'quicklook'
			}
		},
		findinstoreresults :{
			setup : function(dataObject){
				return {};
			},
			defaults: {
				pageName : 'find in store:results',
				channel : 'productArray',
				events : 'event42',
				prop1 : 'quicklook'
			}
		}
	};
	
	return {
		ping : function(type, response){
			logger.log('ping with type: '+type);
			_trackingType._send.call( _trackingType[type].defaults, _trackingType[type].setup(response) );
		}
	};
})(jQuery);

var queryParamFetcher = (function($){
	var _params = {};
	var e,
    	a = /\+/g, 
    	r = /([^&;=]+)=?([^&;]*)/g,
    	d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
    	q = window.location.search.substring(1);

    while (e = r.exec(q))
    	_params[d(e[1])] = d(e[2]);
    
    var _getParamValue = function(key){
    	return _params[key];
    }
    
	return {
		getParamValue : _getParamValue
	}
})(jQuery);

var requestManager = (function($){
	var _requestParams = {
		_standardParams : {
			url : '/main/ProductDetail.jsp',
			type : 'POST',
			dataType : 'json'
		}
	};
	
	return {
		getRequestParams : function(type, _data){ 
			if(_requestParams[type]){
				return  $.extend(true, {}, _requestParams[type], {data : _data});
			}else
				logger.log('ERROR: --- REQUEST IS NOT REGISTERED ---> '+type);
		},
		registerRequest : function(_requestConfig){
			for(var key in _requestConfig){
				if(!_requestParams[key])
					_requestParams[key] = $.extend(true, {}, _requestParams['_standardParams'], _requestConfig[key]);
				else
					logger.log('ERROR: --- REQUEST IS ALREADY REGISTERED ---> '+ key);
			}			
		}
	};
})(jQuery);


var QLFISValidator = (function($){
	var _messageContainer = null;

	var _messages = {
		sizeqtyerror : '<p class="errorsbold quicklook-validation">Please select a color or size.</p>',
		sizeqtyziperror : '<p class="errorsbold quicklook-validation">Please select a color or size and ZIP.</p>'
	};
	
	var _emptyMessaging = function(){
		if(_messageContainer)
			_messageContainer.empty();
	};
	
	var _setMessaging = function(requestType, messageType){
		_messageContainer = _getmessageContainer(requestType);
		_messageContainer.append(_messages[messageType]);
	};
	
	var _getmessageContainer = function(requestType){
		if(requestType === 'btnSubmit')
			return $('#FIS-error');
		else if(requestType === 'jsAddToBag' || requestType === 'jsFindInStoreQL')
			return $('#message-quicklook-foot');
	}
	
	var _validator = {
		_isValid : function(type, currentProduct){
			_emptyMessaging();
			return _validator._validations[type](currentProduct); 
		},
		_validations : {
			btnSubmit : function(currentProduct){
				logger.log('VALIDATE DATA on click of btnsubmit BEFORE REQUESTING STORES');
				
				var parent = $('#findInStore')
				var qtyInput = $('#MainProductqtyToBuy0',parent);
				var zipInput = $('#zip',parent);
				var skuInput = $('select.vars-to-buy',parent);
				
				qtyInput.removeClass('input-error');
				zipInput.removeClass('input-error');
				skuInput.removeClass('input-error');
				
				$(".errorMsgPage").empty();
				$(".errorsbold").empty();
				$("#FIS-error").empty();
				$('#findInStoreResults').remove();
				
				var data = {
					id : currentProduct._productCode,
					qty : parseInt(qtyInput.val()) || 1,
					sku_id : saksFindInStore.calculateSkuValue(parent),
					zip : $(zipInput, parent).val(),
					radius : $('#radius option:selected', parent).val()
				};

				$(qtyInput, parent).val(data.qty);
				if( data.qty && parseInt(data.sku_id) && this.validateZip(data.zip) ){
					currentProduct._quantity = data.qty;
					currentProduct._skuCode = data.sku_id;
					return data;
				}else{

					$(".errorMsgPage").append('<span>Please check the error(s) highlighted below.</span>');
					if( this.validateZip(data.zip) == false){
						zipInput.addClass('input-error');
						$("#zipcodeError").append('<span>Please enter a valid 5 digit US Zip Code.</span>');
					}
					if(!parseInt(data.sku_id)){
						skuInput.addClass('input-error');
						$("#colorSizeError").append('<span>Please select a Color/Size.</span>');
					}
					if(!data.qty){
						qtyInput.addClass('input-error');
						$("#qtyError").append('<span>Please enter a valid Quantity.</span>');
					}
					
					saksModal.resizeModalBox(779,390);
					return false;
				}
			},
			jsAddToBag : function(currentProduct){
				logger.log('validating client side add to bag click');
				var parent = $('#quicklook');
				var data = {
					productCode : sksItemModel.getProductInfo('_productCode'),
					itemQuantity : $('#MainProductqtyToBuy0', parent).val(),
					sku_id : saksFindInStore.calculateSkuValue(parent)
				};
				if( parseInt(data.itemQuantity) > 0 && parseInt(data.sku_id) !== 0 )
					return data;
				else{
					_setMessaging('jsAddToBag', 'sizeqtyerror');
					return false;
				}
			},
			jsFindInStoreQL : function(currentProduct){
				logger.log('validating client side find in store click');
				
				var parent = $('#generic-modal');
				var data = {
					id : sksItemModel.getProductInfo('_productCode'),
					qty : $('#MainProductqtyToBuy0', parent).val(),
					sku_id : saksFindInStore.calculateSkuValue(parent)
				};
				logger.log('QL TO FIS QTY --> '+data.qty);
				logger.log('QL TO FIS SKU --> '+data.sku_id);
				data.qty = (!parseInt(data.qty)) ? 1 : data.qty;

				return data;

			},
			validateZip : function(val){
				logger.log('Validating FIS Zip code: '+val);
				var zip = $.trim(val);
				var zipLen = zip.length;
				if (zipLen == 0){
					return false;
				}else if (zipLen != 5){
					return false;
				}else if(!zip.match(/^[0-9]{5}$/)){
					return false;
				}else
					return true;
			}
		}
	};
	
	return{
		getValidData : _validator._isValid
	};
})(jQuery);

(function($){
	$(document).ready(function() {
		(window.saksQuickLook)? saksQuickLook.onLoad() : '';
		(window.saksFindInStore)? saksFindInStore.onLoad() : '';
	});
})(jQuery);


/*
 * jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/
 */

jQuery.easing.jswing=jQuery.easing.swing;jQuery.extend(jQuery.easing,{def:"easeOutQuad",swing:function(e,f,a,h,g){return jQuery.easing[jQuery.easing.def](e,f,a,h,g)},easeInQuad:function(e,f,a,h,g){return h*(f/=g)*f+a},easeOutQuad:function(e,f,a,h,g){return -h*(f/=g)*(f-2)+a},easeInOutQuad:function(e,f,a,h,g){if((f/=g/2)<1){return h/2*f*f+a}return -h/2*((--f)*(f-2)-1)+a},easeInCubic:function(e,f,a,h,g){return h*(f/=g)*f*f+a},easeOutCubic:function(e,f,a,h,g){return h*((f=f/g-1)*f*f+1)+a},easeInOutCubic:function(e,f,a,h,g){if((f/=g/2)<1){return h/2*f*f*f+a}return h/2*((f-=2)*f*f+2)+a},easeInQuart:function(e,f,a,h,g){return h*(f/=g)*f*f*f+a},easeOutQuart:function(e,f,a,h,g){return -h*((f=f/g-1)*f*f*f-1)+a},easeInOutQuart:function(e,f,a,h,g){if((f/=g/2)<1){return h/2*f*f*f*f+a}return -h/2*((f-=2)*f*f*f-2)+a},easeInQuint:function(e,f,a,h,g){return h*(f/=g)*f*f*f*f+a},easeOutQuint:function(e,f,a,h,g){return h*((f=f/g-1)*f*f*f*f+1)+a},easeInOutQuint:function(e,f,a,h,g){if((f/=g/2)<1){return h/2*f*f*f*f*f+a}return h/2*((f-=2)*f*f*f*f+2)+a},easeInSine:function(e,f,a,h,g){return -h*Math.cos(f/g*(Math.PI/2))+h+a},easeOutSine:function(e,f,a,h,g){return h*Math.sin(f/g*(Math.PI/2))+a},easeInOutSine:function(e,f,a,h,g){return -h/2*(Math.cos(Math.PI*f/g)-1)+a},easeInExpo:function(e,f,a,h,g){return(f==0)?a:h*Math.pow(2,10*(f/g-1))+a},easeOutExpo:function(e,f,a,h,g){return(f==g)?a+h:h*(-Math.pow(2,-10*f/g)+1)+a},easeInOutExpo:function(e,f,a,h,g){if(f==0){return a}if(f==g){return a+h}if((f/=g/2)<1){return h/2*Math.pow(2,10*(f-1))+a}return h/2*(-Math.pow(2,-10*--f)+2)+a},easeInCirc:function(e,f,a,h,g){return -h*(Math.sqrt(1-(f/=g)*f)-1)+a},easeOutCirc:function(e,f,a,h,g){return h*Math.sqrt(1-(f=f/g-1)*f)+a},easeInOutCirc:function(e,f,a,h,g){if((f/=g/2)<1){return -h/2*(Math.sqrt(1-f*f)-1)+a}return h/2*(Math.sqrt(1-(f-=2)*f)+1)+a},easeInElastic:function(f,h,e,l,k){var i=1.70158;var j=0;var g=l;if(h==0){return e}if((h/=k)==1){return e+l}if(!j){j=k*0.3}if(g<Math.abs(l)){g=l;var i=j/4}else{var i=j/(2*Math.PI)*Math.asin(l/g)}return -(g*Math.pow(2,10*(h-=1))*Math.sin((h*k-i)*(2*Math.PI)/j))+e},easeOutElastic:function(f,h,e,l,k){var i=1.70158;var j=0;var g=l;if(h==0){return e}if((h/=k)==1){return e+l}if(!j){j=k*0.3}if(g<Math.abs(l)){g=l;var i=j/4}else{var i=j/(2*Math.PI)*Math.asin(l/g)}return g*Math.pow(2,-10*h)*Math.sin((h*k-i)*(2*Math.PI)/j)+l+e},easeInOutElastic:function(f,h,e,l,k){var i=1.70158;var j=0;var g=l;if(h==0){return e}if((h/=k/2)==2){return e+l}if(!j){j=k*(0.3*1.5)}if(g<Math.abs(l)){g=l;var i=j/4}else{var i=j/(2*Math.PI)*Math.asin(l/g)}if(h<1){return -0.5*(g*Math.pow(2,10*(h-=1))*Math.sin((h*k-i)*(2*Math.PI)/j))+e}return g*Math.pow(2,-10*(h-=1))*Math.sin((h*k-i)*(2*Math.PI)/j)*0.5+l+e},easeInBack:function(e,f,a,i,h,g){if(g==undefined){g=1.70158}return i*(f/=h)*f*((g+1)*f-g)+a},easeOutBack:function(e,f,a,i,h,g){if(g==undefined){g=1.70158}return i*((f=f/h-1)*f*((g+1)*f+g)+1)+a},easeInOutBack:function(e,f,a,i,h,g){if(g==undefined){g=1.70158}if((f/=h/2)<1){return i/2*(f*f*(((g*=(1.525))+1)*f-g))+a}return i/2*((f-=2)*f*(((g*=(1.525))+1)*f+g)+2)+a},easeInBounce:function(e,f,a,h,g){return h-jQuery.easing.easeOutBounce(e,g-f,0,h,g)+a},easeOutBounce:function(e,f,a,h,g){if((f/=g)<(1/2.75)){return h*(7.5625*f*f)+a}else{if(f<(2/2.75)){return h*(7.5625*(f-=(1.5/2.75))*f+0.75)+a}else{if(f<(2.5/2.75)){return h*(7.5625*(f-=(2.25/2.75))*f+0.9375)+a}else{return h*(7.5625*(f-=(2.625/2.75))*f+0.984375)+a}}}},easeInOutBounce:function(e,f,a,h,g){if(f<g/2){return jQuery.easing.easeInBounce(e,f*2,0,h,g)*0.5+a}return jQuery.easing.easeOutBounce(e,f*2-g,0,h,g)*0.5+h*0.5+a}});

/*
 * jQuery Cycle Plugin (with Transition Definitions)
 * Examples and documentation at: http://jquery.malsup.com/cycle/
 * Copyright (c) 2007-2010 M. Alsup
 * Version: 2.9997 (13-OCT-2011)
 * Dual licensed under the MIT and GPL licenses.
 * http://jquery.malsup.com/license.html
 * Requires: jQuery v1.3.2 or later
 */

(function(i){var l="2.9997";if(i.support==undefined){i.support={opacity:!(i.browser.msie)}}function a(t){i.fn.cycle.debug&&f(t)}function f(){window.console&&console.log&&console.log("[cycle] "+Array.prototype.join.call(arguments," "))}i.expr[":"].paused=function(s){return s.cyclePause};i.fn.cycle=function(t,s){var u={s:this.selector,c:this.context};if(this.length===0&&t!="stop"){if(!i.isReady&&u.s){f("DOM not ready, queuing slideshow");i(function(){i(u.s,u.c).cycle(t,s)});return this}f("terminating; zero elements found by selector"+(i.isReady?"":" (DOM not ready)"));return this}return this.each(function(){var y=n(this,t,s);if(y===false){return}y.updateActivePagerLink=y.updateActivePagerLink||i.fn.cycle.updateActivePagerLink;if(this.cycleTimeout){clearTimeout(this.cycleTimeout)}this.cycleTimeout=this.cyclePause=0;var z=i(this);var A=y.slideExpr?i(y.slideExpr,this):z.children();var w=A.get();var v=k(z,A,w,y,u);if(v===false){return}if(w.length<2){f("terminating; too few slides: "+w.length);return}var x=v.continuous?10:h(w[v.currSlide],w[v.nextSlide],v,!v.backwards);if(x){x+=(v.delay||0);if(x<10){x=10}a("first timeout: "+x);this.cycleTimeout=setTimeout(function(){e(w,v,0,!y.backwards)},x)}})};function m(s,v,u){var w=i(s).data("cycle.opts");var t=!!s.cyclePause;if(t&&w.paused){w.paused(s,w,v,u)}else{if(!t&&w.resumed){w.resumed(s,w,v,u)}}}function n(s,v,t){if(s.cycleStop==undefined){s.cycleStop=0}if(v===undefined||v===null){v={}}if(v.constructor==String){switch(v){case"destroy":case"stop":var x=i(s).data("cycle.opts");if(!x){return false}s.cycleStop++;if(s.cycleTimeout){clearTimeout(s.cycleTimeout)}s.cycleTimeout=0;x.elements&&i(x.elements).stop();i(s).removeData("cycle.opts");if(v=="destroy"){r(x)}return false;case"toggle":s.cyclePause=(s.cyclePause===1)?0:1;w(s.cyclePause,t,s);m(s);return false;case"pause":s.cyclePause=1;m(s);return false;case"resume":s.cyclePause=0;w(false,t,s);m(s);return false;case"prev":case"next":var x=i(s).data("cycle.opts");if(!x){f('options not found, "prev/next" ignored');return false}i.fn.cycle[v](x);return false;default:v={fx:v}}return v}else{if(v.constructor==Number){var u=v;v=i(s).data("cycle.opts");if(!v){f("options not found, can not advance slide");return false}if(u<0||u>=v.elements.length){f("invalid slide index: "+u);return false}v.nextSlide=u;if(s.cycleTimeout){clearTimeout(s.cycleTimeout);s.cycleTimeout=0}if(typeof t=="string"){v.oneTimeFx=t}e(v.elements,v,1,u>=v.currSlide);return false}}return v;function w(z,A,y){if(!z&&A===true){var B=i(y).data("cycle.opts");if(!B){f("options not found, can not resume");return false}if(y.cycleTimeout){clearTimeout(y.cycleTimeout);y.cycleTimeout=0}e(B.elements,B,1,!B.backwards)}}}function b(s,t){if(!i.support.opacity&&t.cleartype&&s.style.filter){try{s.style.removeAttribute("filter")}catch(u){}}}function r(s){if(s.next){i(s.next).unbind(s.prevNextEvent)}if(s.prev){i(s.prev).unbind(s.prevNextEvent)}if(s.pager||s.pagerAnchorBuilder){i.each(s.pagerAnchors||[],function(){this.unbind().remove()})}s.pagerAnchors=null;if(s.destroy){s.destroy(s)}}function k(B,O,y,x,I){var G=i.extend({},i.fn.cycle.defaults,x||{},i.metadata?B.metadata():i.meta?B.data():{});var E=i.isFunction(B.data)?B.data(G.metaAttr):null;if(E){G=i.extend(G,E)}if(G.autostop){G.countdown=G.autostopCount||y.length}var t=B[0];B.data("cycle.opts",G);G.$cont=B;G.stopCount=t.cycleStop;G.elements=y;G.before=G.before?[G.before]:[];G.after=G.after?[G.after]:[];if(!i.support.opacity&&G.cleartype){G.after.push(function(){b(this,G)})}if(G.continuous){G.after.push(function(){e(y,G,0,!G.backwards)})}o(G);if(!i.support.opacity&&G.cleartype&&!G.cleartypeNoBg){g(O)}if(B.css("position")=="static"){B.css("position","relative")}if(G.width){B.width(G.width)}if(G.height&&G.height!="auto"){B.height(G.height)}if(G.startingSlide){G.startingSlide=parseInt(G.startingSlide,10)}else{if(G.backwards){G.startingSlide=y.length-1}}if(G.random){G.randomMap=[];for(var M=0;M<y.length;M++){G.randomMap.push(M)}G.randomMap.sort(function(Q,w){return Math.random()-0.5});G.randomIndex=1;G.startingSlide=G.randomMap[1]}else{if(G.startingSlide>=y.length){G.startingSlide=0}}G.currSlide=G.startingSlide||0;var A=G.startingSlide;O.css({position:"absolute",top:0,left:0}).hide().each(function(w){var Q;if(G.backwards){Q=A?w<=A?y.length+(w-A):A-w:y.length-w}else{Q=A?w>=A?y.length-(w-A):A-w:y.length-w}i(this).css("z-index",Q)});i(y[A]).css("opacity",1).show();b(y[A],G);if(G.fit){if(!G.aspect){if(G.width){O.width(G.width)}if(G.height&&G.height!="auto"){O.height(G.height)}}else{O.each(function(){var Q=i(this);var w=(G.aspect===true)?Q.width()/Q.height():G.aspect;if(G.width&&Q.width()!=G.width){Q.width(G.width);Q.height(G.width/w)}if(G.height&&Q.height()<G.height){Q.height(G.height);Q.width(G.height*w)}})}}if(G.center&&((!G.fit)||G.aspect)){O.each(function(){var w=i(this);w.css({"margin-left":G.width?((G.width-w.width())/2)+"px":0,"margin-top":G.height?((G.height-w.height())/2)+"px":0})})}if(G.center&&!G.fit&&!G.slideResize){O.each(function(){var w=i(this);w.css({"margin-left":G.width?((G.width-w.width())/2)+"px":0,"margin-top":G.height?((G.height-w.height())/2)+"px":0})})}var H=G.containerResize&&!B.innerHeight();if(H){var z=0,F=0;for(var K=0;K<y.length;K++){var s=i(y[K]),P=s[0],D=s.outerWidth(),N=s.outerHeight();if(!D){D=P.offsetWidth||P.width||s.attr("width")}if(!N){N=P.offsetHeight||P.height||s.attr("height")}z=D>z?D:z;F=N>F?N:F}if(z>0&&F>0){B.css({width:z+"px",height:F+"px"})}}var v=false;if(G.pause){B.hover(function(){v=true;this.cyclePause++;m(t,true)},function(){v&&this.cyclePause--;m(t,true)})}if(c(G)===false){return false}var u=false;x.requeueAttempts=x.requeueAttempts||0;O.each(function(){var S=i(this);this.cycleH=(G.fit&&G.height)?G.height:(S.height()||this.offsetHeight||this.height||S.attr("height")||0);this.cycleW=(G.fit&&G.width)?G.width:(S.width()||this.offsetWidth||this.width||S.attr("width")||0);if(S.is("img")){var Q=(i.browser.msie&&this.cycleW==28&&this.cycleH==30&&!this.complete);var T=(i.browser.mozilla&&this.cycleW==34&&this.cycleH==19&&!this.complete);var R=(i.browser.opera&&((this.cycleW==42&&this.cycleH==19)||(this.cycleW==37&&this.cycleH==17))&&!this.complete);var w=(this.cycleH==0&&this.cycleW==0&&!this.complete);if(Q||T||R||w){if(I.s&&G.requeueOnImageNotLoaded&&++x.requeueAttempts<100){f(x.requeueAttempts," - img slide not loaded, requeuing slideshow: ",this.src,this.cycleW,this.cycleH);setTimeout(function(){i(I.s,I.c).cycle(x)},G.requeueTimeout);u=true;return false}else{f("could not determine size of image: "+this.src,this.cycleW,this.cycleH)}}}return true});if(u){return false}G.cssBefore=G.cssBefore||{};G.cssAfter=G.cssAfter||{};G.cssFirst=G.cssFirst||{};G.animIn=G.animIn||{};G.animOut=G.animOut||{};O.not(":eq("+A+")").css(G.cssBefore);i(O[A]).css(G.cssFirst);if(G.timeout){G.timeout=parseInt(G.timeout,10);if(G.speed.constructor==String){G.speed=i.fx.speeds[G.speed]||parseInt(G.speed,10)}if(!G.sync){G.speed=G.speed/2}var J=G.fx=="none"?0:G.fx=="shuffle"?500:250;while((G.timeout-G.speed)<J){G.timeout+=G.speed}}if(G.easing){G.easeIn=G.easeOut=G.easing}if(!G.speedIn){G.speedIn=G.speed}if(!G.speedOut){G.speedOut=G.speed}G.slideCount=y.length;G.currSlide=G.lastSlide=A;if(G.random){if(++G.randomIndex==y.length){G.randomIndex=0}G.nextSlide=G.randomMap[G.randomIndex]}else{if(G.backwards){G.nextSlide=G.startingSlide==0?(y.length-1):G.startingSlide-1}else{G.nextSlide=G.startingSlide>=(y.length-1)?0:G.startingSlide+1}}if(!G.multiFx){var L=i.fn.cycle.transitions[G.fx];if(i.isFunction(L)){L(B,O,G)}else{if(G.fx!="custom"&&!G.multiFx){f("unknown transition: "+G.fx,"; slideshow terminating");return false}}}var C=O[A];if(!G.skipInitializationCallbacks){if(G.before.length){G.before[0].apply(C,[C,C,G,true])}if(G.after.length){G.after[0].apply(C,[C,C,G,true])}}if(G.next){i(G.next).bind(G.prevNextEvent,function(){return q(G,1)})}if(G.prev){i(G.prev).bind(G.prevNextEvent,function(){return q(G,0)})}if(G.pager||G.pagerAnchorBuilder){d(y,G)}j(G,y);return G}function o(s){s.original={before:[],after:[]};s.original.cssBefore=i.extend({},s.cssBefore);s.original.cssAfter=i.extend({},s.cssAfter);s.original.animIn=i.extend({},s.animIn);s.original.animOut=i.extend({},s.animOut);i.each(s.before,function(){s.original.before.push(this)});i.each(s.after,function(){s.original.after.push(this)})}function c(y){var w,u,t=i.fn.cycle.transitions;if(y.fx.indexOf(",")>0){y.multiFx=true;y.fxs=y.fx.replace(/\s*/g,"").split(",");for(w=0;w<y.fxs.length;w++){var x=y.fxs[w];u=t[x];if(!u||!t.hasOwnProperty(x)||!i.isFunction(u)){f("discarding unknown transition: ",x);y.fxs.splice(w,1);w--}}if(!y.fxs.length){f("No valid transitions named; slideshow terminating.");return false}}else{if(y.fx=="all"){y.multiFx=true;y.fxs=[];for(p in t){u=t[p];if(t.hasOwnProperty(p)&&i.isFunction(u)){y.fxs.push(p)}}}}if(y.multiFx&&y.randomizeEffects){var v=Math.floor(Math.random()*20)+30;for(w=0;w<v;w++){var s=Math.floor(Math.random()*y.fxs.length);y.fxs.push(y.fxs.splice(s,1)[0])}a("randomized fx sequence: ",y.fxs)}return true}function j(t,s){t.addSlide=function(v,w){var u=i(v),x=u[0];if(!t.autostopCount){t.countdown++}s[w?"unshift":"push"](x);if(t.els){t.els[w?"unshift":"push"](x)}t.slideCount=s.length;u.css("position","absolute");u[w?"prependTo":"appendTo"](t.$cont);if(w){t.currSlide++;t.nextSlide++}if(!i.support.opacity&&t.cleartype&&!t.cleartypeNoBg){g(u)}if(t.fit&&t.width){u.width(t.width)}if(t.fit&&t.height&&t.height!="auto"){u.height(t.height)}x.cycleH=(t.fit&&t.height)?t.height:u.height();x.cycleW=(t.fit&&t.width)?t.width:u.width();u.css(t.cssBefore);if(t.pager||t.pagerAnchorBuilder){i.fn.cycle.createPagerAnchor(s.length-1,x,i(t.pager),s,t)}if(i.isFunction(t.onAddSlide)){t.onAddSlide(u)}else{u.hide()}}}i.fn.cycle.resetState=function(t,s){s=s||t.fx;t.before=[];t.after=[];t.cssBefore=i.extend({},t.original.cssBefore);t.cssAfter=i.extend({},t.original.cssAfter);t.animIn=i.extend({},t.original.animIn);t.animOut=i.extend({},t.original.animOut);t.fxFn=null;i.each(t.original.before,function(){t.before.push(this)});i.each(t.original.after,function(){t.after.push(this)});var u=i.fn.cycle.transitions[s];if(i.isFunction(u)){u(t.$cont,i(t.elements),t)}};function e(y,s,x,A){if(x&&s.busy&&s.manualTrump){a("manualTrump in go(), stopping active transition");i(y).stop(true,true);s.busy=0}if(s.busy){a("transition active, ignoring new tx request");return}var v=s.$cont[0],D=y[s.currSlide],B=y[s.nextSlide];if(v.cycleStop!=s.stopCount||v.cycleTimeout===0&&!x){return}if(!x&&!v.cyclePause&&!s.bounce&&((s.autostop&&(--s.countdown<=0))||(s.nowrap&&!s.random&&s.nextSlide<s.currSlide))){if(s.end){s.end(s)}return}var z=false;if((x||!v.cyclePause)&&(s.nextSlide!=s.currSlide)){z=true;var w=s.fx;D.cycleH=D.cycleH||i(D).height();D.cycleW=D.cycleW||i(D).width();B.cycleH=B.cycleH||i(B).height();B.cycleW=B.cycleW||i(B).width();if(s.multiFx){if(A&&(s.lastFx==undefined||++s.lastFx>=s.fxs.length)){s.lastFx=0}else{if(!A&&(s.lastFx==undefined||--s.lastFx<0)){s.lastFx=s.fxs.length-1}}w=s.fxs[s.lastFx]}if(s.oneTimeFx){w=s.oneTimeFx;s.oneTimeFx=null}i.fn.cycle.resetState(s,w);if(s.before.length){i.each(s.before,function(E,F){if(v.cycleStop!=s.stopCount){return}F.apply(B,[D,B,s,A])})}var t=function(){s.busy=0;i.each(s.after,function(E,F){if(v.cycleStop!=s.stopCount){return}F.apply(B,[D,B,s,A])});if(!v.cycleStop){C()}};a("tx firing("+w+"); currSlide: "+s.currSlide+"; nextSlide: "+s.nextSlide);s.busy=1;if(s.fxFn){s.fxFn(D,B,s,t,A,x&&s.fastOnEvent)}else{if(i.isFunction(i.fn.cycle[s.fx])){i.fn.cycle[s.fx](D,B,s,t,A,x&&s.fastOnEvent)}else{i.fn.cycle.custom(D,B,s,t,A,x&&s.fastOnEvent)}}}else{C()}if(z||s.nextSlide==s.currSlide){s.lastSlide=s.currSlide;if(s.random){s.currSlide=s.nextSlide;if(++s.randomIndex==y.length){s.randomIndex=0}s.nextSlide=s.randomMap[s.randomIndex];if(s.nextSlide==s.currSlide){s.nextSlide=(s.currSlide==s.slideCount-1)?0:s.currSlide+1}}else{if(s.backwards){var u=(s.nextSlide-1)<0;if(u&&s.bounce){s.backwards=!s.backwards;s.nextSlide=1;s.currSlide=0}else{s.nextSlide=u?(y.length-1):s.nextSlide-1;s.currSlide=u?0:s.nextSlide+1}}else{var u=(s.nextSlide+1)==y.length;if(u&&s.bounce){s.backwards=!s.backwards;s.nextSlide=y.length-2;s.currSlide=y.length-1}else{s.nextSlide=u?0:s.nextSlide+1;s.currSlide=u?y.length-1:s.nextSlide-1}}}}if(z&&s.pager){s.updateActivePagerLink(s.pager,s.currSlide,s.activePagerClass)}function C(){var E=0,F=s.timeout;if(s.timeout&&!s.continuous){E=h(y[s.currSlide],y[s.nextSlide],s,A);if(s.fx=="shuffle"){E-=s.speedOut}}else{if(s.continuous&&v.cyclePause){E=10}}if(E>0){v.cycleTimeout=setTimeout(function(){e(y,s,0,!s.backwards)},E)}}}i.fn.cycle.updateActivePagerLink=function(s,u,t){i(s).each(function(){i(this).children().removeClass(t).eq(u).addClass(t)})};function h(x,v,w,u){if(w.timeoutFn){var s=w.timeoutFn.call(x,x,v,w,u);while(w.fx!="none"&&(s-w.speed)<250){s+=w.speed}a("calculated timeout: "+s+"; speed: "+w.speed);if(s!==false){return s}}return w.timeout}i.fn.cycle.next=function(s){q(s,1)};i.fn.cycle.prev=function(s){q(s,0)};function q(v,u){var y=u?1:-1;var t=v.elements;var x=v.$cont[0],w=x.cycleTimeout;if(w){clearTimeout(w);x.cycleTimeout=0}if(v.random&&y<0){v.randomIndex--;if(--v.randomIndex==-2){v.randomIndex=t.length-2}else{if(v.randomIndex==-1){v.randomIndex=t.length-1}}v.nextSlide=v.randomMap[v.randomIndex]}else{if(v.random){v.nextSlide=v.randomMap[v.randomIndex]}else{v.nextSlide=v.currSlide+y;if(v.nextSlide<0){if(v.nowrap){return false}v.nextSlide=t.length-1}else{if(v.nextSlide>=t.length){if(v.nowrap){return false}v.nextSlide=0}}}}var s=v.onPrevNextEvent||v.prevNextClick;if(i.isFunction(s)){s(y>0,v.nextSlide,t[v.nextSlide])}e(t,v,1,u);return false}function d(t,u){var s=i(u.pager);i.each(t,function(v,w){i.fn.cycle.createPagerAnchor(v,w,s,t,u)});u.updateActivePagerLink(u.pager,u.startingSlide,u.activePagerClass)}i.fn.cycle.createPagerAnchor=function(x,u,z,w,t){var A;if(i.isFunction(t.pagerAnchorBuilder)){A=t.pagerAnchorBuilder(x,u);a("pagerAnchorBuilder("+x+", el) returned: "+A)}else{A='<a href="#">'+(x+1)+"</a>"}if(!A){return}var v=i(A);if(v.parents("body").length===0){var y=[];if(z.length>1){z.each(function(){var D=v.clone(true);i(this).append(D);y.push(D[0])});v=i(y)}else{v.appendTo(z)}}t.pagerAnchors=t.pagerAnchors||[];t.pagerAnchors.push(v);var B=function(G){G.preventDefault();t.nextSlide=x;var F=t.$cont[0],E=F.cycleTimeout;if(E){clearTimeout(E);F.cycleTimeout=0}var D=t.onPagerEvent||t.pagerClick;if(i.isFunction(D)){D(t.nextSlide,w[t.nextSlide])}e(w,t,1,t.currSlide<x)};if(/mouseenter|mouseover/i.test(t.pagerEvent)){v.hover(B,function(){})}else{v.bind(t.pagerEvent,B)}if(!/^click/.test(t.pagerEvent)&&!t.allowPagerClickBubble){v.bind("click.cycle",function(){return false})}var C=t.$cont[0];var s=false;if(t.pauseOnPagerHover){v.hover(function(){s=true;C.cyclePause++;m(C,true,true)},function(){s&&C.cyclePause--;m(C,true,true)})}};i.fn.cycle.hopsFromLast=function(v,u){var t,s=v.lastSlide,w=v.currSlide;if(u){t=w>s?w-s:v.slideCount-s}else{t=w<s?s-w:s+v.slideCount-w}return t};function g(u){a("applying clearType background-color hack");function t(v){v=parseInt(v,10).toString(16);return v.length<2?"0"+v:v}function s(y){for(;y&&y.nodeName.toLowerCase()!="html";y=y.parentNode){var w=i.css(y,"background-color");if(w&&w.indexOf("rgb")>=0){var x=w.match(/\d+/g);return"#"+t(x[0])+t(x[1])+t(x[2])}if(w&&w!="transparent"){return w}}return"#ffffff"}u.each(function(){i(this).css("background-color",s(this))})}i.fn.cycle.commonReset=function(y,v,x,t,u,s){i(x.elements).not(y).hide();if(typeof x.cssBefore.opacity=="undefined"){x.cssBefore.opacity=1}x.cssBefore.display="block";if(x.slideResize&&t!==false&&v.cycleW>0){x.cssBefore.width=v.cycleW}if(x.slideResize&&u!==false&&v.cycleH>0){x.cssBefore.height=v.cycleH}x.cssAfter=x.cssAfter||{};x.cssAfter.display="none";i(y).css("zIndex",x.slideCount+(s===true?1:0));i(v).css("zIndex",x.slideCount+(s===true?0:1))};i.fn.cycle.custom=function(E,y,s,v,x,t){var D=i(E),z=i(y);var u=s.speedIn,C=s.speedOut,w=s.easeIn,B=s.easeOut;z.css(s.cssBefore);if(t){if(typeof t=="number"){u=C=t}else{u=C=1}w=B=null}var A=function(){z.animate(s.animIn,u,w,function(){v()})};D.animate(s.animOut,C,B,function(){D.css(s.cssAfter);if(!s.sync){A()}});if(s.sync){A()}};i.fn.cycle.transitions={fade:function(t,u,s){u.not(":eq("+s.currSlide+")").css("opacity",0);s.before.push(function(x,v,w){i.fn.cycle.commonReset(x,v,w);w.cssBefore.opacity=0});s.animIn={opacity:1};s.animOut={opacity:0};s.cssBefore={top:0,left:0}}};i.fn.cycle.ver=function(){return l};i.fn.cycle.defaults={activePagerClass:"activeSlide",after:null,allowPagerClickBubble:false,animIn:null,animOut:null,aspect:false,autostop:0,autostopCount:0,backwards:false,before:null,center:null,cleartype:!i.support.opacity,cleartypeNoBg:false,containerResize:1,continuous:0,cssAfter:null,cssBefore:null,delay:0,easeIn:null,easeOut:null,easing:null,end:null,fastOnEvent:0,fit:0,fx:"fade",fxFn:null,height:"auto",manualTrump:true,metaAttr:"cycle",next:null,nowrap:0,onPagerEvent:null,onPrevNextEvent:null,pager:null,pagerAnchorBuilder:null,pagerEvent:"click.cycle",pause:0,pauseOnPagerHover:0,prev:null,prevNextEvent:"click.cycle",random:0,randomizeEffects:1,requeueOnImageNotLoaded:true,requeueTimeout:250,rev:0,shuffle:null,skipInitializationCallbacks:false,slideExpr:null,slideResize:1,speed:1000,speedIn:null,speedOut:null,startingSlide:0,sync:1,timeout:4000,timeoutFn:null,updateActivePagerLink:null,width:null}})(jQuery);

/*
 * jQuery Cycle Plugin Transition Definitions
 * This script is a plugin for the jQuery Cycle Plugin
 * Examples and documentation at: http://malsup.com/jquery/cycle/
 * Copyright (c) 2007-2010 M. Alsup
 * Version:	 2.73
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 */
(function(a){a.fn.cycle.transitions.none=function(c,d,b){b.fxFn=function(g,e,f,h){a(e).show();a(g).hide();h()}};a.fn.cycle.transitions.fadeout=function(c,d,b){d.not(":eq("+b.currSlide+")").css({display:"block",opacity:1});b.before.push(function(k,i,j,f,g,e){a(k).css("zIndex",j.slideCount+(!e===true?1:0));a(i).css("zIndex",j.slideCount+(!e===true?0:1))});b.animIn.opacity=1;b.animOut.opacity=0;b.cssBefore.opacity=1;b.cssBefore.display="block";b.cssAfter.zIndex=0};a.fn.cycle.transitions.scrollUp=function(d,e,c){d.css("overflow","hidden");c.before.push(a.fn.cycle.commonReset);var b=d.height();c.cssBefore.top=b;c.cssBefore.left=0;c.cssFirst.top=0;c.animIn.top=0;c.animOut.top=-b};a.fn.cycle.transitions.scrollDown=function(d,e,c){d.css("overflow","hidden");c.before.push(a.fn.cycle.commonReset);var b=d.height();c.cssFirst.top=0;c.cssBefore.top=-b;c.cssBefore.left=0;c.animIn.top=0;c.animOut.top=b};a.fn.cycle.transitions.scrollLeft=function(d,e,c){d.css("overflow","hidden");c.before.push(a.fn.cycle.commonReset);var b=d.width();c.cssFirst.left=0;c.cssBefore.left=b;c.cssBefore.top=0;c.animIn.left=0;c.animOut.left=0-b};a.fn.cycle.transitions.scrollRight=function(d,e,c){d.css("overflow","hidden");c.before.push(a.fn.cycle.commonReset);var b=d.width();c.cssFirst.left=0;c.cssBefore.left=-b;c.cssBefore.top=0;c.animIn.left=0;c.animOut.left=b};a.fn.cycle.transitions.scrollHorz=function(c,d,b){c.css("overflow","hidden").width();b.before.push(function(h,f,g,e){if(g.rev){e=!e}a.fn.cycle.commonReset(h,f,g);g.cssBefore.left=e?(f.cycleW-1):(1-f.cycleW);g.animOut.left=e?-h.cycleW:h.cycleW});b.cssFirst.left=0;b.cssBefore.top=0;b.animIn.left=0;b.animOut.top=0};a.fn.cycle.transitions.scrollVert=function(c,d,b){c.css("overflow","hidden");b.before.push(function(h,f,g,e){if(g.rev){e=!e}a.fn.cycle.commonReset(h,f,g);g.cssBefore.top=e?(1-f.cycleH):(f.cycleH-1);g.animOut.top=e?h.cycleH:-h.cycleH});b.cssFirst.top=0;b.cssBefore.left=0;b.animIn.top=0;b.animOut.left=0};a.fn.cycle.transitions.slideX=function(c,d,b){b.before.push(function(g,e,f){a(f.elements).not(g).hide();a.fn.cycle.commonReset(g,e,f,false,true);f.animIn.width=e.cycleW});b.cssBefore.left=0;b.cssBefore.top=0;b.cssBefore.width=0;b.animIn.width="show";b.animOut.width=0};a.fn.cycle.transitions.slideY=function(c,d,b){b.before.push(function(g,e,f){a(f.elements).not(g).hide();a.fn.cycle.commonReset(g,e,f,true,false);f.animIn.height=e.cycleH});b.cssBefore.left=0;b.cssBefore.top=0;b.cssBefore.height=0;b.animIn.height="show";b.animOut.height=0};a.fn.cycle.transitions.shuffle=function(e,f,d){var c,b=e.css("overflow","visible").width();f.css({left:0,top:0});d.before.push(function(i,g,h){a.fn.cycle.commonReset(i,g,h,true,true,true)});if(!d.speedAdjusted){d.speed=d.speed/2;d.speedAdjusted=true}d.random=0;d.shuffle=d.shuffle||{left:-b,top:15};d.els=[];for(c=0;c<f.length;c++){d.els.push(f[c])}for(c=0;c<d.currSlide;c++){d.els.push(d.els.shift())}d.fxFn=function(m,j,l,g,i){if(l.rev){i=!i}var h=i?a(m):a(j);a(j).css(l.cssBefore);var k=l.slideCount;h.animate(l.shuffle,l.speedIn,l.easeIn,function(){var o=a.fn.cycle.hopsFromLast(l,i);for(var q=0;q<o;q++){i?l.els.push(l.els.shift()):l.els.unshift(l.els.pop())}if(i){for(var r=0,n=l.els.length;r<n;r++){a(l.els[r]).css("z-index",n-r+k)}}else{var s=a(m).css("z-index");h.css("z-index",parseInt(s,10)+1+k)}h.animate({left:0,top:0},l.speedOut,l.easeOut,function(){a(i?this:m).hide();if(g){g()}})})};a.extend(d.cssBefore,{display:"block",opacity:1,top:0,left:0})};a.fn.cycle.transitions.turnUp=function(c,d,b){b.before.push(function(g,e,f){a.fn.cycle.commonReset(g,e,f,true,false);f.cssBefore.top=e.cycleH;f.animIn.height=e.cycleH;f.animOut.width=e.cycleW});b.cssFirst.top=0;b.cssBefore.left=0;b.cssBefore.height=0;b.animIn.top=0;b.animOut.height=0};a.fn.cycle.transitions.turnDown=function(c,d,b){b.before.push(function(g,e,f){a.fn.cycle.commonReset(g,e,f,true,false);f.animIn.height=e.cycleH;f.animOut.top=g.cycleH});b.cssFirst.top=0;b.cssBefore.left=0;b.cssBefore.top=0;b.cssBefore.height=0;b.animOut.height=0};a.fn.cycle.transitions.turnLeft=function(c,d,b){b.before.push(function(g,e,f){a.fn.cycle.commonReset(g,e,f,false,true);f.cssBefore.left=e.cycleW;f.animIn.width=e.cycleW});b.cssBefore.top=0;b.cssBefore.width=0;b.animIn.left=0;b.animOut.width=0};a.fn.cycle.transitions.turnRight=function(c,d,b){b.before.push(function(g,e,f){a.fn.cycle.commonReset(g,e,f,false,true);f.animIn.width=e.cycleW;f.animOut.left=g.cycleW});a.extend(b.cssBefore,{top:0,left:0,width:0});b.animIn.left=0;b.animOut.width=0};a.fn.cycle.transitions.zoom=function(c,d,b){b.before.push(function(g,e,f){a.fn.cycle.commonReset(g,e,f,false,false,true);f.cssBefore.top=e.cycleH/2;f.cssBefore.left=e.cycleW/2;a.extend(f.animIn,{top:0,left:0,width:e.cycleW,height:e.cycleH});a.extend(f.animOut,{width:0,height:0,top:g.cycleH/2,left:g.cycleW/2})});b.cssFirst.top=0;b.cssFirst.left=0;b.cssBefore.width=0;b.cssBefore.height=0};a.fn.cycle.transitions.fadeZoom=function(c,d,b){b.before.push(function(g,e,f){a.fn.cycle.commonReset(g,e,f,false,false);f.cssBefore.left=e.cycleW/2;f.cssBefore.top=e.cycleH/2;a.extend(f.animIn,{top:0,left:0,width:e.cycleW,height:e.cycleH})});b.cssBefore.width=0;b.cssBefore.height=0;b.animOut.opacity=0};a.fn.cycle.transitions.blindX=function(d,e,c){var b=d.css("overflow","hidden").width();c.before.push(function(h,f,g){a.fn.cycle.commonReset(h,f,g);g.animIn.width=f.cycleW;g.animOut.left=h.cycleW});c.cssBefore.left=b;c.cssBefore.top=0;c.animIn.left=0;c.animOut.left=b};a.fn.cycle.transitions.blindY=function(d,e,c){var b=d.css("overflow","hidden").height();c.before.push(function(h,f,g){a.fn.cycle.commonReset(h,f,g);g.animIn.height=f.cycleH;g.animOut.top=h.cycleH});c.cssBefore.top=b;c.cssBefore.left=0;c.animIn.top=0;c.animOut.top=b};a.fn.cycle.transitions.blindZ=function(e,f,d){var c=e.css("overflow","hidden").height();var b=e.width();d.before.push(function(i,g,h){a.fn.cycle.commonReset(i,g,h);h.animIn.height=g.cycleH;h.animOut.top=i.cycleH});d.cssBefore.top=c;d.cssBefore.left=b;d.animIn.top=0;d.animIn.left=0;d.animOut.top=c;d.animOut.left=b};a.fn.cycle.transitions.growX=function(c,d,b){b.before.push(function(g,e,f){a.fn.cycle.commonReset(g,e,f,false,true);f.cssBefore.left=this.cycleW/2;f.animIn.left=0;f.animIn.width=this.cycleW;f.animOut.left=0});b.cssBefore.top=0;b.cssBefore.width=0};a.fn.cycle.transitions.growY=function(c,d,b){b.before.push(function(g,e,f){a.fn.cycle.commonReset(g,e,f,true,false);f.cssBefore.top=this.cycleH/2;f.animIn.top=0;f.animIn.height=this.cycleH;f.animOut.top=0});b.cssBefore.height=0;b.cssBefore.left=0};a.fn.cycle.transitions.curtainX=function(c,d,b){b.before.push(function(g,e,f){a.fn.cycle.commonReset(g,e,f,false,true,true);f.cssBefore.left=e.cycleW/2;f.animIn.left=0;f.animIn.width=this.cycleW;f.animOut.left=g.cycleW/2;f.animOut.width=0});b.cssBefore.top=0;b.cssBefore.width=0};a.fn.cycle.transitions.curtainY=function(c,d,b){b.before.push(function(g,e,f){a.fn.cycle.commonReset(g,e,f,true,false,true);f.cssBefore.top=e.cycleH/2;f.animIn.top=0;f.animIn.height=e.cycleH;f.animOut.top=g.cycleH/2;f.animOut.height=0});b.cssBefore.height=0;b.cssBefore.left=0};a.fn.cycle.transitions.cover=function(f,g,e){var i=e.direction||"left";var b=f.css("overflow","hidden").width();var c=f.height();e.before.push(function(j,d,h){a.fn.cycle.commonReset(j,d,h);if(i=="right"){h.cssBefore.left=-b}else{if(i=="up"){h.cssBefore.top=c}else{if(i=="down"){h.cssBefore.top=-c}else{h.cssBefore.left=b}}}});e.animIn.left=0;e.animIn.top=0;e.cssBefore.top=0;e.cssBefore.left=0};a.fn.cycle.transitions.uncover=function(f,g,e){var i=e.direction||"left";var b=f.css("overflow","hidden").width();var c=f.height();e.before.push(function(j,d,h){a.fn.cycle.commonReset(j,d,h,true,true,true);if(i=="right"){h.animOut.left=b}else{if(i=="up"){h.animOut.top=-c}else{if(i=="down"){h.animOut.top=c}else{h.animOut.left=-b}}}});e.animIn.left=0;e.animIn.top=0;e.cssBefore.top=0;e.cssBefore.left=0};a.fn.cycle.transitions.toss=function(e,f,d){var b=e.css("overflow","visible").width();var c=e.height();d.before.push(function(i,g,h){a.fn.cycle.commonReset(i,g,h,true,true,true);if(!h.animOut.left&&!h.animOut.top){a.extend(h.animOut,{left:b*2,top:-c/2,opacity:0})}else{h.animOut.opacity=0}});d.cssBefore.left=0;d.cssBefore.top=0;d.animIn.left=0};a.fn.cycle.transitions.wipe=function(s,m,e){var q=s.css("overflow","hidden").width();var j=s.height();e.cssBefore=e.cssBefore||{};var g;if(e.clip){if(/l2r/.test(e.clip)){g="rect(0px 0px "+j+"px 0px)"}else{if(/r2l/.test(e.clip)){g="rect(0px "+q+"px "+j+"px "+q+"px)"}else{if(/t2b/.test(e.clip)){g="rect(0px "+q+"px 0px 0px)"}else{if(/b2t/.test(e.clip)){g="rect("+j+"px "+q+"px "+j+"px 0px)"}else{if(/zoom/.test(e.clip)){var o=parseInt(j/2,10);var f=parseInt(q/2,10);g="rect("+o+"px "+f+"px "+o+"px "+f+"px)"}}}}}}e.cssBefore.clip=e.cssBefore.clip||g||"rect(0px 0px 0px 0px)";var k=e.cssBefore.clip.match(/(\d+)/g);var u=parseInt(k[0],10),c=parseInt(k[1],10),n=parseInt(k[2],10),i=parseInt(k[3],10);e.before.push(function(w,h,t){if(w==h){return}var d=a(w),b=a(h);a.fn.cycle.commonReset(w,h,t,true,true,false);t.cssAfter.display="block";var r=1,l=parseInt((t.speedIn/13),10)-1;(function v(){var y=u?u-parseInt(r*(u/l),10):0;var z=i?i-parseInt(r*(i/l),10):0;var A=n<j?n+parseInt(r*((j-n)/l||1),10):j;var x=c<q?c+parseInt(r*((q-c)/l||1),10):q;b.css({clip:"rect("+y+"px "+x+"px "+A+"px "+z+"px)"});(r++<=l)?setTimeout(v,13):d.css("display","none")})()});a.extend(e.cssBefore,{display:"block",opacity:1,top:0,left:0});e.animIn={left:0};e.animOut={left:0}}})(jQuery);

/*
 * jQuery TextField Plugin  	
 * Takes an element that's wrapping an input[type=text] and label 
 * element and lays the label over the input element as its 
 * placeholder. The placeholder is visible while the input field 
 * contains no value. While the input is focused the placeholder 
 * is lighten to give the user some feedback. Once some value is 
 * inserted into the input field that placeholder is hidden.
 */

(function($) {
	
	var textfield = {
		
		initialize: function ( options ) {
			return this.each( function() {
				var $this = $(this).addClass('textfield');
				var label = $this.find('> label');
				var input = $this.find('> input[type=text]');				
				label.css('line-height', input.innerHeight() + 'px');				
				input.bind('focus.texfield', textfield.focus);
				
				if (input.val()) label.addClass('hidden');
			});
		},
		
		destroy: function () {
			return this.each( function() {
				$(this).unbind('focus.textfield', textfield.focus);
			});
		},
		
		focus: function (event) {
			var input = $(this);				
			var label = input.parent().find('> label');
			var hasValue = !!input.val();			
			
			if (!hasValue) {				
				input.bind( 'keydown.textfield', textfield.change );				
				input.bind( 'input.textfield', textfield.change );
				input.bind( 'paste.textfield', textfield.change );				
				label.addClass('focus');
			}
			
			input.bind('blur.textfield', textfield.blur);
		},
		
		change: function (event) {
			var input = $(this);				
			var label = input.parent().find('label');			
			input.unbind( 'keydown.textfield', textfield.change );			
			input.unbind( 'input.textfield', textfield.change );
			input.unbind( 'paste.textfield', textfield.change );			
			label.addClass('hidden');			
		},
		
		blur: function (event) {
			
			var input = $(this);				
			var label = input.parent().find('label');
			var hasValue = !!input.val();
			
			input.unbind( 'blur.textfield', textfield.blur );
			
			if ( !hasValue ) label.removeClass('hidden').removeClass('focus');
		}
	};
	
	$.fn.textfield = function( method ) {
		
		$('html').addClass('js');
		
		if ( textfield[method] ) {
			return textfield[method].apply( this, Array.prototype.slice.call( arguments, 1 ) );
		} else if (typeof method === 'object' || !method) {
			return textfield.initialize.apply( this, arguments );
		} else {
			$.error( 'Method ' + method + ' does not exist on jQuery.textfield' );
		}
	}
})(jQuery);

//Initialize textfield object in Global Footer

(function($){	
	$(function(){
		$('#saks-bt-email-signup-form')
			.submit(function(){checkEmail(this);})
			.find('.textfield')
			.textfield(); 
	});
})(jQuery);
	
/*
 *  @requires
 *  	- jQuery
 *  	- jQuery.Cycle
 *  	- jQuery.Easing
 *  	- defined global countryCode variable
 *  
 *  @description
 *  
 *  Initializes the free shipping promotions on the global top navigation header.
 *  
 */

(function($){
	
	$('html').addClass('js');
	
	$(function(){
		
		var topNavPromo = (function () {
			
			// private interface
			
			var _intlRoot = $('#intl_free_ship_div');
			var _natlRoot = $('#free_ship_div');			
			var _isInitialized = false;
			
			var _intlCountryFsMap = {
				'BD' : 'B','KH' : 'B','CN' : 'B','HK' : 'B','IN' : 'B','JP' : 'B','MO' : 'B','NP' : 'B',
		        'PH' : 'B','SG' : 'B','KR' : 'B','LK' : 'B','TW' : 'B','TH' : 'B','VN' : 'B','CA' : 'A',
		        'AT' : 'B','BE' : 'B','BG' : 'B','CZ' : 'B','DK' : 'B','EE' : 'B','FI' : 'B','FR' : 'B',
		        'DE' : 'B','GR' : 'B','GD' : 'B','HU' : 'B','IE' : 'B','IT' : 'B','LV' : 'B','LI' : 'B',
		        'LT' : 'B','LU' : 'B','MT' : 'B','MC' : 'B','MA' : 'B','NL' : 'B','NO' : 'B','PL' : 'B',
		        'PT' : 'B','RO' : 'B','SK' : 'B','SI' : 'B','ES' : 'B','SE' : 'B','CH' : 'B','UA' : 'B',
		        'GB' : 'A','AU' : 'B','BN' : 'B','ID' : 'B','MV' : 'B','NZ' : 'B','ZA' : 'B','BH' : 'B',
		        'CY' : 'B','EG' : 'B','IL' : 'B','JO' : 'B','KW' : 'B','OM' : 'B','PK' : 'B','SA' : 'B',
		        'TR' : 'B','AE' : 'B','QA' : 'B','DM' : 'B','AG' : 'B','AR' : 'B','BB' : 'B','BZ' : 'B',
		        'BO' : 'B','BR' : 'B','CL' : 'B','CO' : 'B','CR' : 'B','DO' : 'B','EC' : 'B','SV' : 'B',
		        'GT' : 'B','HT' : 'B','HN' : 'B','JM' : 'B','MX' : 'B','NI' : 'B','PA' : 'B','PY' : 'B',
		        'PE' : 'B','SR' : 'B','TT' : 'B','AI' : 'B','AW' : 'B','BM' : 'B','KY' : 'B','GF' : 'B',
		        'GI' : 'B','GP' : 'B','GG' : 'B','IS' : 'B','JE' : 'B','MQ' : 'B','MS' : 'B','RE' : 'B',
		        'RU' : 'B','KN' : 'B','LC' : 'B','TC' : 'B'
		  	};
	   		
			var _intlCountryFsOffers = {
				A : 'promo-ukca',
				B : 'promo-world'	
			};
			
			function _setupPopUp (context) {
				
				if (!context) return;
				
				$('.FSO-close-button', context).click(function() {
					var toClose = $(this).parent().parent().attr('id');
					slideOut(toClose);
				});
				
				$('.FSO-messaging-link', '#navmenuLogo').click(function(e) {
					e.preventDefault();
					var data = $(this).attr('data-element').split('|');
					slideIn(data[0], parseInt(data[1]));				
					return false;
				});			
			}
			
			function _setupCycle (context) {
				
				if (!context) return;
				
				var fscycle = $('.FSO-cycle', context);
				
				if (!fscycle || !fscycle.length) return;
				
				var fsbanner_over = function () { fscycle.cycle('pause');	}							
				var fsbanner_out = function () { fscycle.cycle('resume'); }
				
				fscycle.cycle({
					pause: false,
					speed: 550,
					width: 580,
					timeout: 3000,
					easeIn: 'swing',
					easeOut: 'swing',
					fx: 'scrollDown'
				});
				
				fscycle.bind('mouseover', fsbanner_over);
				fscycle.bind('mouseout', fsbanner_out);
				
				
				$('.FSO-close-button', context).click(function(){
					fscycle.bind('mouseout', fsbanner_out);
					fscycle.cycle('resume');
				});
				
				$('.FSO-messaging-link', context).click(function(){
					fscycle.unbind('mouseout');	
				})
			}
			
			// public interface
			
			return {
				
				showInternational: function () {					
					if (!_isInitialized) {
						_isInitialized = true;
						var intlPromoID = _intlCountryFsOffers[ _intlCountryFsMap [countryCode] ];
			   			$('#'+intlPromoID).css({'display' : 'inline'});
			   			_intlRoot.show();
			   			_setupPopUp(_intlRoot);
			   			_setupCycle(_intlRoot)
			   			
					}			   					   		
				},
		
				showNational: function (isVisible) {
					if (!_isInitialized) {
						_isInitialized = true;
						_natlRoot.show();
						_setupPopUp(_natlRoot);
						_setupCycle(_natlRoot);						
					}
				}
			}
			
			
		})();
		
		// initialize top navigation based on country code.		
		
		if (window.countryCode && window.countryCode != "US" ) {
			$('#edit_tn').hide();
			topNavPromo.showInternational();
		} else {
			$('#edit_tn').show();
			topNavPromo.showNational();	
		}
		
	});		
})(jQuery);


//Site Wide Free Shipping Side Banner

(function($, w){	
	$(function(){		
		var isiPad = w.navigator.userAgent.match(/iPad/i) != null;	
		var hasPABanner = w.location.href.match(/(ProductArray|EndecaSearch)\.jsp/i) != null;
		var isDomestic = w.countryCode && w.countryCode == 'US';
		var _isEnabled = false;
		
		if ( !isiPad && !hasPABanner && isDomestic && _isEnabled) { // display free shipping promo for valid UA in valid pages
			
			var saks_body = $('#saksBody');
			
			if ( !saks_body.length ) return; // main container doesn't exist
			
			
			var bn_image = new Image();
			
			var bn_container = $( '<div class="mhp-side-banner-wrapper"></div>' );
			
			var bn_element = $( '<div class="mhp-side-banner" data-element="FreeShippingDetailsPopUp|500"></div>' )
				.appendTo( bn_container )
				.click(function(e) {
					e.preventDefault();
					var data = $(this).attr('data-element').split('|');
					slideIn(data[0], parseInt(data[1]));
					return false;
				});
			
			bn_container.appendTo( saks_body );
			
			bn_image.onload = function () {
				bn_element.css( 'backgroundImage', 'url(' + this.src  + ')' );				
				w.setTimeout( function(){ bn_element.animate({ left: 0 }, 600);	}, 100);
			}
			
			bn_image.src = '/static/images/promo/mhp_side_banner.jpg';
		}
	});
})(jQuery, window);
