/**** Define global variables ****/
var loaded = false;
var refreshRate = 7200000; //// Milliseconds between refreshes.  Default is 2 hours, to override, use ?refreshtimeout=5000
var navCookie = "realNav"; //// Name of cookie used for remembering state.
var navCookieLife = 360; //// Days for the nav cookie to live

/****
    Get the arguments from the query string & 
    put them into an object of name/value pairs.  
    Accessible by obj.name=value 
****/
var obj = getArgs(); 

function init(){
    //alert ("Running Init");
    
    
    if(!document.getElementById) {
        ////alert("Older than 4.0 browser.");
        document.write("Your browser is not supported by this application.");
    } 
    else if (obj.state == true && document.getElementById('nav')){ // if state=1 is in the URL query string, remember what nav layers are open or not.
        if (getCookieValue(navCookie)){ // If there's a navCookie, open it up & get the list of what layers to open
            var cookieVal = getCookieValue(navCookie);
            groupCategories = cookieVal.split('|');
            for (var i=0; i < groupCategories.length; i++) {
                ////alert(groupCategories[i]);
                if (groupCategories[i].length > 1){
                    /**** 
                        for each item in the cookie, open that layer up...
                    ****/
                    toggleLayer(groupCategories[i]); 
                }
            }
        }
    }
    
    /****
        If you're in the player, refresh the page every 2 hours (or whatever ?refreshtimeout is)
    ****/
    if(is_in_player){
        if (obj.refreshtimeout) {
            refreshRate = obj.refreshtimeout.length>1?obj.refreshtimeout:refreshRate;
        }
        //startRefreshTimer();
        

    }
    
    pingTheGuide();
}

function openPopup(theURL, theTitle, width, height) {
    var strSettings = 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width='+width+',height='+height;  
    var win = window.open(theURL, theTitle, strSettings);
    win.focus();
} 

function isViper() {
    var pv = plyrObj.PlayerProperty("PRODUCTVERSION");
    var beamerVersion = "6.0.11.000";
    return versionCompare( pv, beamerVersion ) == -1;
}

function isBoxter() {
    var pv = plyrObj.PlayerProperty("PRODUCTVERSION");
    var boxterVersion = "6.0.11.999";
    return versionCompare( pv, boxterVersion ) == 1;
}

/* Compares 2 versions as #.#.#.# strings... */
function versionCompare(a,b) {
    var testver1 = a.split(".");
    var testver2 = b.split(".");

    if( testver1.length != testver2.length ) {
        return 0;
    }
        
    for( var i=0 ; i<testver1.length ; i++ ) {
        var t1 = testver1[i]-0;
        var t2 = testver2[i]-0;

        if( t1 != t2 ) {
            if( t1 < t2 ) {
                return -1;
            }
            if( t1 > t2 ) {
                return 1;
            }
        }
    }
    return 0;
}

function navigateToTab( tab, theURL ) {    
    if( is_in_player && plyrObj != null ) {
        if (!isBoxter() && (tab == "home" || tab == "musicguide" || tab == "musicstore" || tab == "browser" || tab == "channels")) {
            tab = "web";
        }
        plyrObj.OpenURLInPlayerBrowser(theURL,"_rpexternal");
    } else if (tab == "external") {
        var win = window.open(theURL, '_rpexternal');
        win.focus();
    } else {
        document.location.href = theURL; 
    }
}

function getArgs() {
    
    var args = new Object(); 
    var query = location.search.substring(1); //// Get Query String 
    var pairs = query.split("&"); //// Split query at the ampersand
    
    for(var i = 0; i < pairs.length; i++) {    //// Begin loop through the querystring

        var pos = pairs[i].indexOf('='); //// Look for "name=value"
        if (pos == -1) continue; //// if not found, skip to next
        var argname = pairs[i].substring(0,pos); //// Extract the name
        
        var value = pairs[i].substring(pos+1); //// Extract the value
        args[argname] = unescape(value); //// Store as a property
    }
    return args; //// Return the Query string name/value pairs as an Object
}

