/**
* $Id: m2g.js 3354 2006-02-10 22:53:13Z hudson $
* This is the shared JS file for the index.html pages
* @author hudson
*/

var buildVersion = "W1.3.7.0";
var jsEnabled = true;
var isPlatformsupported = (navigator.appName.indexOf("Explorer") != -1 && navigator.userAgent.indexOf("Win") != -1 && parseInt(navigator.appVersion) >= 4);
var docUrl;
docUrl = document.URL;
//alert("docUrl="+docUrl);
var B3AssetsBaseUrl = 'http://www.yourradiomusicstore.com/store_assets/eoc/cart/MTG/MTG/';
var iTunesBaseUrl = "phobos.apple.com/WebObjects/MZSearch.woa/wa/advancedSearchResults/?partnerId=30";
var curStationId;
var params = null;
var defaultWidgetWidth = "234";
var defaultWidgetHeight = "280";
var adAutoRefreshInterval = 0;
var sharedFolder = "/wshared/";
var useDefaultSize = false;

function getDomain() {
	var result = docUrl;
	if (result) {
		var urlAry = result.split( "/");
		if (urlAry[2] == "tunegenie.net") {
			initParams();
			urlAry[2] = params.StationId + "." + urlAry[2];
		}
		result = urlAry.slice(0, 3).join("/");
	} else {
		result = params.StationId + ".tunegenie.net";
	}
	return result;
}

function getSharedFolder() {
	return sharedFolder;
}

// Hook for Internet Explorer.
if (isPlatformsupported) {
	document.write('<script language=\"VBScript\"\>\n');
	document.write('On Error Resume Next\n');
	document.write('Sub m2gStore_FSCommand(ByVal command, ByVal args)\n');
	document.write('	Call m2gStore_DoFSCommand(command, args)\n');
	document.write('End Sub\n');
	document.write('</script\>\n');
	document.write('<script for=player event=PlayStateChange(newState)\>');
	document.write('onPlayStateChanged(newState);\n');
	document.write('</script\>\n');	
}

function m2gStore_DoFSCommand(command, argStr) {
	// TODO: use eval(argStr) to allow more arg types
	var functionToCall = eval(command);
	//alert( command + ", "+argStr); //+", "+functionToCall);
	functionToCall.apply(functionToCall, argStr.split("','")); //just use string args
}

function initParams() {
	if (params == null) {
		params = getParams();
		addGetStringParams(params);
		if (params.onProduction == null) params.onProduction = isOnProduction();
		if (params._pageBgColor == null) params._pageBgColor = "000000";
		widgetBgColor = params._pageBgColor;
		if (params.adWidth == null) params.adWidth = "234";
		adWidth = params.adWidth;
		if (params.adHeight == null) params.adHeight = "60";
		adHeight = params.adHeight;
		if (params.bgColor == null) params.bgColor = "000000";
		if (params.progressColors == null) params.progressColors = "FFFFFF#FF0000#FFFFFF#FFFFFF";
		if (params.promotionIdInEffect == null) params.promotionIdInEffect = "0";
		if (params.StationId == null) params.StationId = getStation();
		curStationId = params.StationId;
		if (params.HoursStationId == null) params.HoursStationId = params.StationId;
		//alert("station id="+ params.StationId+", hours id="+ params.HoursStationId);
		if (params.Gateway == null) params.Gateway = getGateway();
		params.Gateway += "?stationId=" + params.StationId;
		//alert("Gateway="+ params.Gateway);
		if (params.BinaryContentUrl == null) params.BinaryContentUrl = getBinaryContentUrl();
		if (params.ServiceClass == null) params.ServiceClass = "com.m2g.service.M2GRIAService";
		if (params.TemplateId == null) params.TemplateId = 'Altern';
		if (params.StoreUrl == null) params.StoreUrl = getStoreUrl();
		if (params.StationFolderUrl == null) params.StationFolderUrl = getStationFolderUrl();
		if (params.IntroMusicUrl == null) params.IntroMusicUrl = getStationIntroMusicIUrl(params.StationId);
		if (params.isExplorer == null) params.isExplorer = (navigator.appName.indexOf ("Microsoft") > -1);
		if (params.isPC == null) params.isPC = (navigator.userAgent.indexOf("Win") != -1);
		if (params.MainGenre == null) params.MainGenre = "cRock";
		if (params.CartType == null) params.CartType = "station";
		if (params.checkoutType == null) params.checkoutType = "store"; // set in URL to specify type of "sticky"
		if (params.storeCheckoutTitle == null) params.storeCheckoutTitle = "";
		if (params.iTunesCheckoutTitle == null) params.iTunesCheckoutTitle = "iTUNES " + curStationId.toUpperCase() + " Sticky";
		params.iTunesCheckout = convertToBoolean(params.iTunesCheckout);
		if (params.iTunesAffiliateId == null) params.iTunesAffiliateId = "Q4all6q52gQ";
		if (params.uacct == null) params.uacct = "UA-2693543-1";
		if (params.adAutoRefreshInterval == null) params.adAutoRefreshInterval = 0;
		if (params.excludeStationCheckout == null) params.excludeStationCheckout = "false";
		if (params.hookSource == null) params.hookSource = "moontaxi";
		if (params.buildVersion == null) params.buildVersion = buildVersion;
		if (params.wallUrl == null) params.wallUrl = "/wallstations/"+curStationId+"/index.php?stationId="+curStationId; //"http://"+getDomain()+
		params.wallActive = ((params.wallActive == true) || (params.wallActive == "true")) ? "true" : "false";
		params.inWall = "false";
		
		adAutoRefreshInterval = Number(params.adAutoRefreshInterval);
				
		addPreloadParams(params);
	}
	if (useDefaultSize == true) params.inWall = "true";
	if (params._stageWidth == null || useDefaultSize == true) params._stageWidth = defaultWidgetWidth;
	widgetWidth = params._stageWidth;
	if (params._stageHeight == null || useDefaultSize == true) params._stageHeight = defaultWidgetHeight;
	widgetHeight = params._stageHeight;
	
	return params;
}

