// -------------------------
//     tuner events
// -------------------------

function onTunerEvent() {
	if (!arguments || arguments.length == 0) {
		return;
	}
	var event = arguments[0];
	var eventArgs = [];
	for (var i=1; i < arguments.length; i++) {
		eventArgs[i -1] = unescape(arguments[i]);
	}
	window[event](eventArgs);
}
function radio_DoFSCommand(name, args) {
	// workaround for javascript: URLs failing to work in AIR for Mac
	eval(args);
}
function songPlayed (/*Array*/ args) {
	gLastSongPlayed = args[0];  // see ad methods below
}
function openContentWindow (/*Array*/ args) {
	openWindow(args[0], args[1]);
}

function songSetComplete() {
	// this is overridden in tuner_clearchannel.jsp, it is defined here so unittests don't fail
}

function normalizeHash(hash) {
	if (hash == "" || hash == "#") hash = "#/";
	return hash.replace(/%2D/gi, "-").replace(/%20/gi, "+");
}
function getLocationHash() {
	// sometimes FF unescapes characters in the hash when it really shouldn't,
	// therefore we need to grab the hash from the href to prevent parsing errors.
	var i = location.href.lastIndexOf('#');
	if (i == -1) {
		var hash = "#/";
	} else {
		var hash = location.href.substr(i);
	}
	return normalizeHash(hash);
}

function getMaxUrlLimit() {
    //see http://www.boutell.com/newfaq/misc/urllength.html
    if ($.browser.msie) {
        if (window.navigator.appVersion.indexOf("IE 6.0") != -1 || window.navigator.appVersion.indexOf("IE 5.5") != -1) {
            Pandora.sendMaxUrlLimit(450);
        }else{
            Pandora.sendMaxUrlLimit(2000);
        }
    }else{
        Pandora.sendMaxUrlLimit(65000);
    }
}

gCurrentURLFragment = getLocationHash();

var BACK_BUTTON_FRAME = "/include/homepageBackButtonFrameIE.html?"
var gBackButtonFrame = null;
if ($.browser.msie) {
		var styles = 'left:-1000px;top:-1000px;width:1px;height:1px;border:0;position:absolute;';
		var iframeHTML = '<iframe frameborder="0" id="backButtonFrame" style="' + styles + '" src="' + BACK_BUTTON_FRAME + gCurrentURLFragment.substr(1) + '"></iframe>';
		document.write(iframeHTML);
		gBackButtonFrame = document.getElementById("backButtonFrame");
}

function onURLFragmentChange(args) {
	gCurrentURLFragment = normalizeHash(args[0]);
	// double-check that the hashes aren't the same because some older
	// Safaris have problems with setting the same hash twice.
	if (gCurrentURLFragment != getLocationHash()) {
		if (gBackButtonFrame) {
			backButtonFrame.location = BACK_BUTTON_FRAME + gCurrentURLFragment.substr(1);
		}
		location.hash = gCurrentURLFragment;
		// browsers may alter escaping of the hash, so we'll set this back to our
		// global so that we don't get stuck infinitely updating
		gCurrentURLFragment = getLocationHash();

        // fire the beacon only for appropriate fragments (RADIO-8804)
        if (args[1]) {
	        fireComscoreBeacon();
	    }
	}
}
function checkHash() {
	var hash = getLocationHash();
	if (hash != gCurrentURLFragment) {
		gCurrentURLFragment = hash;
		Pandora.sendTunerCommand("URLFragmentChange", hash);
	}
}
setInterval(checkHash, 250);

var originalTitle = document.title;
function navigateToHash(hash) {
	// this is called by the BACK_BUTTON_PAGE
	location.hash = hash;
	// setting the hash will mess up IE's title...
	document.title = originalTitle;
}

function redirectWithTrackingCode (/*Array*/ args) {
	var location = getQueryString(null, ['tc']);
	if (location != '?') {
	    location += '&';
	}
	location += "tc=" + args[0];
	window.location.href = location;
}

function openBackstageWindow(type) {
	var mode = "all"
	var param = "?type="
	if (type == null) {
		param = "";
		type = "" }
	openWindow("/backstage" + param + type);
}