/****
    Set the refreshRate from the querystring if present 
    and refresh the page that often.  Otherwise, use the 
    default 2 hour timer. 
****/
function startRefreshTimer( ) {
    if( !loaded ){
        setTimeout("startRefreshTimer()",1000);
    } else{
        setTimeout("pageRefresh();",refreshRate);
    }
}

function pageRefresh() {
    if (is_in_player) {
        var plyrObj = top.parent.window.external;
    } else {    
        document.write("<object id=\"IERPCtl\" width=0 height=0 classid=\"CLSID:FDC7A535-4070-4B92-A0EA-D9994BCC0DC5\"></object>");
        var plyrObj = document.getElementById("IERPCtl");
    }
    
    if( refreshURL && plyrObj.IsNetConnected() && plyrObj.PlayerProperty("WORKOFFLINE")!=1 ){
          document.location.href = refreshURL; 
    } else{
        setTimeout("pageRefresh();",refreshRate);
    }
}

/****
    Next two functions encode string as UTF-8.
****/
function encodeChar( val )
{
    /* Create URL encoded utf-8 values from a scalar int */
    var output = "";
    /* Single Byte Values */
    if( (val & 0x7F) == val )
    {
        return escape( String.fromCharCode(val) );
    }
    /* Two Byte translation */
    if( ( val & 0x07FF ) == val )
    {
        output += "%" + ( ( val>>6 ) | 0xC0 ).toString(16);
        output += "%" + ( ( val & 0x3F ) | 0x80 ).toString(16);
        return output;
    }
    /* Three byte translation */
    if( (val & 0xFFFF) == val )
    {
        output += "%" + (( val >> 12 ) | 0xE0 ).toString(16);
        output += "%" + ((( val >> 6 ) &  0x3F ) | 0x80 ).toString(16);
        output += "%" + (( val & 0x3F ) | 0x80 ).toString(16);
        return output;
    }
    /* Four Byte translation */
    if( (val & 0x1FFFFF) == val )
    {
        output += "%" + (( val >> 18 ) | 0xF0).toString(16);
        output += "%" + ((( val >> 12 ) & 0x3F ) | 0x80 ).toString(16);
        output += "%" + ((( val >> 6) & 0x3F ) | 0x80 ).toString(16);
        output += "%" + (( val & 0x3F ) | 0x80 ).toString(16);
        return output;
    }
}
function urlHexEncode( str )
{
    var ret = "";
    for( var i=0; i<str.length; i++ )
    {
        ret += encodeChar( str.charCodeAt( i ) );
    }
    return ret;
}


function RPOnStateChange(play_state){
    if (document.getElementById("flash")){
        switch(play_state) {
            case 0:
                // stopped state
                flash.Play();
                break
            case 3:
                // playing state
                flash.StopPlay();
                break;
        }
    }
}

function getExpiryDateForCookie(days){
    var UTCString;
    Today = new Date();
    milliseconds = Date.parse(Today);
    Today.setTime(milliseconds + days*24*60*60*1000);
    UTCString = Today.toUTCString();
    return UTCString;
}

