var bnNav = {
    setCsXSLTCookie:function(yesOrNo){
        this.setCookie("csxslt",yesOrNo);
    },
    checkIfSupported: function(){
       XslParams.paramsCollection["transform"] = "y";
       var result = XmlUtil.xslTransform("/include/xxl/navbar/navTest.xml","/include/xxl/navbar/navTest.xsl");
       if (result && result=="Pass")
            this.setCsXSLTCookie("yes");
       /*if (result.firstChild) {
            if (result.firstChild.nodeValue=="Pass")
                this.setCsXSLTCookie("yes"); 
       }
       else if (result=="Pass") {
            this.setCsXSLTCookie("yes");
       }*/
    },
    render: function(xmlUrl,xslUrl){
        var nav = XmlUtil.xslTransform(xmlUrl,xslUrl,"navContainer");     
        if (nav==null)
            this.setCsXSLTCookie("no");
        /*    
        if (document.getElementById("promo") && document.getElementById("promo").textContent) {
            document.getElementById("promo").innerHTML = document.getElementById("promo").textContent;    
        }
        */
    },
    getCookie: function(Name) {
        var search = Name + "="   
        if (document.cookie.length > 0) { // if there are any cookies 
             offset = document.cookie.indexOf(search)       
             if (offset != -1) { // if cookie exists          
             offset += search.length          
             // set index of beginning of value 
             end = document.cookie.indexOf(";", offset)          
             // set index of end of cookie value         
             if (end == -1)             
 	            end = document.cookie.length         
	            return unescape(document.cookie.substring(offset, end))      
	            }    
            }
    },
    setCookie: function(c_name,value,days) {
        if(days){
            (time = new Date()).setTime(new Date().getTime()+days*24*60*60*1000);
            var exp = '; expires='+time.toGMTString();
        }else{
            var exp='';
        }
        document.cookie=c_name+"="+value+exp+"; domain=barnesandnoble.com;path=/";
    },
    buildPromo: function(PID, isMember, sourceID) {
		elm = document.getElementById('hb-members');
		if (!elm) return;
		
		var cdsPage = "http://www.barnesandnoble.com/promo/cds_bannerpromo.asp?PID=";
		if (isMember)
		    cdsPage = "http://www.barnesandnoble.com/promo/cds_bannerpromo_mbr.asp?PID=";
		
		elm.removeAttribute("style");
		
		elm.innerHTML = "";
		var promoIframe = document.createElement("iframe");
		promoIframe.setAttribute("id","promoIframe");
		if (sourceID=="") {
			promoIframe.src = cdsPage + PID;
        } else {
			promoIframe.src = cdsPage + PID + "&xx=" + sourceID;
        }	
		promoIframe.scrolling = "no";
        promoIframe.setAttribute("frameBorder", 0);
        elm.appendChild(promoIframe);
     }
}

// ************************************************************************************************
// The following code is for the iframed CDS promo on Search Results and Product Pages
// ************************************************************************************************

var jsIframe_js = true;

function makeIframeWithPID (pid, host, url, qs, width, height, kw, kwZone) {
	var iSrc;
	var iHost;
	var iURL;
	var iQS;
	var iWidth;
	var iHeight;
	var iKw;
	var sKwZone;
	
	if (!host) {
		iHost = "www.barnesandnoble.com";
	} else {
		iHost = host;	
	}
	if (!url) {
		iURL = "newsletters/kmp_iframe_cds2.asp";
	} else {
		iURL = url;	
	}
	if (!qs) {
		iQS = "";
	} else {
		iQS = "&"+qs;	
	}
	if (!width) {
		iWidth = "192";
	} else {
		iWidth = width;	
	}
	if (!height) {
		iHeight = "183";
	} else {
		iHeight = height;	
	}
	
	if (!kw) {
		iKw = "";
	} else {
		iKw = "&kw="+kw;	
	}

	if (!kwZone) {
		sKwZone = "";
	} else {
		sKwZone = "&kwzone="+kwZone;	
	}	
	
	if (!pid) {
		alert("A PID is required to create the js iframe!");
		return(true);
	} else if (!IsNumeric(pid)) {
		alert("The PID must be numeric to create the js iframe!");
		return(true);	
	} else {
		document.write("<iframe src=\"http://" + iHost + "/" + iURL + "?pid=" + pid + iQS + iKw + sKwZone + "\" width=\"" + iWidth + "\" height=\"" + iHeight + "\" frameborder=\"0\" marginheight=\"0\" marginwidth=\"0\" scrolling=\"no\"\/><\/iframe>");
		return(true);
	}			
}