function sendSongToThirdParty(type, title, artist, album) {
	//alert("sendSongToThirdParty "+type+" , "+title+" , "+artist+" , "+album);
	initParams();
	var url = "";
	if (type == "iTunes") {
		var baseUrl = iTunesBaseUrl + "&id="+ params.iTunesAffiliateId;
		if (!nullString(title)) url += "&songTerm="+title;
		if (!nullString(artist)) url += "&artistTerm="+artist;
		if (!nullString(album)) url += "&albumTerm="+album;
		if (typeof( iTunesDetected) == "function" && iTunesDetected()) {
			url = "itms://" + baseUrl + url;
			var iFrameDoc = getIFrameDoc('sendToThirdPartyFrame');
			iFrameDoc.location.replace(url);
		} else {
			url = "http://" + baseUrl + url;
			window.open(url);
		}
//		alert( url);
	} else {
		alert("sendSongToThirdParty unknown type "+type);
	}
}

function getIFrameDoc(id) {
	var result = null;
	var fr = document.getElementById(id);
	if (fr == null) {
		alert("error: getIFrameDoc failed with id='"+id+"'");
	} else {
		if (fr.contentDocument) {
		// For NS6
			result = fr.contentDocument;
		} else if (fr.contentWindow) {
		// For IE5.5 and IE6
			result = fr.contentWindow.document;
		} else if (fr.document) {
		// For IE5
			result = fr.document;
		}
	}
	return result;
}

function nullString(str) {
	var result;
	if (typeof(str) != "string") {
		result = true;
	} else {
		result = (str.length < 1) || (str.toLowerCase() == "null") || (str.toLowerCase() == "undefined");
	} 
	return result;
}