function onChangeDefaultSkinRequest(/* array */ args){
	setDefaultValance(args[0]);
}

function onSkinRequest(/* array */ args){
	setCurrentValance(args[0]);
}

function openWindow(url, target) {
	if (target == null || target == "")
		target = Pandora.BACKSTAGE_WINDOW_TARGET;

	var win = callOpen(url, target);
	if (win == null) {
		onPopupBlocker();
	} else {
		win.focus(); // brings the window to the front
	}
}

// separate function so that the mini-tuner can override to bust tabs.
function callOpen(url, target) {
	return window.open(url, target);
}

function launchMini() {
	if (MiniTuner.launchFromHomepage()) {
		window.location = getQueryString("indexmini", new Array("sc", "sn", "search"));
	}
}

gPopupWarningTimeout = null;
function onPopupBlocker() {
	$("#popup_blocker_warning").css("display","block").show(300);
	disableDiv(AD_DIV);
	if (gPopupWarningTimeout != null) {
		clearTimeout(gPopupWarningTimeout);
	}
	gPopupWarningTimeout = setTimeout(onClosePopupWarning, 30 * 1000);
}

function onClosePopupWarning() {
	$("#popup_blocker_warning").hide(300);
	enableDiv(AD_DIV);
	clearTimeout(gPopupWarningTimeout);
	gPopupWarningTimeout = null;
}


function bringToFront() {
	window.focus();
}

gListenerId     = null;
gSurveyCode     = "";
function userAuthChanged (/*Array*/ args) {
	if	(isEmpty(args[0])) {
		// User has probably just logged out of the tuner
		// Don't delete "at" cookie here in case the user wants to keep using backstage.
		// If a different account logs in, it will just overwrite the current "at" cookie.
	} else {
		// web auth token is already URL escaped to evade browser escaping inconsistencies
		setPersistentCookie("at", args[0], 30);
	}

	gListenerId = isEmpty(args[1]) ? null : args[1];
	gSurveyCode = gListenerId == null ? "" : gListenerId;
}

function getSurveyCode() {
	return gSurveyCode;
}

function setSessionCookie(/*string*/ name, /*string*/ value) {
	var val = name+"="+value+";path=/;";
	if (document.domain != null && document.domain.match(/pandora.com$/) ) {
		val += "domain=.pandora.com;";
	}
	document.cookie = val;
}

function setPersistentCookie(/*string*/ name, /*string*/ value, /*int*/ exipirationDays) {
	var date = new Date();
	date.setTime(date.getTime()+(exipirationDays*24*60*60*1000));
	var val = name+"="+value+"; path=/; ";
	val += "expires=" + date.toGMTString() + "; ";
	if (document.domain != null && document.domain.match(/pandora.com$/) ) {
		val += "domain=.pandora.com;";
	}
	document.cookie = val;
}

// -----------------------------
//       DOM manipulation
// -----------------------------
function existsDiv(divID) {
	return getDiv(divID) != null;
}

function enableDiv(divID) {
	var div = getDiv(divID);
	if (div == null) return;
	if(document.layers) {
		// old netscape way
		div.visibility = "";
	} else {
		// standard way
		div.style.visibility = "";
	}
}

function disableDiv(divID) {
	var div = getDiv(divID);
	if (div == null) return;
	if(document.layers) {
		// old netscape way
		div.visibility = "hide";
	} else {
		// standard way
		div.style.visibility = "hidden";
	}
}

function setDivEnabled(divID, /*boolean*/ b) {
	if(b) {
		enableDiv(divID);
	} else {
		disableDiv(divID);
	}
}

// -----------------------------
//        ad display
// -----------------------------
var gAdsEnabled      = true; // pages that don't display ads will set this to
                             // false.  (e.g. specialized landing pages)
var gLastSongPlayed  = null;
var gStationSeed     = null;
var gStationArtistId = null;
var gLastAdDisplay   = 0;
var gSessionId       = new Date().getTime();
var gLastAdTimestamp = null;
var gAdStationTarget = ""; // station ID

