//replicating some procedural crap
function stripQuotes(inText) {
	inText = inText.toString(); //convert our input text to a string
	var safeText = "";
	safeText = inText.replace("'", "&#39;"); //escape all single quotes
	safeText = inText.replace(/"/g, ""); // remove all double quotes
	return safeText;
}

function logOnboardEvent(ctype, etype) {//just in case for now
	onboard.logOnboardEvent(ctype, etype);
}

var onboard = {
	visibleServerPref : true,
	visiblePref : true,
	visible : false,
	visibleReturn : true,
	toggleObject : null,
	uurl : "http://home.napster.com/cgi-bin/campaignMessager",
	
	logOnboardEvent: function(ctype, etype) {
		var obEventStr = 's.eVar5="' + ctype + '";';
		obEventStr += 's.eVar4="onboard";';
		obEventStr += 's.eVar3=s.PageName;';
		obEventStr += 's.eVar1="' + etype + '";';
		obEventStr += 's.eVar17="' + ctype + ":" + etype + '";';
		$SCEG('OnboardEvents',obEventStr);
	},
	
	ohelpPop: function(id, help_id) {
		if (typeof(id) == "undefined") {id = "other";}
		if (typeof(help_id) == "undefined") {help_id = 0;}
		help_id = parseInt(help_id);
		onboard.logOnboardEvent("moreInfo", id);
		helpPop(help_id);
	},
	
	initToggle: function() {//have to set this separately because of load timing
		onboard.toggleObject = new dojo.fx.Toggler({
			node : dojo.query("#onboard_body")[0],
			showFunc: dojo.fx.wipeIn,
			hideFunc: dojo.fx.wipeOut,
			showDuration : 700,
			hideDuration : 700
		});
	},
	
	toggle: function(e) {
		var obActButton = dojo.query("#onboard_footer a")[0];
		if (onboard.visible) {
			onboard.toggleObject.hide();
			if (dojo.isIE == 6) {
				obActButton.innerHTML = "OPEN";
			} else {
				obActButton.className = "actOpen";
			}
		} else {
			onboard.toggleObject.show();
			if (dojo.isIE == 6) {
				obActButton.innerHTML = "CLOSE";
			} else {
				obActButton.className = "actClose";
			}
		}
		
		onboard.visible = !onboard.visible;
		onboard.visibleReturn = onboard.visible;
		onboard.clientOnboardVis();
		
		if (dojo.query("#tb_close")[0]) {
			dojo.query("#tb_close")[0].innerHTML = (onboard.visible) ? "[ - ]" : "[ + ]";
		}
	},
	
	trackToggle: function() {
		onboard.logOnboardEvent("closeCurtain", onboard.visible);
		onboard.toggle();
	},
	
	clientOnboardVis: function() {
		if (isClient()) {
			var upvis = (onboard.visible) ? '1' : '0';
			updateCookieHash('SDAT','OBVIS', upvis);
		}
	},
	
	init: function() {
		onboard.visible = false;
	
		var obBody = dojo.query("#onboard_body")[0];
		var obActButton = dojo.query("#onboard_footer a")[0];
		var obFooterSub = dojo.query("#onboard_footer_sub")[0];
		
		onboard.initToggle();

		if (dojo.isIE == 6) {
			obActButton.innerHTML = (onboard.visible) ? "CLOSE" : "OPEN";
		} else {
			obActButton.className = (onboard.visible) ? "actClose" : "actOpen";
		}
	
		obActButton.onclick = function() {//dojo gets sad in the client when you use connect
			onboard.trackToggle();
		}
		dojo.connect(obFooterSub, "onclick", onboard.trackToggle);
		obFooterSub.style.cursor = "pointer";
		
		if (isClient()) {//client return vis check
			var SDAT = getCookieHash('SDAT');
			onboard.visibleReturn = !(SDAT['OBVIS'] == "0");
		}
		
		onboard.load(onboard.uurl, "onboard_body_sub", "onboard.postHTML()");
	},
	
	load: function(obUrl, target, postFunction) {
		var getObHTML = dojo.xhrGet({
			preventCache: true,
			handleAs: "json",
			url: obUrl,
			error: function(response, ioArgs) {
				return response;
			},
			load: function(response, ioArgs) {
				if (response.content == "" || response.content == null) { return response; }

				dojo.byId("onboard_bar").style.display = "block";
				var target_content_node = dojo.byId(target);
				
				if (!isClient()) {
					//console.log("i should write: " + response.content);
					var web_loader = dojo.byId("loader");
					console.log("my web_loader: " + web_loader);
					web_loader.innerHTML = response.content;
					
					fixLinks(web_loader);
					
					if (response.status == "0") {
						onboard.visibleServerPref = false;
					}
					var ldd_style_node;
					if (document.getElementById("importStyles")) {
						ldd_style_node = dojo.query("#importStyles", web_loader)[0];
					} else { 
						//this is here for Safari
						var doc = (new DOMParser()).parseFromString(response.content, "text/xml");
						ldd_style_node = doc.getElementById("importStyles")?doc.getElementById("importStyles").cloneNode(true):"";
					}
		
					if (dojo.byId(target + "Styles")) {
						document.getElementsByTagName("head")[0].removeChild(dojo.byId(target + "Styles"));
					}
					ldd_style_node.setAttribute('id', target + "Styles");
					document.getElementsByTagName("head")[0].appendChild(ldd_style_node);
		
					target_content_node.innerHTML = dojo.query("#main", web_loader)[0].innerHTML;
					
					web_loader.innerHTML = "";
				} else {
					var target_style_node = dojo.byId("importStyles");
					
					var ob_load_div = document.createElement('div');
					ob_load_div.id = "ob_loader";
					ob_load_div.style.display = "none";
					ob_load_div.innerHTML = response.content;
					
					//NOTE: don't have access to getElementById so you have to loop "by hand"
					//also, in other lameness you must put styles into the page before content 
					//(thus the 2 for loops) or else it will break
					for ( i = 0; i < ob_load_div.childNodes.length; i++ ) {
						if (ob_load_div.childNodes[i].id == "importStyles") {
							ob_load_div.childNodes[i].id = "importStyles_x";
							document.getElementsByTagName("head")[0].appendChild(ob_load_div.childNodes[i]);
						}
					}
					
					for ( i = 0; i < ob_load_div.childNodes.length; i++ ) {
						if (ob_load_div.childNodes[i].id == "main") {
							if (response.status == "0") {
								onboard.visibleServerPref = false;
							}
							target_content_node.innerHTML = ob_load_div.childNodes[i].innerHTML;
						}
					}
					ob_load_div.parentNode.removeChild(ob_load_div);
					fixLinks(target_content_node);
				}

                                //site cat hack
                                var obNum = response.id;
                                // obNum++;
                                var fakeSCUrl = "info/onboard/" + obNum + ".html";
                                runSCPageLoad(fakeSCUrl);

                                return response;
			}
		});
		
		getObHTML.addCallback(
			function(result) {
				//console.log("getWebObHTML callback");
				eval(postFunction);
				return result;
			}
		);
	},
	
	postHTML: function() {
		dojo.query("#onboard_footer_sub")[0].innerHTML = dojo.query("#obcore_footer")[0].innerHTML;
		dojo.query("#tb_close")[0].onclick = function() {
			onboard.trackToggle();
		}
		
		var obPreferenceCheckbox = dojo.query("#obcore_showPreference")[0];
		if (typeof(obPreferenceCheckbox) != "undefined") {
			obPreferenceCheckbox.onclick = function () {
				onboard.preference.updateVisible(this.checked);
			}
		}
		
		var getVisiblePref = dojo.xhrGet({//MATTFIX - replace with a better preference.get when you can
			url: "http://home.napster.com/cgi-bin/userData?id=1&format=json",
			handleAs: "json",
			preventCache: true,
			error: function(response, ioArgs) {
				onboard.visiblePref = true;
				return response;
			},
			load: function(response, ioArgs) {
				onboard.visiblePref = (response["content"]["1"] == null) ? true : response["content"]["1"];
				return response;
			}
		});
		
		getVisiblePref.addCallback(
			function(result) {
				//setting checkbox - do this before the override
				dojo.query("#obcore_showPreference")[0].checked = !onboard.visiblePref;
				onboard.visiblePref = (onboard.visiblePref) ? onboard.visibleServerPref : onboard.visiblePref; //for serverprefs - userprefs override
				if(onboard.visiblePref && onboard.visibleReturn) {onboard.toggle();}
				return result;
			}
		);
	},
	
	modBoxHeight: function(heightMod, operator) {//MATTFIX
		if (typeof(heightMod) == "undefined") {return;}
		if (typeof(operator) == "undefined") {operator = "add"}
		var obSubShell = dojo.byId("onboard_body_sub");
		var exh = dojo.style(obSubShell, "height");
		exh = (operator == "add") ? exh + heightMod : exh - heightMod;
		exh = exh + "px";
		dojo.style(obSubShell, "height", exh);
		
	},
	
	preference: {
		url: "http://home.napster.com/cgi-bin/userData",
		updateVisible:	function(hideOb) {
			onboard.logOnboardEvent("dontShowMeAgain", hideOb);
			this.set(1, !hideOb);
			if(hideOb) {onboard.toggle();}
		},
		set: function(id, myPref) {
			//add arg check
			var myUrl = this.url + "?id=" + id + "&value=" + myPref;
			dojo.xhrGet({
				url: myUrl,
				error: function(response, ioArgs) {
					//console.log("failed onboard.preference.set");
					return response;
				},
				load: function(response, ioArgs) {
					//console.log("successful onboard.preference.set");
					return response;
				}
			});
		}
	},
	
	billboard: {
		err1: true,
		error: function(msg) {
			if (typeof(msg) == "undefined") {return;}
			var eb = dojo.byId("obcore_billboard_errorbox");
			eb.style.display = "block";
			dojo.query("span", eb)[0].innerHTML = msg;
			var cmHeight = dojo.style(eb, "marginBottom") + dojo.style(eb, "marginTop") + dojo.style(eb, "height");
			if (onboard.billboard.err1) onboard.modBoxHeight(cmHeight); //MATTFIX
			onboard.billboard.err1 = false;
		},
		
		check: function(val) {
			if (val.length != 4) {
				onboard.billboard.error("Please enter a 4 digit year");
				return false;
			}
			var yearPattern = /(19(5[5-9]|[6-9]\d)|200[0-8])/;
			var yearResult = val.search(yearPattern);
			
			if (yearResult != 0) {
				onboard.billboard.error("Please enter a year between 1955 and 2008");
				return false;
			} else {
				onboard.logOnboardEvent("billboardGo", true);
				onboard.preference.set(2, val);
				if(isClient()) {
					var clurl = "http://opcode.napster.com/?op=switch&tab=browse&type_id=billboard&result_type=track&select_by=chart&select_value=6&year=" + val + "&seasoncode=SP&format=json&count=10&index=0&clickSource=onboard";
					self.location = clurl;
				} else {
					var url = "http://home.napster.com/cgi-bin/searchXML?type_id=billboard&result_type=track&select_by=chart&select_value=6&year=" + val + "&seasoncode=SP&format=json&count=10&index=0&clickSource=onboard";
					navigate(url);
					//hacky open and set sidenav
					var menuItemRef = dojo.query("#bar3 li a").some(
						function f(x) {
							if (x.innerHTML == "Hot 100 Tracks") {
								var xxul = x.parentNode.parentNode;
								var xxli = xxul.parentNode;
								xxul.style.display = "block";
								xxli.className = "arrow_d";
								gStickyToggle(x);
							};
							return (x.innerHTML == "Hot 100 Tracks");
						}
					);
				}
			}
		}
	},
	
	automix: {
		err1: true,
		error: function(msg) {
			if (typeof(msg) == "undefined") {return;}
			var eb = dojo.byId("obcore_automix_errorbox");
			var rb = dojo.byId("obcore_automix_resultbox");
			
			var rmHeight = dojo.style(rb, "paddingBottom") + dojo.style(rb, "paddingTop") + dojo.style(rb, "marginBottom") + dojo.style(rb, "marginTop") + dojo.style(rb, "height");
			if (rb.style.display == "block") onboard.modBoxHeight(rmHeight, "subtract"); //MATTFIX
			onboard.automix.err2 = true;
			
			rb.style.display = "none";
			eb.style.display = "block";
			
			dojo.query("span", eb)[0].innerHTML = msg;
			var cmHeight = dojo.style(eb, "marginBottom") + dojo.style(eb, "marginTop") + dojo.style(eb, "height");
			if (onboard.automix.err1) onboard.modBoxHeight(cmHeight); //MATTFIX
			onboard.automix.err1 = false;
			return false;
		},
		
		err2: true,
		results: function(html) {
			if (typeof(html) == "undefined") {return;}
			
			var eb = dojo.byId("obcore_automix_errorbox");
			var rb = dojo.byId("obcore_automix_resultbox");
			
			var emHeight = dojo.style(eb, "paddingBottom") + dojo.style(eb, "paddingTop") + dojo.style(eb, "marginBottom") + dojo.style(eb, "marginTop") + dojo.style(eb, "height");
			if (eb.style.display == "block") onboard.modBoxHeight(emHeight, "subtract"); //MATTFIX
			onboard.automix.err1 = true;
			
			eb.style.display = "none";
			rb.style.display = "block";
			
			dojo.query("ul", rb)[0].innerHTML = html;
			
			var cmHeight = dojo.style(rb, "paddingBottom") + dojo.style(rb, "paddingTop") + dojo.style(rb, "marginBottom") + dojo.style(rb, "marginTop") + dojo.style(rb, "height");
			if (onboard.automix.err2) onboard.modBoxHeight(cmHeight); //MATTFIX
			onboard.automix.err2 = false;
			return false;
		},

		clearMessages: function() {
			var eb = dojo.byId("obcore_automix_errorbox");
			var rb = dojo.byId("obcore_automix_resultbox");
			
			var emHeight = dojo.style(eb, "paddingBottom") + dojo.style(eb, "paddingTop") + dojo.style(eb, "marginBottom") + dojo.style(eb, "marginTop") + dojo.style(eb, "height");
			if (eb.style.display == "block") {
				onboard.modBoxHeight(emHeight, "subtract");
				eb.style.display = "none";
				onboard.automix.err1 = true;
			}
			
			var rmHeight = dojo.style(rb, "paddingBottom") + dojo.style(rb, "paddingTop") + dojo.style(rb, "marginBottom") + dojo.style(rb, "marginTop") + dojo.style(rb, "height");
			if (rb.style.display == "block") {
				onboard.modBoxHeight(rmHeight, "subtract");
				rb.style.display = "none";
				onboard.automix.err2 = true;
			}
		},

		check: function(val) {
			var mySearch = encodeURIComponent(stripQuotes(val));
			var popularityThreshold = 2000;
			var searchUrl = "http://home.napster.com/search-cgi/searchByNameXML?type=artist&search_string=" + mySearch + "&count=5&index=0&enc=utf8&COUNTRYCODE=US&EXPLICIT=Y&format=json";
			onboard.preference.set(3, val);
			
			var passId = "";
			
			var getAutomixArtists = dojo.xhrGet({
				url: searchUrl,
				handleAs: "json",
				error: function(response, ioArgs) {
					//alert("failed getAutomixArtists-xhr");
					onboard.automix.error("There was an error with your search, please try again later.");
					return response;
				},
				load: function(response, ioArgs) {
					//console.log("successful getAutomixArtists-xhr");
					return response;
				}
			});
			
			getAutomixArtists.addCallback(function(result) {
				var myLis = "";
				if (result["result"] != null) {
					for ( i = 0; i < result["result"].length; i++ ) {
						passId = new String(result["result"][i]["artist_id"]);
						if (result["result"][i]["artist_popularity"] >= popularityThreshold) {
							onboard.logOnboardEvent("automix", "play");
							onboard.automix.clearMessages();
							Play(passId,'4','1');
							break;
						} else {
							myLis += "<li><a href=\"#\" onclick=\"onboard.logOnboardEvent('automix', 'play'); Play(" + passId + ",'4','1'); return false;\">" + result["result"][i]["artist_name"] + "<\/a><\/li>";
							if (i == (result["result"].length-1)) {
								onboard.automix.results(myLis);
							}
						}
					}
				} else {
					onboard.automix.error("Sorry, no matches were found for your search.");
				}
			});
			return false;
		}
	}
}

function ob_helpPop(id, help_id) {
	if (typeof(id) == "undefined") {id = "other";}
	if (typeof(help_id) == "undefined") {help_id = 0;}
	help_id = parseInt(help_id);
	logOnboardEvent("moreInfo", id);
	helpPop(help_id);
}