function indexBody(_useDefaultSize) {
	if (_useDefaultSize == true) useDefaultSize = true;
	initParams();
	hasCookies = cookiesEnabled();
//	logAction("bodyInit", "unknown", null, "cookiesEnbled", hasCookies)
	if (hasCookies) {
		writeWMPPagePrep();
		document.writeln('<BODY>');
		if (params.CartType == "iTunes") {
			document.writeln('<object classID="CLSID:D719897A-B07A-4C0C-AEA9-9B663A28DFCB" width="1" height="1" id="iTunesDetectorIE" ></object>');
		}
		var version = swfobject.getFlashPlayerVersion(); 
		var flashVerStr;
		if (version['major'] > 0) {
			flashVerStr = ', you have Flash version '+version['major'] +'.'+ version['minor'] +'.'+ version['rev'] +' installed.';
		} else {
			flashVerStr = '.';
		}
		document.writeln('<div id="flashcontent" ><strong>You need to allow blocked content or upgrade your Flash Player'+flashVerStr+'</strong></div>');
		document.writeln(getAdHtml());
		if (params.CartType != "store") {
			document.writeln('<IFRAME id="sendToThirdPartyFrame" width="1" height="1" frameborder="0">this browser does not support frames</IFRAME>');
		}
		
		var flashvars = {flashVarNames:""};
		var prop;
		for (prop in params) {
			if (prop.indexOf("_") != 0) {
				flashvars[prop] = params[prop];
				flashvars.flashVarNames += prop+"|";
			}
		}
		var flashparams = {};
		flashparams.allowScriptAccess = "sameDomain";
		flashparams.scale = "exactfit";
		flashparams.menu = "false";
		flashparams.bgcolor = "#"+params.bgColor;
		flashparams.wmode = "opaque";
		var flashattributes = {};
		flashattributes.id = "m2gStore";
		flashattributes.name = "m2gStore";
		swfobject.embedSWF(getSharedFolder() + "liteloader.swf", "flashcontent", params._stageWidth, params._stageHeight, "8", getSharedFolder() + "expressInstall.swf", flashvars, flashparams, flashattributes);
		
//		var tag = new SWFObject(getSharedFolder() + "liteloader.swf", "m2gStore", params._stageWidth, params._stageHeight, "8", "#"+params.bgColor, true);
//		tag.addParam("allowScriptAccess", "sameDomain");
//		tag.addParam("scale", "exactfit");
//		tag.addParam("menu", "false");
//		//tag.addParam("wmode", "transparent");
//		var prop;
//		for (prop in params) {
//			if (prop.indexOf("_") != 0) {
//				tag.addVariable(prop, params[prop]);
//			}
//		}
//		tag.write("flashcontent");
		
		
	//	var adTag = new SWFObject("hours_flash_ad.swf", "adPlaceHolder", params.adWidth, params.adHeight, "8", "#"+params.bgColor);
	//	adTag.addParam("allowScriptAccess", "sameDomain");
	//	adTag.addParam("scale", "exactfit");
	//	adTag.addParam("wmode", "transparent");
	//	adTag.write("tempAd");
		//document.writeln('<IFRAME id="'+adElementId+'" width="'+params.adWidth+'" height="'+params.adHeight+'" frameborder="0">this browser does not support frames</IFRAME>');
		document.writeln('<div id="flashversion"></div>');
		document.writeln('<br/>');
		if (isPlatformsupported) {
			// Media Player DIV (hidden to user) 
			document.writeln('<div id="uiplayer">');
			document.writeln('<object id="player" classid="clsid:6BF52A52-394A-11d3-B153-00C04F79FAA6" height="64" width="320">');
			document.writeln('<param name="uiMode" value="invisible" />');  // invisible mini full
			document.writeln('<param name="autoStart" value="true" />'); 
			document.writeln('<param name="SendPlayStateChangeEvents" value="true" />'); 
			document.writeln('</object></div>');
		} else {
			document.writeln('<IFRAME id="hookLauncherFrame" width="1" height="1" frameborder="0">this browser does not support frames</IFRAME>');
			// hack to stop cached sound on page refresh, firefox only
			stopSound();
		}
		//document.writeln('</td></tr></table>');
		document.writeln('</BODY>');
//		var adEl = document.getElementById("adPlaceHolder");
//		adEl.style.visibility = 'visible';
//		alert(adEl.style.visibility);
	} else {
		document.writeln('<body>Your browser\'s cookie functionality is turned off. Please turn it on.. <a href="'+getSharedFolder()+'resources/web/cookiehelp.html">Here\'s how.</a></body>');
	}
}

function convertToBoolean(val) {
	var result = eval(val);
	if (result < 0) result = -result;
	if (val == null) result = false;
	else result = (result > 0); 
	return result;
}

function getBinaryContentUrl() {
	return getGatewayDomain()+"m2g-web/BinaryContent?";
}

function isOnProduction() {
	return (docUrl.split("/")[2].indexOf( "tunegenie.net") >= 0)
}

function getStoreUrl() {
	var result;
	var stationId = curStationId;
	if (stationId == null) stationId = getStation();
	if (isOnProduction()) {
		result = "http://" +stationId+ ".tunegenie.net";
	} else {
		var urlAry = docUrl.split("/").slice(0,5);
		urlAry[3] = "stations";
		urlAry[4] = stationId;
		result = urlAry.join("/");
	}
	return result;
}

function getGatewayDomain() {
	var result;
	var url = docUrl;
	if ((url.indexOf("file") == 0) || (url.indexOf("//blondie.") >= 0) || (url.indexOf("//demo.") >= 0)) {
		//result = "http://localhost:9000";
		result = "http://tunegenie.net";
	} else {
		var urlAry = url.split( "/");
		result = urlAry.slice(0, 3).join("/");
	}
        //alert(result);
	return result + "/";
}

function getGateway() {
	return getGatewayDomain()+"m2g-web/gateway";
} 

function getStationFolderUrl() {
	var url = docUrl;
	var urlAry = url.split( "/");
	urlAry[urlAry.length - 1] = "";
	return urlAry.join("/");
} 