// var gAdRefreshInterval  = moved to tuner_embed.jsp

// First companion is used to specify the first companion ad to display upon page load.
// It is passed in the "fc" URL parameter from the MSN Messenger Tab.
if (location.search != null && location.search.match(/fc=([\w-_]+)/) ) {
	gFirstCompanion = RegExp.$1;
} else {
	gFirstCompanion = null;
}

function adStateChange (/*[string]*/ args) {
	if (args == null) {
		args = ["0:0:0:::0:0:0"];
	}
	Patron.setProfile(args[0]);
	var showAds = args[0].split(":")[0] == "1";
	
	if (args[1] == "newbie") {
		gCurrentAdSize = gNewbieAdSize;
	} else {
		gCurrentAdSize = gVeteranAdSize;
		if (window.jQuery) {
			$("#pandora_tips").css("visibility","").fadeIn(1000);
		} else {
			document.getElementById("pandora_tips").style.visibility = "";
		}

		// the promotional gallery is initialized here so the ticker and gallery
		// will appear to load together because, visually, they are the same element.
		// Subsequent ad state changes will not re-load the gallery
		initializePromotionalGallery(showAds);
	}
	
	// override refresh if necessary
	if (location.search != null && location.search.match(/adWait=(\d+)/) ) {
		gAdRefreshInterval = Math.min(Number(RegExp.$1), gAdRefreshInterval);
	}

	if (!showAds) {
		writeAdHTML(null);
		if(window.setTicker) window.setTicker(null);
	}
}

function onAdDemogCallback(/* [string] */ args){
	window['ad_demog_callback'](args);
}

// The content for the homepage promotional gallery is ad-served for registered users.
// For subscribers the content is set directly here.
function initializePromotionalGallery(showAds) {
	var promotionalGallery = document.getElementById("promotional_gallery");
	if (promotionalGallery == null) return;

	var promotionalGalleryDivRight = document.getElementById("promotional_gallery_right_div");
	var promotionalGalleryDivMiddleRight = document.getElementById("promotional_gallery_middle_right_div");
	var promotionalGalleryDivMiddleLeft = document.getElementById("promotional_gallery_middle_left_div");
	var promotionalGalleryDivLeft = document.getElementById("promotional_gallery_left_div");
	if (promotionalGalleryDivRight == null || promotionalGalleryDivMiddleRight == null || promotionalGalleryDivMiddleLeft == null || promotionalGalleryDivLeft == null) return;

	// For new subscribers we want to turn off ads immediately (on ad change)
	if (!showAds) {

		// subscriber content
		promotionalGalleryDivLeft.innerHTML =
			'<div id="promotional_gallery_left_sub"><a href="/mobile" target="pandoraContent" onclick="if (this.blur) { this.blur(); }; return true;"></div>';
		promotionalGalleryDivMiddleLeft.innerHTML =
			'<div id="promotional_gallery_middle_left_sub"><a href="/station_gift" target="pandoraContent" onclick="if (this.blur) { this.blur(); }; return true;"></div>';
		promotionalGalleryDivMiddleRight.innerHTML =
			'<div id="promotional_gallery_middle_right_sub"><a href="http://blog.pandora.com/show" target="pandoraContent" onclick="if (this.blur) { this.blur(); }; return true;"></div>';
		promotionalGalleryDivRight.innerHTML =
			'<div id="promotional_gallery_right_sub"><a href="/people/" target="pandoraContent" onclick="if (this.blur) { this.blur(); }; return true;"></div>';
	}

	// Since the gallery ad tags are not tied to a particular campaign,
	// only initialize the gallery once.
	if (promotionalGallery.style.visibility == "hidden") {

		if (showAds) {
			// registered user content - ad driven
			promotionalGalleryDivLeft.innerHTML        = Patron.generateIFrame("promotional_gallery_left", 2000, 13, {pos:1}, "promotionalGallery");
			promotionalGalleryDivMiddleLeft.innerHTML  = Patron.generateIFrame("promotional_gallery_middle_left", 2000, 13, {pos:2}, "promotionalGallery");
			promotionalGalleryDivMiddleRight.innerHTML = Patron.generateIFrame("promotional_gallery_middle_right", 2000, 13, {pos:3}, "promotionalGallery");
			promotionalGalleryDivRight.innerHTML       = Patron.generateIFrame("promotional_gallery_right", 2000, 13, {pos:4}, "promotionalGallery");
		}

		if (window.jQuery) {
			$("#promotional_gallery").css("visibility", "").fadeIn(1000);
		} else {
			promotionalGallery.style.visibility = "";
		}
	}
}