function setCookie(name, value, duration, path, domain, secure) {
    document.cookie= name + "=" + value +
        ((duration) ? "; expires=" + getExpiryDateForCookie(duration) : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

function rp_playclip(url) {
  if (plyrObj) {
    plyrObj.PlayClip(url);
    return false;
  }
  else {
    return true;
  }

}

function pingTheGuide() {
	var pstate = -1;
	try {
        pstate = plyrObj.GetPlayerState();
//alert("http://ping." + guideURL + "/?player-state=" + pstate);
		if (window.XMLHttpRequest) {
		    // For Firefox and Mozilla
		    var req = new XMLHttpRequest()
		    req.open("GET", "http://" + guideURL + "/ping?player-state=" + pstate, true)
		    req.send(null)
		}
		else if (window.ActiveXObject) {
		    // For IE
		    var req = new ActiveXObject("Microsoft.XMLHTTP");
		    if (req) {
		        req.open("GET", "http://" + guideURL + "/ping?player-state=" + pstate, true);
		        req.send();
		    }
		}
	}
	catch (ex) {}
}   

function NewWindow(mypage,myname,w,h){
	LeftPosition = (screen.width) ? (screen.width-w)/2 : 0;
	TopPosition = 20;
		    	
	settings =
	'height='+h+',width='+w+',top='+TopPosition+',left='+LeftPosition+',scrollbars=yes,location=yes,resizable=yes,toolbar=yes,status=yes,menubar=yes'
	win = window.open(mypage,myname,settings)
}

/*** For Ringback Tones ***/

function hide(id) {
  if (document.getElementById(id) != null && document.getElementById(id) != '') {
    document.getElementById(id).style.display = 'none';
  }  
}
function show(id) {
  if (document.getElementById(id) != null && document.getElementById(id) != '') {
    document.getElementById(id).style.display = 'block';
  }  
}

function playRingtone(modandnum) {
 
  var active = modandnum;
  var pauseid = modandnum + "Pause";
  var playid = modandnum + "Play";

  var playButtons = new Array();
  playButtons[0] = "header1";
  playButtons[1] = "header2";
  playButtons[2] = "promo11";
  playButtons[3] = "promo12";
  playButtons[4] = "promo21";
  playButtons[5] = "promo22";
  playButtons[6] = "promo31";
  playButtons[7] = "promo32";
  playButtons[8] = "promo33";

  for (i=0;i<playButtons.length;i++) {
    if (playButtons[i] != active) {
      show(playButtons[i] + "Play");    
      hide(playButtons[i] + "Pause");
    }
    else {
      show(pauseid);
      hide(playid);
    }
  }  
}
function pauseRingtone(modandnum) {
  var pauseid = modandnum + "Pause";
  var playid = modandnum + "Play";

  show(playid);
  hide(pauseid);
}

/*** For Omniture ***/
var RhapsodyTracking = {
	_accountId: null,
	_category: null,
	_pageName: null,
	_environment: null,
	
	primaryContentId: null,
	primaryContentName: null,
	artistId: null,
	artistName: null,
	albumId: null,
	albumName: null,
	galleryId: null,
	imageSetId: null,
	
	browseResultsCount: null,
	browseQuery: null,
	treatSearchAsBrowse: false,
	errorType: null,
	genreName: null,
	lsrc: null,
	musicVideoId: null,
	pageId: null,
	_rhapsodyMember: null,
	searchCategory: null,
	searchResultsCount: null,
	searchQuery: null,
	searchType: null,
	testVariant: null,
	topLevelGenreName: null,
	
	profileFriends: null,
	profilePublicPlaylists: null,
	
	okToDebug: false,
	
	debugElement: null,
	getAccountId: function(){
		return this._accountId;
	},
	getEnvironment: function(){
		return this._environment;
	},
	getCategory: function(){
		return this._category?this._category:"";
	},
	getPageName: function(){
		return this._pageName?this._pageName:"";
	},	
	getGalleryId: function(){
		return this.galleryId?this.galleryId:"";
	},
	getImageSetId: function(){
		return this.imageSetId?this.imageSetId:"";
	},
	getCategory: function(){
		return this._category?this._category:"";
	},
	setAccountId: function( aid ){
		this._accountId = aid;
	},
	setEnvironment: function( env ){
		this._environment = env;
	},
	setCategory: function( cat ){
		this._category = cat;
	},
	setPageName: function( pn ){
		this._pageName = pn;
	},
	setImageSetId: function( is ){
		this.imageSetId = is;
	},
	setGalleryId: function( gi ){
		this.galleryId = gi;
	},
	getBreadcrumbs: function(){
		var crumbs = null;
		var crumbTrail = document.getElementById( 'crumbtrail' );
		if( crumbTrail ) crumbs = crumbTrail.innerHTML;
		if( crumbs ){
			crumbs = crumbs.stripTags();
			crumbs = crumbs.replace( /&gt;/g, ' : ' );
			crumbs = crumbs.replace( /&[^;]+;/g, '' );
			crumbs = crumbs.replace( /\s+/g, ' ' );
			crumbs = crumbs.replace( /Home :/gi, ' ' );
			crumbs = crumbs.strip();
			return crumbs;
		} else return null;
	},
	getLocalSrc: function( raw ){
		var returnLsrc = this.lsrc;
		if( !raw && returnLsrc ) returnLsrc = returnLsrc.replace( /_/g, ':' );
		return returnLsrc;
	},
	setLocalSrc: function( ls ){
		this.lsrc = ls;
	},
	getLinkInternalFilters: function(){
		return "javascript:,rhapsody.com,static.";
	},
	getCustomMetric: function( cmName, castTo ){
		var cmReturn = this[ cmName ];
		if( ( cmReturn != null ) && ( castTo == 'String' ) ) cmReturn = cmReturn.toString();
		return cmReturn != null?cmReturn:"";
	},
	setCustomMetric: function( cmName, cmValue ){
		if( cmValue.strip != '' ) this[ cmName ] = cmValue;
		return cmValue;
	},
	getRhapsodyMember: function(){
		return this._rhapsodyMember;
	},
	setRhapsodyMember: function( rm ){
		this._rhapsodyMember = rm;
	},
	getCampaignData: function(){
		var delim = ":";
		var cdString = "";
		var thePcode = ( this.getRhapsodyMember() && this.getRhapsodyMember().cobrandPartner && this.getRhapsodyMember().cobrandPartner != '' )?this.getRhapsodyMember().cobrandPartner:"RN";
		var theCpath = ( this.getRhapsodyMember() && this.getRhapsodyMember().cpath && this.getRhapsodyMember().cpath != '' )?this.getRhapsodyMember().cpath:"RN";
		var theRsrc =  ( this.getRhapsodyMember() && this.getRhapsodyMember().rsrc && this.getRhapsodyMember().rsrc != '' )?this.getRhapsodyMember().rsrc:"RN";
		if( this.getRhapsodyMember() ) cdString = thePcode + delim + theCpath + delim + theRsrc;
		return cdString;
	},
	sendPageView: function( overridesObj, optionsObj ){
		var disableCall = false;
		var persistPreviousOverrides = ( optionsObj && optionsObj.persistPreviousOverrides )? ( optionsObj && optionsObj.persistPreviousOverrides ): false;
		try{
			s = s_gi( this.getAccountId() );
		} catch( e ){ disableCall = true }
		if( !persistPreviousOverrides ) this.setDefaultConfig();
		if( !disableCall ){
			this._setOverrides( overridesObj );
			void( s.t() );
			if( this.okToDebug ) this.debug();
		}
	},
	sendLinkEvent: function( overridesObj, optionsObj ){
		// if i want original data set s.linkTrackVars = ""; and s.linkTrackEvents = "";
		var disableCall = false;
		try{
			s = s_gi( this.getAccountId() );
		} catch( e ){ disableCall = true }
		var linkTypeHash = new Object();
		linkTypeHash[ 'exit' ] = 'e';
		linkTypeHash[ 'download' ] = 'd';
		linkTypeHash[ 'custom' ] = 'o';
		var linkTypeAbbrev = optionsObj.type?linkTypeHash[ optionsObj.type ]:null;
		var linkName =  optionsObj.linkName?optionsObj.linkName:null;
		var ltvString = "eVar18";
		var moreThanOne = false;
		if( !disableCall && optionsObj && overridesObj ){
			s.eVar18 = this.getPageName();
			for( var i in overridesObj ){
				s[ i ] = overridesObj[ i ];
				ltvString += "," + i;
				moreThanOne = true;
			}
			if( optionsObj.events ){
				s.linkTrackEvents = optionsObj.events;
				s.events = optionsObj.events;
				ltvString += ",events";
			}
			s.linkTrackVars = ltvString;
			 if( linkTypeAbbrev && linkName ){
				void( s.tl( this, linkTypeAbbrev, linkName ) );
			 }
		}
	},
	_setOverrides: function( or ){
		for( var i in or ){
			s[ i ] = or[ i ];
		}
	},
	debug: function( closeDebug ){
		var timeoutTilClose = 5000;
		var omnitureImgHolder =  document.getElementById( 'omnitureCodeToPaste' );
		var omnitureImg = null;
		var debugInfo = 'Tracking Info:<br\/>' + 
			'Category: ' + this.getCategory()+ '<br\/>' + 'Page Name: ' + this.getPageName() + '<br\/>' +
			'<a href="#" onclick="RhapsodyTracking.debug( true ); return false;">close<\/a>';
		if( omnitureImgHolder && ( typeof omnitureImgHolder != 'undefined' ) ){
			var omnitureImgs = omnitureImgHolder.getElementsByTagName( 'IMG' );
			for( var i=0; i<omnitureImgs.length; i++ ){
				if( omnitureImgs[ i ].getAttribute( 'NAME' ) == 's_i_' + this.getAccountId() ) omnitureImg = omnitureImgs[ i ];
			}
		}
		if( omnitureImg && omnitureImg.src != '' ) debugInfo += "<p>sent a request to omniture<\/p>";
		else debugInfo += '<p style="color: red;">no request sent to omniture!<\/p>';
		if( !closeDebug ){
			this.debugElement = new DialogBox(
				{
					elementId: "RhapsodyTrackingDebugBox",
					width: '230px',
					height: '120px',
					htmlContent: debugInfo
				}
			);
			this.debugElement.show();
			with( this.debugElement.getHoldingElement().style ){
				backgroundColor = "#CCC";
				padding = "10px";
				overflow = "auto";
			}

			if( !RhapsodyTracking.getPageName() || !RhapsodyTracking.getCategory() ){
				timeoutTilClose = 15000;
				with( this.debugElement ){
					hide();
					setMask( true );
					getHoldingElement().style.backgroundColor = "red";
					centerInPage();
					show();
					loadContent( { htmlContent: debugInfo + '<p><b>set a category and pagename in /conf/rotw.reporting-services.xml<\/b><\/p>' } );
				}
			}
			RhapsodyUtility.setAlpha( "RhapsodyTrackingDebugBox", 80 );
			
			var omnitureDebugHolderElement = document.createElement( "DIV" );
			var omnitureDebugAnchor = document.createElement( "A" );
			var omnitureDebugAnchorText = document.createTextNode( "view omniture debugger" );
			omnitureDebugAnchor.appendChild( omnitureDebugAnchorText );
			omnitureDebugAnchor.setAttribute( "href", "javascript:RhapsodyTracking.launchOmnitureDebug();" );
			omnitureDebugHolderElement.appendChild( omnitureDebugAnchor );
			this.debugElement.getHoldingElement().appendChild( omnitureDebugHolderElement );

			setTimeout( "RhapsodyTracking.debug( true )", timeoutTilClose );
		} else {
			if( RhapsodyTracking.debugElement ){
				RhapsodyTracking.debugElement.removeHoldingElement();
				if( RhapsodyTracking.debugElement.getMask() ) RhapsodyTracking.debugElement.setMask( false );
				RhapsodyTracking.debugElement = null;
			}
		}
	},
	launchOmnitureDebug: function(){
		window.open("","stats_debugger","width=600,height=600,location=0,menubar=0,status=1,toolbar=0,resizable=1,scrollbars=1").document.write("<script language=\"JavaScript\" src=\"http://192.168.112.2O7.net/stats_debugger.php\"></"+"script>"); 
	}
}


function doOmniture(page,name,value,id, pageNum){
//alert('page: ' + page + ' name: ' +name + ' value: ' + value + 'id: ' + id + ' pageNum: ' + pageNum);
  	RhapsodyTracking.sendLinkEvent( 
		{ 
		eVar17: value,  
		prop18: page,  
		prop32: name, 
		eVar32: name,
		prop48: pageNum,
		eVar48: pageNum
		}, 
		{ 
		type: 'custom', 
		linkName: value, 
		events: 'event8' 
		} 
  	);

}