function IsNumeric(sText) {
	var ValidChars = "0123456789";
	var IsNumber=true;
	var Char;
	for (i = 0; i < sText.length && IsNumber == true; i++) { 
		Char = sText.charAt(i); 
		if (ValidChars.indexOf(Char) == -1) {
			IsNumber = false;
		}
	}
	return IsNumber;
}

jQuery(function() {
	// Log non-b2b links in the B2B sites
	var LOG_SERVICE_URL = "http://www.barnesandnoble.com/include/inc_tracker.asp?type=1&";

	var logInvalidUrl = function(sourceUrl, invalidUrl, textUrl) {
		var now = new Date().getTime(); // to refresh the URL (avoid caching from the browser)
		var logStr = "URL=" + encodeURIComponent(invalidUrl) + 
					"&TXT=" + encodeURIComponent(textUrl) +
					"&TS=" + now;
		var imgObj = new Image();
		imgObj.src = LOG_SERVICE_URL + logStr;
	};

	var isB2B = /btob/.test(document.domain);
	//debugging -- remove for production
	// isB2B = true;
	if (!isB2B){
		return false;
	}

	$('a').each(function() {
			var btobp = this.href.match(/[^\/]+\/\/btob[^\/]+barnesandnoble\.com/);
			var emptyp = this.href === '';
			var jsp = this.href.match(/^javascript:/);
			var dhtmlp = emptyp || jsp;
			var vendorp = ! dhtmlp && (null === this.href.match(/[^\/]+\/\/[^\/]*barnesandnoble\.com/));
			var publicdocs = this.href.match(/images.barnesandnoble.com/); // allow access to resources such as *.doc, *.pdf from imagehost.
			
			var seeInside = this.href.match(/BookViewer/);
			
			if (!(btobp || dhtmlp || vendorp) && !publicdocs) {

				if (typeof console == 'object' && console.firebug) {
					console.log('Found and blocked: %o', this);
				}

				var link = $(this);

				link.attr({onclick: ''});

				link.click(function() {
					var notify = new $.Overlay({block: 0, useHeading: 1, heading: 'Not Available'});
					var msg = seeInside? "This feature is not available through this microsite. " : "This product is not available for purchase through this microsite. ";
					notify.set.content("<p style='padding:0.5em'>" + msg + "Please close this window to continue shopping.</p>");
					notify.set.width("300px");
					notify.open();
					$('.overlayClose').click(function(){notify.close();notify.remove();});

					// Log error
					var invalidLink = link.attr('href');
					var invalidLinkText = link.text();
					logInvalidUrl(document.location, invalidLink, invalidLinkText);

					return false;
				});
			}
		});
		return false;
	}
);


var BN_Analytics = (function() {
	var optimostEnabled = true;
	var pageName = "";
	
	return {
		'setOptimostEnabled' : function(e) { optimostEnabled = e; },
		'isOptimostEnabled' : function() { return optimostEnabled; },
		'getPageName' : function() { return pageName; },
		'setPageName' : function(n) { pageName = n; }
	};
})();