function onRegistration() {
	var div = document.createElement("div");
	div.innerHTML = "<iframe src='/static/counters/registrationConversion.html' style='border:none;height:0;width:0;'></iframe>";
	document.body.appendChild(div);
}

var gInteractionAdIndex = 0;
function onAdInteraction(/*Array*/ args) {
	var interaction = args[0];
	if (gAdsEnabled) {	
		var refreshInterval = gAdRefreshInterval;
		if (typeof gAdRefreshIntervalOverride != 'undefined' && gAdRefreshIntervalOverride >= 0) {
			refreshInterval = gAdRefreshIntervalOverride;
		}
		if( new Date().getTime() - gLastAdDisplay < refreshInterval && interaction != "skipAd" )
			return;
	
		// an ad can tell us that it should ignore pause interactions
		// [#RADIO-6512] Update homepage ad unit to have option to disable pause button as an interaction
		if (interaction == "pause" && getIgnorePauseInteractions()){
			return;
		}
	
		setIgnorePauseInteractions(false);
	
		gInteractionAdIndex++; // support for "first three impressions" ad type
		sendAdRequest({interaction: interaction, index: gInteractionAdIndex});
	} else {
		if(window.setTicker) window.setTicker(null);
	}
}

function adStationChange(/*[string, string, string, string]*/ args) {
	gAdStationTarget = args[0];
	gStationSeed     = args[1];

	// will be an empty string if station is song-based
	gStationArtistId = args[2] == "" ? null : args[2];
	Patron.cacheAntiTargetGenre(args[3] == "1");
}

function getIgnorePauseInteractions(){
	return window['ignorePauseInteractions'] == true;
}

function setIgnorePauseInteractions(b){
	window['ignorePauseInteractions'] = b;
}

// override normal wait settings
function companionAd(args) {
	sendAdRequest({companion: args[0]});
}

function storeFamilyIndex(/*[string]*/ args) {
    Patron.cacheFamIndex(args[0] == "" ? null : args[0]);
}

function sendAdRequest(options) {
    if (gRegistrationFormShowing) return;
    
	if (gCurrentAdSize == null) {
		// an ad request before we're fully initialized
		// when sz is null, the network will play *any* ad.  This is bad,
		// so let's not do that.
		return;
	}

	gLastAdDisplay = new Date().getTime();

	// display the ad.
	var path = "/include/radioAdEmbed";
	
	options.sz = gCurrentAdSize;
	options.ord = Patron.generateOrd(); // override ord setting because otherwise
		                                // it's static

	if (gStationSeed != null)
	{
		path += "Genre.jsp";
		// underscore prefix means that this value won't be passed on to the
		// DC embed.
		options._musicId = gStationSeed;

		// reset our genre in case no genre is found
		// (will be set by the embedded JSP if one is found)
		Patron.cacheGenre(null);

		// set to null so future ad embeds don't try to fetch genre again
		gStationSeed = null;
	} else {
		path += ".html";
	}

	if (gAdStationTarget != null) {
		options.station = gAdStationTarget;
	}

	if (gStationArtistId != null) {
		options.artist = gStationArtistId;
	}

	// the following exist for logging and data mining purposes
	options._session = gSessionId;

	var time = new Date().getTime();
	if (gLastAdTimestamp != null)
		options._elapsed = time - gLastAdTimestamp;

	gLastAdTimestamp = time;

	// Check for first companion global
	if (gFirstCompanion != null) {
		options.companion = gFirstCompanion;
		gFirstCompanion = null;
	}
	
	// write out the ad
	writeAdHTML(Patron.generateEmbedUrl(path, options));
}