function getStation() {
	var result;
	var url = docUrl;
	var urlAry = url.split( "/");
	result = urlAry[2].split(":")[0];
	result = result.split(".")[0];
	var i = urlAry.length;
	while (i--) { // if "stations" is a folder in the URL path, then assumes the station name is one up from this
		if (urlAry[ i].indexOf("wstations") >= 0) {
			result = urlAry[ i+1];
			break;
		}
	}
	if (result.indexOf( "_") > 0) {
		result = result.split("_")[0];
	}
	//alert( "station name = '"+result+"'");
	return result;
}

function getStationIntroMusicIUrl(stationId) {
	if (stationId == null) stationId = curStationId;
	if (stationId == null) stationId = getStation();
	var result;
	// E.G.:  ..../m2g-web/BinaryContent?stationId=wbos&type=intromusic
	result = getGatewayDomain() + "m2g-web/BinaryContent?stationId=" + stationId + "&type=intromusic";
	//alert( "station intro music url= "+result);
	//window.open(result,'introMusicTest');
	return result;
}

function logAction(action, sessionId, station, idName, idValue) {
}

function trackAction(action, sessionId, station, idName, idValue) {
}

function parseGetStringParams() {
	var result = {};
	var searchStrLoc = docUrl.indexOf("?") + 1;
	if (searchStrLoc > 0) {
		getString = docUrl.substr(searchStrLoc);
	} else {
		getString = "";
	}
	var nvp;
	var nvps = getString.split("&");
	var i, n = nvps.length;
	for (i=0; i<n; i++) {
		nvp = nvps[i].split("=");
		result[nvp[0]] = nvp[1];
	}
	return result;
}

function addGetStringParams(params) {
	var getStrParams = parseGetStringParams();
	var name;
	for (name in getStrParams) {
		params[name] = getStrParams[name];
	}
	var plDispOverride = null;
	if (params.initialDisplayList != null) {
		if (params.initialDisplayList.substr(0, 20) == "search_artistAndSong") {
			plDispOverride = "V";
		} else if (params.userPlaylist > 0) {
			plDispOverride = "C";
		} else {
			plDispOverride = "D";
		}
		if (params.plDisplay == null) params.plDisplay = plDispOverride;
	}
	if (params.disableIntroMusic == "true") {
		params.IntroMusicUrl = " ";
	}
	if ( params.stationBuild != null) {
		params.buildVersion += "_" + params.stationBuild;
	}
}

// currently we are not using cookies, but leaving these functions here for possible future use
function cookiesEnabled() {
	return true; // remove or comment this line if using cookies
	var cookieTestStr = "testCookies";
	setCookie(cookieTestStr, cookieTestStr);
	return (getCookie(cookieTestStr) == cookieTestStr);
}
 
function getCookie(cookiename) { 
	var result = null;
	var cookieStr = document.cookie + ";";
	cookiename = "m2g_" + cookiename + "=";
	var begin = cookieStr.indexOf(cookiename);
	if (begin > -1) {
		begin += cookiename.length;
		var end = begin + cookieStr.substring(begin).indexOf(";");
		result = unescape(cookieStr.substring(begin, end)); 
	}
	return result;
}

function setCookie(cookiename, value) { 
	document.cookie = "m2g_" + cookiename + "=" + value;
}

function openWidgetWindow(url) {
	ww = 26 + eval(defaultWidgetWidth);
	wh = 80 + eval(defaultWidgetHeight);
	wl = 0;
	wt = 0;
	locStr = getSavedWindowLoc();
	if (!nullString(locStr)) {
		locAry = locStr.split(",");
		if (locAry.length == 2) {
			wl = locAry[0];
			wt = locAry[1];
		}
	}
	stationId = curStationId;
	if (stationId == null) stationId = getStation();
	if (screen.width > 0) {
		//wl = screen.width - ww;
	} 
	openNewWindow(url, stationId+'_sticky', 'menubar=no,scrollbars=no,resizable=yes,width='+ww+',height='+wh+',left='+wl+',top='+wt);
}

function getSavedWindowLoc() {
	return getCookie("stickyLoc");
}

function saveWindowLoc() {
	setCookie("stickyLoc", ""+ window.screenX+","+window.screenY)
}


function openStoreWindow(url) {
	stationId = curStationId;
	if (stationId == null) stationId = getStation();
	openNewWindow(url, stationId+'_store', 'menubar=no,scrollbars=yes,resizable=yes,width=1000,height=700');
}

function openNewWindow(url, title, features) {
	return window.open(url, title, features);
}

function getPageTitle(_useDefaultSize) {
	if (_useDefaultSize == true) useDefaultSize = true;
	initParams();
	var result = params[params.CartType + "CheckoutTitle"];
	if (result == null) {
		result = ""
	}
	return result;
}

function decodeJSON(JSONString) {
	return eval("("+JSONString+")");
}