var BN_Analytics_Optimost = {
	isEnabled : function() {
		// Enable If Optimost is enabled and the page name is defined
		var enabled = BN_Analytics.isOptimostEnabled() && (BN_Analytics.getPageName() != "");
		return enabled;
	},
	
	/*
	 *	Optimost Page Code (Global Code/small library, inserted at every page)
	 */
	optimostPageCode : function() {
	
		if (BN_Analytics.isOptimostEnabled()) { // regardless of the page name (since it's usually not defined before this call unfortunately)
		
			optimost={A:{},C:{},D:document,L:document.location,M:[],Q:{},T:new Date(),U:'',V:'2.7',Enabled:true,ST:"script",SA:
			{"type":"text/javascript"},I:function(){var s=this.L.search;var c=this.D.cookie;if(s.length>3){for(var a=s.substring(1)
			.split("&"),i=0,l=a.length;i<l;i++){var p=a[i].indexOf("=");if(p>0)this.Q[a[i].substring(0,p)]=unescape(a[i].substring(
			p+1));}}if(c.length>3){for(var a=c.split(";"),i=0,b=a.length;i<b;i++){var v=a[i].split("=");while(v[0].substring(0,
			1)==" ")v[0]=v[0].substring(1,v[0].length);if(v.length==2)this.C[v[0]]=unescape(v[1]);}}},B:function(){var n;this.A={
			};var _o=this;this.A.D_ts=Math.round(_o.T.getTime()/1000);this.A.D_tzo=_o.T.getTimezoneOffset();this.A.D_loc=_o.L.protocol+
			"//"+_o.L.hostname+_o.L.pathname;this.A.D_ckl=_o.D.cookie.length;this.A.D_ref=_o.D.referrer;if(typeof optrial=="object")
			for(n in optrial)this.A[n]=optrial[n];for(n in this.Q)this.A[n]=this.Q[n];for(n in this.C)if(n.substring(0,2)=="op")this.A[n]=
			this.C[n];},S:function(){var q='';for(var n in this.A)if(this.A[n]!=null && this.A[n]!="")q+=(q.length>0?"&":(this.U.indexOf(
			"?")>0?"&":"?"))+n+"="+escape(this.A[n]);return this.U+q;},SC:function(n,v,e,d){var de=new Date();de.setTime(
			de.getTime()+e * 1000);this.D.cookie=n+"="+escape(v)+((e==null)?"":("; expires="+de.toGMTString()))+"; path=/"+((d==
			null)?"":(";domain="+d));},SLD:function(){var sld=this.D.domain;var dp=sld.split(".");var l=dp.length;if(l<2)sld=null;
			else if(!isNaN(dp[l-1])&&!isNaN(dp[l-2]))sld=null;else sld="."+dp[l-2]+"."+dp[l-1];return sld;},R:function(r,c,d,
			e){if(this.Enabled){var b=true;if(r<1000){b=(Math.floor(Math.random()*1000)<r);if(c!=null){if(this.C[c]!=null)b=(this.C[c]!=
			"mvt-no");else this.SC(c,b?"mvt-yes":"mvt-no",e,d);}}if(b){var t='<'+this.ST+' src="'+this.S()+'"';for(n in this.SA)
			t+=(" "+n+'="'+this.SA[n]+'"');t+='><\/'+this.ST+'>';this.D.write(t);}}},addModule:function(s,f){this.M[s]=f;
			},displayModule:function(s){if(typeof this.M[s]=="function")this.M[s]();},hasModules:function(){return count(this.M)>0;
			}};optimost.I();
		}
	},
	
	/*
	 *	Optimost Selector Code (within the head if possible, or as close to the top of the <body> and way before the test HTML area)
	 */
	optimostSelector : function optimostSelector() {
		if (BN_Analytics_Optimost.isEnabled()) {
			//alert("optimostSelector: " + BN_Analytics.getPageName() );
			var optPath = "http://es.optimost.com/";
			if(window.location && window.location.protocol && window.location.protocol.toLowerCase().indexOf("https") > -1)optPath = "https://by.essl.optimost.com/";
			document.write('<script type="text/javascript" src="' + optPath + 'es/591/c/3/u/Optimost_Selector.js' +'"><\/script>');
		}
	},
	
	/*
	 *	Optimost Module Code (bottom of every page, though above Google Analytics)
	 */
	optimostModule : function() {
		if (BN_Analytics_Optimost.isEnabled())
		{
			//alert("optimostModule: " + BN_Analytics.getPageName() );
			if (typeof(optimost) == "object" && typeof(opModulesArray) != "undefined")
			{
				for(var i=0;i<opModulesArray.length;i++)
				{
					optimost.displayModule(opModulesArray[i]);
				}
			}			
		}
	}
};

var optimost = {}; // Global variable used by Optimost

BN_Analytics_Optimost.optimostPageCode();