function writeAdHTML(url) {
	// pages without ads won't have an ad div.
	// Passing a non-null url without ads enabled is an error, so we
	// explicitly check for null here so that we'll get a JS error if
	// we're in an invalid state.
	if (!gAdsEnabled && url == null)
		return;

	var html = "";
	if( url != null ) {
		// RADIO-1725: In Safari, after reloading a page, dynamic creation of the IFrame won't work --
		// it'll continue to display the last ad that displayed in the IFrame.  To get
		// around this, we dynamically create a unique ID for the IFrame, which manages
		// to get around Safari's internal "caching" mechanism.
		var adId = "ad" + (new Date().getTime());
		html = '<IFRAME id="' + adId + '" src="' + url + '" ' +
		       'frameborder="0" scrolling="no" marginheight="0" marginwidth="0" ' +
		       'topmargin="0" leftmargin="0" allowtransparency="true" width="100%" ' +
		       'height="100%"></IFRAME>';
	}

	getDiv(AD_DIV).innerHTML = html;
	if( html == "" ) {
		disableAds();
	} else {
		onAdWritten();

		// this method defined in head_valance.shtml
		if (window.prepareForValanceSwitch)
			prepareForValanceSwitch();
	}
}


// for testing -- called by tuner
function toggleAdDimensions() {
	if( getDiv(AD_DIV).className == "advertisement_double_wide" ) {
		onAdLoad("wide_skyscraper");
	} else if( getDiv(AD_DIV).className == "advertisement_tall" ) {
		onAdLoad("medium_rectangle");
	} else {
		onAdLoad("double_wide");
	}
}

// NOTE: these may be overridden by non-homepage embeds, such as the
//       mini-tuner or MSN spaces
AD_DIV      = "advertisement";

gNewbieAdSize  ="300x250";
gVeteranAdSize ="2000x2";
gCurrentAdSize = null;
function onAdWritten() {
	// ads will be enabled via onAdLoad
	// call-ups from the iframe when it loads.
	// do nothing...
}
function enableAds() {
	enableDiv(AD_DIV);
	enableDiv("promotional_ticker_container");
}
function disableAds() {
	disableDiv(AD_DIV);
	disableDiv("promotional_ticker_container");

	// this method defined in head_valance.shtml
	// not all pages implement this method.
	if (window.switchToDefaultValance) switchToDefaultValance();
}
function onAdLoad(/*string|null*/ adType) {
	// this method defined in head_valance.shtml
	if (window.useDefaultValanceIfNotSwitched)
		useDefaultValanceIfNotSwitched();

	if (gCurrentAdSize == "300x250") {
		// regular ads don't tell us their size
		getDiv(AD_DIV).className = "advertisement_square";
		enableAds();
		return;
	}
	
	if( adType == "medium_rectangle" ) {
		enableAds();
		getDiv(AD_DIV).className = "advertisement_square";
	} else if( adType == "wide_skyscraper" ) {
		enableAds();
		getDiv(AD_DIV).className = "advertisement_tall";
	} else if( adType == "double_wide" ) {
		enableAds();
		getDiv(AD_DIV).className = "advertisement_double_wide";
	} else {
		disableAds();
		if(window.setTicker) setTicker(null);
	}
}

function disableAdsOnShowRegistration() {
    gRegistrationFormShowing = true;
    writeAdHTML(null);

    var promotionalGallery = document.getElementById("promotional_gallery");
    if (promotionalGallery != null) {
        disableDiv("promotional_gallery");
    }

    var pandoraTips = document.getElementById("pandora_tips");
    if (pandoraTips != null) {
        disableDiv("pandora_tips");
    }
}

function enableAdsOnHideRegistration() {
    gRegistrationFormShowing = false;
    
    var promotionalGallery = document.getElementById("promotional_gallery");
    if (promotionalGallery != null) {
        enableDiv("promotional_gallery");
    }

    var pandoraTips = document.getElementById("pandora_tips");
    if (pandoraTips != null) {
        enableDiv("pandora_tips");
    }
}

var gRegistrationFormShowing = false;

// temp code for reporting Flash version and ExternalInterface support
// amongst users.  11/16/09, NEM
var eiCtx = {
	browserVersion: "",
	runtimeVersion: "",
	tested: 0,
	flashToJS: 0,
	JSToFlash: 0,
	timeout: 0,
	reportCount: 0
};
function onFlashVersion(args) {
	var bver = deconcept.SWFObjectUtil.getPlayerVersion();
	eiCtx.browserVersion = bver.major + "," + bver.minor + "," + (bver.release || 0);
	eiCtx.runtimeVersion = args[0];
	if (eiCtx.runtimeVersion.match(/^\w+\s+(\d+)/) && Number(RegExp.$1) >= 8) {
		eiCtx.tested = 1;
		setTimeout(eiTestTimeout, 20000);
		var div = eiTestCreateDiv();
		div.innerHTML = [
			'	<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"',
			'			codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0"',
			'			WIDTH="0" ',
			'			HEIGHT="0"',
			'		   id="TestExternalInterface"',
			'		   style="position:absolute">',
			'		<PARAM NAME=movie VALUE="TestExternalInterface.swf">',
			'		<PARAM NAME=quality VALUE=high>',
			'		<PARAM NAME=bgcolor VALUE=#FFFFFF>',
			'		<PARAM NAME=menu VALUE=false>',
			'	    <PARAM NAME="FlashVars" VALUE="">',
			'       <PARAM name="AllowScriptAccess" value="always">',
			'	<EMBED src="TestExternalInterface.swf"',
			'		   quality=high',
			'		   bgcolor=#FFFFFF',
			'		   WIDTH="0"',
			'		   HEIGHT="0"',
			'		   MENU="false"',
			'		   NAME="TestExternalInterface" ALIGN="" TYPE="application/x-shockwave-flash"',
			'		   PLUGINSPAGE="http://www.macromedia.com/go/getflashplayer"',
			'		   FlashVars=""',
			'          AllowScriptAccess="always"',
			'		   style="position:absolute">',
			'	</EMBED>',
			'	</OBJECT>'
		].join("");
	} else {
		eiTestRoundTripComplete();
	}
}
function eiTestCreateDiv() {
	var div = document.createElement("div");
	div.style.position = "absolute";
	div.style.height = "1px";
	div.style.width = "1px";
	div.style.overflow = "hidden";
	document.body.appendChild(div);
	return div;
}
function eiTestCallFlashToJS() {
	eiCtx.flashToJS = 1;
	if (navigator.appName != null && navigator.appName.indexOf("Microsoft") != -1) {
		var embed = window.TestExternalInterface;
	} else {
		var embed = document.TestExternalInterface;
	}

	if (embed.eiTestCallJSToFlash) {
		embed.eiTestCallJSToFlash();
	} else {
		eiTestRountripComplete();
	}
}
function eiTestConfirmedJSToFlash() {
	eiCtx.JSToFlash = 1;
	eiTestRoundtripComplete();
}
function eiTestRoundtripComplete() {
	eiCtx.reportCount++;
	// this file doesn't exist, we just want it logged
	var url = 
		"/images/clearspacer.gif?eitest=report"
		+ "&browser=" + escape(eiCtx.browserVersion)
		+ "&runtimer=" + escape(eiCtx.runtimeVersion)
		+ "&tested=" + eiCtx.tested
		+ "&toJS=" + eiCtx.flashToJS
		+ "&toFlash=" + eiCtx.JSToFlash
		+ "&timeout=" + eiCtx.timeout
		+ "&count=" + eiCtx.reportCount;
	while (url.indexOf("%2C") >= 0) {
		url = url.replace("%2C", ",");
	}
	while (url.indexOf("%20") >= 0) {
		url = url.replace("%20", "+");
	}
	eiTestCreateDiv().innerHTML = '<img src="' + url + '" style="height:1;width:1;">';
}
function eiTestTimeout() {
	if (eiCtx.reportCount == 0) {
		eiCtx.timeout = 1;
		eiTestRoundtripComplete();
	}
}

function getQueryString(/*string*/ command, /*array*/ ignoreParamList) {
	var strReturn = "";
	if (ignoreParamList == null) {
		ignoreParamList = [];
	}
	var strHref = window.location.href;
	if ( strHref.indexOf("?") > -1 ) {
		var queryString = strHref.substr(strHref.indexOf("?") + 1);
		var queryStringArray = queryString.split("&");
		for ( var iParam = 0; iParam < queryStringArray.length; iParam++ ) {
			var paramSet = queryStringArray[iParam].split("=");
			if (paramSet.length == 2) {
				if (paramSet[0] == "cmd") {
					continue;
				}
				var ignoreFound = false;
				for (ignoreParam in ignoreParamList) {
					if (ignoreParamList[ignoreParam] == paramSet[0]) {
						ignoreFound = true;
						break;
					}
				}
				if (ignoreFound) {
					continue;
				}
				strReturn = strReturn
					+ (strReturn.length != 0 ? "&" : "")
					+ paramSet[0] + "=" + paramSet[1];
			}
		}
	}
	if (command != null) {
		strReturn = strReturn
			+ (strReturn.length != 0 ? "&" : "")
			+ "cmd=" + command;
	}
	return "?" + strReturn;
}

// MiniTuner.js

function getQueryString(/*string*/ command, /*array*/ ignoreParamList) {
	var strReturn = "";
	if (ignoreParamList == null) {
		ignoreParamList = [];
	}
	var strHref = window.location.href;
	if ( strHref.indexOf("?") > -1 ) {
		var queryString = strHref.substr(strHref.indexOf("?") + 1);
		var queryStringArray = queryString.split("&");
		for ( var iParam = 0; iParam < queryStringArray.length; iParam++ ) {
			var paramSet = queryStringArray[iParam].split("=");
			if (paramSet.length == 2) {
				if (paramSet[0] == "cmd") {
					continue;
				}
				var ignoreFound = false;
				for (ignoreParam in ignoreParamList) {
					if (ignoreParamList[ignoreParam] == paramSet[0]) {
						ignoreFound = true;
						break;
					}
				}
				if (ignoreFound) {
					continue;
				}
				strReturn = strReturn
					+ (strReturn.length != 0 ? "&" : "")
					+ paramSet[0] + "=" + paramSet[1];
			}
		}
	}
	if (command != null) {
		strReturn = strReturn
			+ (strReturn.length != 0 ? "&" : "")
			+ "cmd=" + command;
	}
	return "?" + strReturn;
}


var MiniTuner = {
	WIDTH: 728,
	HEIGHT: 360,
	launchFromHomepage: function() {
		if (this.launch()) {
			// don't use disableDiv() or getDiv() or jquery here because they may not
			// be loaded yet when the user clicks.
			var elem = document.getElementById('TunerContainer');
			elem.style.visibility = 'hidden';
			elem.innerHTML='';
			return true;
		} else {
			return false;
		}
		
	},
	launch: function() {
		var win = 
			window.open(this.getUrl(),
						'Pandora',
						'width=' + this.WIDTH + ',height=' + this.HEIGHT 
						  + ',menubar=no,toolbar=no,scrollbars=no,status=no,'
						  + 'location=no,directories=no,resizable=false');
		if (win) {
			return true;
		} else {
			if (window.onPopupBlocker) {
				window.onPopupBlocker();
			}
			return false;
		}
	},
	getUrl: function() {
		var url = 'http://www.pandora.com/' + getQueryString("mini", new Array("sc", "sn", "search"));
		// RADIO-7982
		var unique = (new Date()).getTime();
		url += '&mtverify=' + unique;
		setSessionCookie("mtverify", unique); // defined in tuner.js
		return url;
	},
	verify: function() {
		if (!document.cookie 
			|| !document.cookie.match(/mtverify=(\d+)/) 
			|| location.href.indexOf("mtverify=" + RegExp.$1) == -1) 
		{
			location.href = "/";
		}			
	}
}
