/**
 * AdTooltip Object
 */
var AdTooltip = {
	continuePlayback: false,
	
	addStyles: function(styles) {
		var styleSheet = null;
		if (document.createStyleSheet) {
			styleSheet = document.createStyleSheet();
		} else {
			var head = document.getElementsByTagName("head")[0];
			styleSheet = document.createElement("style");
			head.appendChild(styleSheet);
		}
	
		if (Sys.Browser.agent === Sys.Browser.InternetExplorer) {
			styleSheet.cssText = styles;
		} else if (Sys.Browser.agent === Sys.Browser.Safari) {
			styleSheet.innerText = styles;
		} else {
			styleSheet.innerHTML = styles;
		}
	},

	close: function() {
		if (typeof(window.tip) != 'undefined') {
		    window.tip.hide();
		}
	},
	
	reposition: function() {
	    var paramHeight = 286; 
	    var paramWidth = 300;
	
	    /* Bug #54780, check object tag (id="shell") instead of enclosing div. 
	       On IE there's one 'object' tag, in FF two nested tags. */
	    var swfDiv;
	    if (Sys.Browser.agent === Sys.Browser.InternetExplorer) {
		    swfDiv = document.getElementById('shell');
	    } else if (Sys.Browser.agent === Sys.Browser.Safari) {
		    swfDiv = document.getElementById('shell');
	    } else { // Firefox
		    swfDiv = document.getElementById('shell').getElementsByTagName('object')[0];
	    }
	
		var swfPos = MySpaceMusic.getElementPosition(swfDiv);
	
		// calculate the center position
		var leftMargin = 0;
		if (swfDiv.offsetWidth > paramWidth) {
			leftMargin = (swfDiv.offsetWidth - paramWidth) / 2
		}
		
		/* Let's hope Profiles keeps MusicPlayerControl.Width alive. */
		var topOffsetAdd = (MusicPlayerControl.Width == "450") ? 44 : 99;
		window.tip._tipDiv.style.left = (swfPos.x + leftMargin) + 'px';
		window.tip._tipDiv.style.top = (swfPos.y + topOffsetAdd) + 'px';	
	},

/*************************** Public Functions ****************************/
	
	open: function(continuePlayback) {
	    /* Store flag sent in by media player, so we can restart playback or not. 
	    *  If undefined, that means player didn't send one. */
	    if (typeof(continuePlayback) != "undefined")
            AdTooltip.continuePlayback = continuePlayback;
            
	    // Player can call tootip multiple times now, we need to close previous.
		AdTooltip.close();
	
	    var paramHeight = 286; 
	    var paramWidth = 300;
	
	    /* Bug #54780, check object tag (id="shell") instead of enclosing div. 
	       On IE there's one 'object' tag, in FF two nested tags. */
	    var swfDiv;
	    if (Sys.Browser.agent === Sys.Browser.InternetExplorer) {
		    swfDiv = document.getElementById('shell');
	    } else if (Sys.Browser.agent === Sys.Browser.Safari) {
		    swfDiv = document.getElementById('shell');
	    } else { // Firefox
		    swfDiv = document.getElementById('shell').getElementsByTagName('object')[0];
	    }
	
		var swfPos = MySpaceMusic.getElementPosition(swfDiv);
	
		// calculate the center position
		var leftMargin = 0;
		if (swfDiv.offsetWidth > paramWidth) {
			leftMargin = (swfDiv.offsetWidth - paramWidth) / 2
		}
		
		/* Let's hope Profiles keeps MusicPlayerControl.Width alive. */
		var topOffsetAdd = (MusicPlayerControl.Width == "450") ? 44 : 99;
	
		var cssText = '.tooltipdiv .helper{background:none;border:none;}.tooltipdiv .helperarrow{display:none;}.tooltipleft{margin-left:10px;}';
		AdTooltip.addStyles(cssText);
		content = "<iframe scrolling='no' style='position:absolute;' id='musicFlashPlayerContent' height='" + paramHeight + "' width='" + paramWidth + "' frameborder='0' src='" + MusicPlayerControl.TooltipUrl + "'></iframe>";
		window.tip = $create(MySpace.UI.Tooltip, { content: content, autoPos: false, hover: false, tipPos: 'bottom', margin: 0 }, null, null, $get(MusicPlayerControl.SwfObjectDiv));
		window.tip._tipDiv.childNodes[1].style.display='none';
		window.tip._tipDiv.childNodes[2].childNodes[0].style.display='none';
		window.tip._tipDiv.childNodes[2].childNodes[2].style.display='none';
		window.tip._tipDiv.childNodes[3].style.display='none';
		window.tip._tipDiv.childNodes[2].style.background='transparent';
		window.tip.show();
		window.tip._tipDiv.style.left = (swfPos.x + leftMargin) + 'px';
		window.tip._tipDiv.style.top = (swfPos.y + topOffsetAdd) + 'px';
		$addHandler(window, 'resize', AdTooltip.reposition);
	},
	
    /**
     * Bug#	63188: Re-start track in MediaPlayer based on its continuePlayback flag 
     * (sent in via MySpaceMusic.MedRecRefresh)
     */
 	onClickContinueListen: function() {
		if (typeof(window.parent) != 'undefined' && typeof(window.parent.tip) != 'undefined') {
	        window.parent.tip.hide();
        	if (AdTooltip.continuePlayback)
        	    window.parent.MySpaceMusic.getPlayerFlashObject().playCurrentTrack(); 
	    }         
	}
}
/**
 * Object to allow users to upgrade their Flash player
 */
var FlashUpgrade = {
    /** Returns true if MacOS X is < 10.4. */
    checkIfBelow104: function () {
        if ((Sys.Browser.agent === Sys.Browser.Safari) && (Sys.Browser.version < 200)) {
             return true;
        }
        if (Sys.Browser.agent === Sys.Browser.Firefox) {
             var oscpu = navigator.oscpu;
             return (oscpu.indexOf("10.3")!=-1) || (oscpu.indexOf("10.2")!=-1);
        }
        
        return false;
    },

/********************** Public Functions **********************/

    /** 
     * Init is called right at page load trying to figure if we need Flash upgrade or not.
     * The flash SWFObject is created here
     */
    Init: function () {
        var fo = null;
        try {
            fo = new SWFObject(MusicPlayerControl.EmbedHandlerURL, "shell", MusicPlayerControl.Width, MusicPlayerControl.Height, MusicPlayerControl.PlayerVersion, MusicPlayerControl.BgColor);
        } catch (e) {
        }

        var version = MusicPlayerControl.PlayerVersion.split(".");
        var major = false;
        var majorEq = false;
        var minor = false;
        var minorEq = false;
        var rev = false;

        if (fo && fo.installedVer != undefined) {
            major = fo.installedVer.major > version[0];
            majorEq = fo.installedVer.major == version[0];
            minor = fo.installedVer.minor > version[1];
            minorEq = fo.installedVer.minor == version[1];
            rev = fo.installedVer.rev >= version[2];
        }
        
        // Test 3 conditions in sequence.
        if (major || (majorEq && minor) || (majorEq && minorEq && rev)) {
            if (fo) {
                // No flash upgrade needed.
                fo.addParam("allowScriptAccess", "always");
                fo.addParam("wmode", "transparent");
                fo.write(MusicPlayerControl.SwfObjectDiv);
            }
        } else {
            // Flash upgrade is needed.
            MusicPlayerControl.NeedUpgrade = true;
            document.getElementById(MusicPlayerControl.SwfObjectDiv).style.backgroundColor = "#FFFFFF";
            if (MusicPlayerControl.FlashUpgradeEnabled) {
                if (!MusicPlayerControl.IsPixelPlayer) {
                    document.getElementById(MusicPlayerControl.SwfObjectDiv).innerHTML = MusicPlayerControl.FlashUpgradeMarkup.replace('{0}', FlashUpgrade.GetFlashUpgradeURL(true));
                    if (MySpace.ClientContext.FunctionalContext == "MusicSinglePlaylist" || MySpace.ClientContext.FunctionalContext == "ArtistAlbums") {
			            $get('PlaylistsSinglePlayer').style.height = '172px';
			            $get('flashUpgradeBig').style.margin = '0px 0px 0px 67px';
		            }
		        } else {
                    // If PixelPlayer, we want to put upgrade message on click play button.
                }
            } else {
                document.getElementById(MusicPlayerControl.SwfObjectDiv).innerHTML = '<span style="color:#000000;"><blockquote>' + MusicPlayerControl.ResourcesGetFlash + '</blockquote></span>';
            }
        }
    },
    
    /** 
     * GetFlashUpgradeURL returns different URLs depending on platform detected.
     * This is called from MusicPlayerControl.ascx
     * @param {Boolean} FlashUpgradeEnabled
     */
    GetFlashUpgradeURL: function(FlashUpgradeEnabled) {
        // This is the default main flash upgrade URL.
        var flashUpgradeURL = MusicPlayerControl.AllOtherFlashUpgradeURL;

        /** We only do all this if FlashUpgradeEnabled */
        if (FlashUpgradeEnabled) {
            /** Use navigator.userAgent to detect platform. */
            var agt = navigator.userAgent.toLowerCase();
            var platform = navigator.platform.toLowerCase();
            var isWinme = false; var isWin98 = false; var isLinux = false; 
            var isMacOSX = false; var isMacOSXless104 = false; 
            var isMacppc = false; var isMacIntel = false; 

            isWinme = (agt.indexOf('win 9x 4.90')!=-1 && agt.indexOf('win')!=-1);
            isWin98 = (agt.indexOf("win98")!=-1) || (agt.indexOf("windows 98")!=-1);
            isLinux = (agt.indexOf("inux")!=-1);

            isMacOSX = (agt.indexOf("mac os x")!=-1);
            isMacOSXless104 = (isMacOSX && FlashUpgrade.checkIfBelow104());
            isMacppc = (isMacOSX && ((agt.indexOf("ppc")!=-1) || (agt.indexOf("powerpc")!=-1)));
            /** To detect MacIntel, we need to use navigator.platform. */
            isMacIntel = (isMacOSX && ((platform.indexOf("intel")!=-1)));
            
            if (isWin98 || isWinme) {
                // If isWin98 or isWinme, we need detect browser
                if (Sys.Browser.agent === Sys.Browser.InternetExplorer)
                    flashUpgradeURL = MusicPlayerControl.WinME98_IE_FlashUpgradeURL;
                if (Sys.Browser.agent === Sys.Browser.Firefox)
                     flashUpgradeURL = MusicPlayerControl.WinME98_Netscape_FlashUpgradeURL;
            } else if (isLinux) {
                flashUpgradeURL = MusicPlayerControl.Linux_FlashUpgradeURL;
            } else if (isMacOSXless104) {
                // If isMacOSX and version < 10.4, we need detect processor
                if (isMacppc)
                    flashUpgradeURL = MusicPlayerControl.MacOSX_Less10dot4_PowerPC_FlashUpgradeURL;
                if (isMacIntel)
                    flashUpgradeURL = MusicPlayerControl.MacOSX_Less10dot4_Intel_FlashUpgradeURL;
            }
        }
        
        return flashUpgradeURL;
    }
}
/**
 * LoginObj Object
 */

var LoginObj = {	
	ajaxActionHandler: '/Modules/MusicV2/Services/MusicUtil.ashx?action=EnforceLogin',
	req: null,
	_loginWin: null,

	Sleep: function(mSec) {
		setTimeout("LoginObj.EnforceLoginOpenComplete()", mSec);
	},

	LoginRedirect: function() {
		if (LoginObj.req.readyState == 4) {
			//alert(LoginObj.req.readyState + "     " + LoginObj.req.responseText);
			var json = eval('(' + LoginObj.req.responseText + ')');
			if (json.ServerResponse.IsRequestSuccessful) {
				window.location.href = json.ServerResponse.DisplayText;
			}
		}
	},

	EnforceLoginPOMP: function(url) {
		LoginObj._loginWin = window.open(decodeURI(url), "newWin", "", "");
		LoginObj.Sleep(1000);
	},

	EnforceLoginOpenComplete: function() {
	
		if (LoginObj._loginWin == null) {
			LoginObj.Sleep(1000);
		}
		else {
			if (LoginObj._loginWin.document == null) {
				LoginObj.Sleep(1000);
			}
			else {
				var swfDiv = LoginObj._loginWin.document.getElementById(MusicPlayerControl.SwfObjectDiv);
				if (swfDiv == null) {
					LoginObj.Sleep(1000);
				} else {
					LoginObj._loginWin.LoginObj.EnforceLogin();
				}
			}
		}
	}
}

/**
* Purchase Object
*/
var Purchase = {

    Popup: null,
    AlbumOnlySong: false,
    BuyOptionObjects: null,
    ClickedWhileSongPlaying: null,

    ButtonMouseOver: function(item, addMouseOverClass) {
        if (item != null && addMouseOverClass != "") {
            if (item.className == "")
                item.className = addMouseOverClass;
            else {
                var newClasses = "";
                var currentClasses = item.className.split(" ");
                for (var i = 0; i < currentClasses.length; i++)
                    if (currentClasses[i] == addMouseOverClass)
                    return;
                item.className += " " + addMouseOverClass;
            }
        }
    },

    ButtonMouseOut: function(item, removeMouseOverClass) {
        if (item != null && removeMouseOverClass != "") {
            var newClasses = "";
            var currentClasses = item.className.split(" ");
            for (var i = 0; i < currentClasses.length; i++)
                if (currentClasses[i] != removeMouseOverClass)
                newClasses += (newClasses ? " " : "") + currentClasses[i];
            item.className = newClasses;
        }
    },

    //Function used to open the purchase options poup	
    ButtonClicked: function() {
        if (Purchase.ClickTrackingEnabled())
            Purchase.ButtonClickTracking();
        //Override popup function in global.js
        MySpace.UI.hideElements = function(tagNames, TorF) {
            for (name in tagNames) {
                if (tagNames[name] == "object") {
                    tagNames[name] = "";
                }
            }
            for (var j = 0; j < tagNames.length; j++) {
                var t = document.getElementsByTagName(tagNames[j]);
                for (var i = 0; i < t.length; i++) {
                    if (TorF) t[i].setAttribute('origvis', t[i].style.visibility);
                    t[i].style.visibility = TorF ? "hidden" : (t[i].getAttribute('origvis') ? t[i].getAttribute('origvis') : "");
                }
            }
        }

        Purchase.OpenPopup(Purchase.CreatePopupContent());
    },

    //Function used to close the purchase options popup and open up the ringtones popup
    RingtonesButtonClicked: function(artist) {
        if (Purchase.ClickTrackingEnabled())
            Purchase.MakeBeaconRequest('', "ringtones", "jamster", MySpace.Application.keyDisabled("MusicJV_BuyButtonMultipleProviders"));

        if (MySpace.ClientContext.FunctionalContext != "PopUpPlayer")
            Purchase.Popup._hide();
        Ringtones.openBeta(artist);
    },

    CreatePopupContent: function() {
        var j = 0;
        var buyOptions = new Array();
        var ringtoneArtist = "";
        var iTunesButton = "<div id='poiTunesLogo'></div> \
							<div id='poiTunesPrice'>" + MySpaceRes.Purchase.For + "</div>";
        var amazonButton = "<div id='poAmazonLogo'></div> \
							<div id='poAmazonPrice'>" + MySpaceRes.Purchase.For + "</div>";
        var jamsterButton = "<div id='poRingtoneButtons'> \
								<H5 class='poHfive'><span id='poBoldText' class='poBoldText'>" + MySpaceRes.Purchase.ChooseMp3s + "</span></H5> \
								<div id='poRingtoneButton' class='poMusicButton' onclick=\"javascript:Purchase.RingtonesButtonClicked('{0}');\" > \
									<div id='poJamsterLogo'></div> \
									<div id='poJamsterPrice'>" + MySpaceRes.Purchase.Ringtones + "</div> \
								</div> \
							 </div>";
        var popupContent = "<div id='po'> \
								<div id='poGreeting'> \
									<H2 class='poHtwo'>" + MySpaceRes.Purchase.GreatChoice + "</H2> \
								</div>	\
								<div id='poInformation'> \
									<H5 class='poHfive'>" + MySpaceRes.Purchase.DownloadInformation + "</H5> \
								</div> \
								<div id ='poAlbumOnly'> \
									<H5 class='poHfive'><span id='poBoldText' class='poBoldText' style='color:red !important;font-weight:bold !important;font-size:10px !important;'>" + MySpaceRes.Purchase.AlbumOnly + "</span></h5> \
								</div> \
								<div id='poMusicButtons'> \
									<H5 class='poHfive'><span id='poBoldText' class='poBoldText'>" + MySpaceRes.Purchase.DownloadMp3s + "</span></H5>";
        var sortFunction = function(a, b) {
            var c = a.providerName;
            var d = b.providerName;
            if (c > d)
                return -1;
            if (c < d)
                return 1;
            return 0;
        };

        buyOptions = Purchase.BuyOptionObjects.split("|");
        //FIX: We oppose this bug
        for (j = 0; j < buyOptions.length; j++) {
            buyOptions[j] = eval('(' + buyOptions[j] + ')');
        }
        buyOptions.sort(sortFunction);
        //Loop through objects and generate buttons
        for (j = 0; j < buyOptions.length; j++) {
            switch (buyOptions[j].purchaseType.toLowerCase()) {
                case "song":
                    popupContent = MySpaceMusic.textFormat(popupContent, buyOptions[j].mediaName, buyOptions[j].artistName);
                    switch (buyOptions[j].providerName.toLowerCase()) {
                        case "amazon":
                            popupContent += "<div id='poMusicButton' class='poMusicButton' onclick=\"javaScript:Purchase.SongClicked('" + buyOptions[j].providerName + "','" + buyOptions[j].productId + "','" + ((buyOptions[j].mediaId != null) ? buyOptions[j].mediaId : "") + "','','');\">";
                            popupContent += MySpaceMusic.textFormat(amazonButton, (buyOptions[j].price == "") ? "FREE" : buyOptions[j].price);
                            break;
                        case "itunes":
                            popupContent += "<div id='poMusicButton' class='poMusicButtonNoBackground' onclick=\"javaScript:Purchase.SongClicked('" + buyOptions[j].providerName + "','" + buyOptions[j].productId + "','" + ((buyOptions[j].mediaId != null) ? buyOptions[j].mediaId : "") + "','','');\">";
                            popupContent += MySpaceMusic.textFormat(iTunesButton, (buyOptions[j].price == "") ? "FREE" : buyOptions[j].price);
                            break;
                        default:
                    }
                    popupContent += "</div>";
                    break;
                case "albumonly":
                    popupContent = MySpaceMusic.textFormat(popupContent, buyOptions[j].mediaName, buyOptions[j].artistName);
                    switch (buyOptions[j].providerName.toLowerCase()) {
                        case "amazon":
                            popupContent += "<div id='poMusicButton' class='poMusicButton' onclick=\"javaScript:Purchase.SongClicked('" + buyOptions[j].providerName + "','" + buyOptions[j].productId + "','" + ((buyOptions[j].mediaId != null) ? buyOptions[j].mediaId : "") + "','','');\">";
                            popupContent += MySpaceMusic.textFormat(amazonButton, (buyOptions[j].price == "") ? "FREE" : buyOptions[j].price);
                            break;
                        case "itunes":
                            popupContent += "<div id='poMusicButton' class='poMusicButtonNoBackground' onclick=\"javaScript:Purchase.SongClicked('" + buyOptions[j].providerName + "','" + buyOptions[j].productId + "','" + ((buyOptions[j].mediaId != null) ? buyOptions[j].mediaId : "") + "','','');\">";
                            popupContent += MySpaceMusic.textFormat(iTunesButton, (buyOptions[j].price == "") ? "FREE" : buyOptions[j].price);
                            break;
                        default:
                    }
                    popupContent += "</div>";
                    Purchase.AlbumOnlySong = true;
                    break;
                case "album":
                    popupContent = MySpaceMusic.textFormat(popupContent, buyOptions[j].mediaName, buyOptions[j].artistName);
                    switch (buyOptions[j].providerName.toLowerCase()) {
                        case "amazon":
                            popupContent += "<div id='poMusicButton' class='poMusicButton' onclick=\"javaScript:Purchase.AlbumClicked('" + buyOptions[j].providerName + "','" + buyOptions[j].productId + "','" + ((buyOptions[j].mediaId != null) ? buyOptions[j].mediaId : "") + "','','');\">";
                            popupContent += MySpaceMusic.textFormat(amazonButton, (buyOptions[j].price == "") ? "FREE" : buyOptions[j].price);
                            break;
                        case "itunes":
                            popupContent += "<div id='poMusicButton' class='poMusicButtonNoBackground' onclick=\"javaScript:Purchase.AlbumClicked('" + buyOptions[j].providerName + "','" + buyOptions[j].productId + "','" + ((buyOptions[j].mediaId != null) ? buyOptions[j].mediaId : "") + "','','');\">";
                            popupContent += MySpaceMusic.textFormat(iTunesButton, (buyOptions[j].price == "") ? "FREE" : buyOptions[j].price);
                            break;
                        default:
                    }
                    popupContent += "</div>";
                    break;
                case "playlist":
                    popupContent = "<div id='po'> \
										<div id='poGreeting'> \
											<H2 class='poHtwo'>" + MySpaceRes.Purchase.GreatChoice + "</H2> \
										</div>	\
										<div id='poInformation'> \
											<H5 class='poHfive'>" + MySpaceRes.Purchase.DownloadInformationPlaylist + "</H5> \
										</div> \
										<div id ='poAlbumOnly'> \
										</div> \
										<div id='poMusicButtons'> \
											<H5 class='poHfive'><span id='poBoldText' class='poBoldText'>" + MySpaceRes.Purchase.DownloadMp3s + "</span></H5>";
                    popupContent = MySpaceMusic.textFormat(popupContent, buyOptions[j].artistName, buyOptions[j].mediaName);
                    popupContent += "<div id='poMusicButton' class='poMusicButton' onclick=\"javaScript:Purchase.PlaylistClicked('" + buyOptions[j].providerName + "','" + buyOptions[j].productId + "','" + ((buyOptions[j].mediaId != null) ? buyOptions[j].mediaId : "") + "','','');\">";
                    popupContent += MySpaceMusic.textFormat(amazonButton, buyOptions[j].price);
                    popupContent += "</div>";
                    break;
                case "ringtone":
                    ringtoneArtist = buyOptions[j].artistName;
                    break;
                default:
            }
        }
        popupContent += "</div>"; //End of div: poMusicButtons
        if (ringtoneArtist != "")
            popupContent += MySpaceMusic.textFormat(jamsterButton, ringtoneArtist);
        popupContent += "</div>"; //End of div: po

        return popupContent;
    },

    //Functioned used to create the purchase options popup
    OpenPopup: function(content) {
        Purchase.Popup = MySpace.UI.Popup.create(content, '', Purchase.ClosePopupCallback);
        var currentPopupIndex = MySpace.UI.getElementsByClassName('popup_wrapper').length - 1;

        //Styling
        Purchase.Popup.set_top(50);
        Purchase.Popup.set_width(300);
        MySpace.UI.getElementsByClassName('popup_x')[currentPopupIndex].style.background = 'transparent url(http://x.myspacecdn.com/modules/musicv2/static/img/poCloseButton.png) no-repeat 0';
        MySpace.UI.getElementsByClassName('popup_x')[currentPopupIndex].style.width = '43px';
        MySpace.UI.getElementsByClassName('popup_title')[currentPopupIndex].style.padding = '0px';
        MySpace.UI.getElementsByClassName('popup_title')[currentPopupIndex].style.height = '0px';
        MySpace.UI.getElementsByClassName('popup_title')[currentPopupIndex].style.display = 'none';
        MySpace.UI.getElementsByClassName('popup_content')[currentPopupIndex].style.padding = '0px';
        MySpace.UI.getElementsByClassName('popup_content')[currentPopupIndex].style.margin = '0px';
        MySpace.UI.getElementsByClassName('popup_content')[currentPopupIndex].style.border = '2px black solid';
        MySpace.UI.getElementsByClassName('popup_box')[currentPopupIndex].style.padding = '0px';
        MySpace.UI.getElementsByClassName('popup_box')[currentPopupIndex].style.border = '0px';
        MySpace.UI.getElementsByClassName('popup_buttons')[currentPopupIndex].style.padding = '0px';
        MySpace.UI.getElementsByClassName('popup_buttons')[currentPopupIndex].style.margin = '0px';
        MySpace.UI.getElementsByClassName('popup_x')[currentPopupIndex].style.top = '10px';

        if (Purchase.AlbumOnlySong)
            $get('poAlbumOnly').style.visibility = 'visible';
        else
            $get('poAlbumOnly').style.visibility = 'hidden';

        Purchase.AlbumOnlySong = false;

        Purchase.Popup.show();
    },

    //Function to resume music if player was playing prior to popup
    ClosePopupCallback: function() {
        //The call is from the media player
        if (Purchase.ClickedWhileSongPlaying == null) {
            if ((Sys.Browser.agent === Sys.Browser.Firefox) && (MySpace.ClientContext.FunctionalContext === 'UserViewProfile'))
                document.getElementById('shell').getElementsByTagName('object')[0].resumeAfterRingtonesClose();
            else
                document.getElementById('shell').resumeAfterRingtonesClose();
        } else {
            //The call is from the HTML buy button
            if (Purchase.ClickedWhileSongPlaying) {
                if ((Sys.Browser.agent === Sys.Browser.Firefox) && (MySpace.ClientContext.FunctionalContext === 'UserViewProfile')) {
                    document.getElementById('shell').getElementsByTagName('object')[0].playCurrentTrack();
                } else {
                    document.getElementById('shell').playCurrentTrack();
                }
            }

            Purchase.ClickedWhileSongPlaying = null;
        }
    },

    AlbumClicked: function(provider, productId, albumId, artistName, albumName) {
        if (Purchase.ClickTrackingEnabled())
            Purchase.MakeBeaconRequest(albumId, "album", provider, MySpace.Application.keyDisabled("MusicJV_BuyButtonMultipleProviders"));

        switch (provider.toLowerCase()) {
            case "amazon":
                if (MusicPlayerControl.AllowAmazonInPlace && productId != undefined && productId != null && productId != "")
                    Purchase.AmazonInPlace(productId);
                else
                    Purchase.AmazonAffiliate(productId, "album");
                break;
            case "itunes":
                if (productId != undefined && productId != null && productId != "") {
                    var providers = eval('(' + MusicPlayerControl.Providers + ')');
                    var urlCulture = MySpace.Cookies.MSCulture.get_values().IPCulture.toLowerCase();
                    if (urlCulture == "en-au" || urlCulture == "en-nz" || urlCulture == "en-gb") {
                        encodedProductId = encodeURIComponent(productId);
                        iTunesURL = MySpaceMusic.textFormat(providers['iTunes'].Address, encodedProductId + "%3F");
                    }
                    else if (urlCulture == "en-us" || urlCulture == "es-us") {
                        doubleEncodedProductId = encodeURIComponent(encodeURIComponent(productId));
                        iTunesURL = MySpaceMusic.textFormat(providers['iTunes'].Address, doubleEncodedProductId + "%253F");
                    }
                    else
                        iTunesURL = MySpaceMusic.textFormat(providers['iTunes'].Address, '?' + productId);
                    var newWindow = window.open(iTunesURL, 'iTunesSA', 'status=yes, scrollbars=yes, resizable=yes, toolbar=yes, location=yes, directories=no, menubar=yes, width=950, height=700');
                    MySpaceMusic.checkForPopUpBlocker(newWindow);
                }
                break;
            default:
        }
    },

    SongClicked: function(provider, productId, songId, artistName, songName) {

        if (Purchase.ClickTrackingEnabled())
            Purchase.MakeBeaconRequest(songId, "song", provider, MySpace.Application.keyDisabled("MusicJV_BuyButtonMultipleProviders"));

        switch (provider.toLowerCase()) {
            case "amazon":
                if (MusicPlayerControl.AllowAmazonInPlace && productId != undefined && productId != null && productId != "")
                    Purchase.AmazonInPlace(productId);
                else
                    Purchase.AmazonAffiliate(productId, "song");
                break;
            case "itunes":
                if (productId != undefined && productId != null && productId != "") {
                    var providers = eval('(' + MusicPlayerControl.Providers + ')');                   
                    var urlCulture = MySpace.Cookies.MSCulture.get_values().IPCulture.toLowerCase();
                    if (urlCulture == "en-au" || urlCulture == "en-nz" || urlCulture == "en-gb") {
                        encodedProductId = encodeURIComponent(productId);
                        iTunesURL = MySpaceMusic.textFormat(providers['iTunes'].Address, encodedProductId + "%26");
                    }
                    else if (urlCulture == "en-us" || urlCulture == "es-us") {
                        doubleEncodedProductId = encodeURIComponent(encodeURIComponent(productId));
                        iTunesURL = MySpaceMusic.textFormat(providers['iTunes'].Address, doubleEncodedProductId + "%2526");
                    }
                    else
                        iTunesURL = MySpaceMusic.textFormat(providers['iTunes'].Address, '?' + productId);
                    var newWindow = window.open(iTunesURL, 'iTunesSA', 'status=yes, scrollbars=yes, resizable=yes, toolbar=yes, location=yes, directories=no, menubar=yes, width=950, height=700');
                    MySpaceMusic.checkForPopUpBlocker(newWindow);
                }
                break;
            default:
        }
    },

    PlaylistClicked: function(provider, productIds, playlistId) {
        if (Purchase.ClickTrackingEnabled())
            Purchase.MakeBeaconRequest(playlistId, "playlist", provider, MySpace.Application.keyDisabled("MusicJV_BuyButtonMultipleProviders"));

        switch (provider.toLowerCase()) {
            case "amazon":
                switch (MySpace.ClientContext.FunctionalContext) {
                    case "MusicSinglePlaylist":
                        buyPlaylistUrl = MySpaceMusic.textFormat("http://www.amazon.com/gp/browse.html?node={0}&tag={1}&ASINs={2}",
																"1266319011",
																"playlistpurchase-20",
																productIds);
                        break;
                    case "CelebrityPromo":
                        buyPlaylistUrl = MySpaceMusic.textFormat("http://www.amazon.com/gp/browse.html?node={0}&tag={1}&ASINs={2}",
																"1266319011",
																"featuredplaylistpurchase-20",
																productIds);
                        break;
                    default:
                        buyPlaylistUrl = MySpaceMusic.textFormat("http://www.amazon.com/gp/browse.html?node={0}&tag={1}&ASINs={2}",
																"1266319011",
																"mys0d05-20",
																productIds);
                        break;
                }
                window.open(buyPlaylistUrl, 'AmazonSA', 'status=yes, scrollbars=yes, resizable=yes, toolbar=yes, location=yes, directories=no, menubar=yes, width=950, height=700');
                break;
            default:
        }
    },

    AmazonInPlace: function(ASIN) {
        var amazonURL = MusicPlayerControl.AmazonPrice + "&asin=" + ASIN + "&mode=";
        var popupWidth = 626;
        var popupHeight = 426;

        if (navigator.userAgent.toLowerCase().indexOf("firefox/") >= 0) {
            popupWidth = 611;
            popupHeight = 366;
        }

        amazonURL += "windowed";
        var newWindow = window.open(amazonURL, 'Amazon', 'status=no, scrollbars=no, resizable=no, toolbar=no, location=no, directories=no, menubar=no, width=610, height=400');
        MySpaceMusic.checkForPopUpBlocker(newWindow);
    },

    AmazonAffiliate: function(ASIN, mediaType) {
        standardAffUrl = "http://www.amazon.com/dp/" + ASIN;
        if (mediaType == "album") {
            //Append specific album tag
            switch (MySpace.ClientContext.FunctionalContext) {
                case "ArtistAlbums":
                    standardAffUrl += "?tag=albumalbumpurchase-20";
                    break;
                case "MusicSinglePlaylist":
                    standardAffUrl += "?tag=playlistalbumpurchase-20";
                    break;
                case "UserViewProfile":
                    if (MySpace.ProfileClientContext != null && MySpace.ProfileClientContext.ProfileType == 7)
                        standardAffUrl += "?tag=artistalbumpurchase-20";
                    else if (MySpace.ProfileClientContext != null && MySpace.ProfileClientContext.ProfileType == 8)
                        standardAffUrl += "?tag=brandalbumpurchase-20";
                    else
                        standardAffUrl += "?tag=useralbumpurchase-20";
                    break;
                case "CelebrityPromo":
                    standardAffUrl += "?tag=featuredalbumpurchase-20";
                    break;
                case "PopUpPlayer":
                    standardAffUrl += "?tag=pompalbumpurchase-20";
                    break;
                case "SiteSearch":
                    standardAffUrl += "?tag=searchalbumpurchase-20";
                    break;
                case "MusicTopCharts":
                    standardAffUrl += "?tag=chartsalbumpurchase-20";
                    break;    
                default:
                    standardAffUrl += "?tag=mys0d05-20";
            }
        }
        if (mediaType == "song") {
            //Append specific song tag
            switch (MySpace.ClientContext.FunctionalContext) {
                case "ArtistAlbums":
                    standardAffUrl = standardAffUrl + "?tag=albumsongpurchase-20";
                    break;
                case "MusicSinglePlaylist":
                    standardAffUrl += "?tag=playlistsongpurchase-20";
                    break;
                case "UserViewProfile":
                    if (MySpace.ProfileClientContext != null && MySpace.ProfileClientContext.ProfileType == 7)
                        standardAffUrl += "?tag=artistsongpurchase-20";
                    else if (MySpace.ProfileClientContext != null && MySpace.ProfileClientContext.ProfileType == 8)
                        standardAffUrl += "?tag=brandsongpurchase-20";
                    else
                        standardAffUrl += "?tag=usersongpurchase-20";
                    break;
                case "CelebrityPromo":
                    standardAffUrl += "?tag=featuredsongpurchase-20";
                    break;
                case "PopUpPlayer":
                    standardAffUrl += "?tag=pompsongpurchase-20";
                    break;
                case "Music":
                    standardAffUrl += "?tag=msmhomesongpurchase-20";
                    break;
                case "SiteSearch":
                    standardAffUrl += "?tag=searchsongpurchase-20";
                    break;
                case "MusicTopCharts":
                    standardAffUrl += "?tag=chartssongpurchase-20";
                    break; 
                default:
                    standardAffUrl = standardAffUrl + "?tag=mys0d05-20";
            }
        }
        var newWindow = window.open(standardAffUrl, 'AmazonSA', 'status=yes, scrollbars=yes, resizable=yes, toolbar=yes, location=yes, directories=no, menubar=yes, width=950, height=700');
        MySpaceMusic.checkForPopUpBlocker(newWindow);
    },

    ButtonClickTracking: function() {
        try
        {
            if(Purchase.BuyOptionObjects)  {               
                var buyOptions = Purchase.BuyOptionObjects.split("|");
                if (buyOptions.length > 0) {
                    var providers = '';
                    for (var j = 0; j < buyOptions.length; j++) {
                        buyOptions[j] = eval('(' + buyOptions[j] + ')');
                        providers += buyOptions[j].providerName.toLowerCase() + ",";
                    }
                    providers = providers.substring(0, providers.length - 1);
                    var srcType = buyOptions[0].purchaseType == "albumonly" ? "song" : buyOptions[0].purchaseType;
                    Purchase.MakeBeaconRequest(buyOptions[0].mediaId, srcType, providers, true);
                }
            }
        }
        catch(e) {}
    },

    /**
    * Function that finds the top level element for a song row given a sub element.
    */
    findTopLevelElement: function(elemT) {
        while (!(Sys.UI.DomElement.containsCssClass(elemT, 'msm_draggablesong') || Sys.UI.DomElement.containsCssClass(elemT, 'ui-draggable'))) {
            elemT = elemT.parentNode;
            //return null if we've reached the body element and haven't found the class
            if (elemT.tagName.toLowerCase() === 'body')
                return null;
        }
        return elemT;
    },

    AddMusicSearchClickTracking: function(beaconData) {
        var buyBtn = Purchase.ClickedBuyButton;
        if (beaconData.srcType === "song") {
            var parentElem = Purchase.findTopLevelElement(buyBtn);
            if (parentElem != null) {
                beaconData.albumid = parentElem.getAttribute('msm_albumid');
                beaconData.searchid = parentElem.getAttribute('msm_searchid');
                beaconData.pagenum = parentElem.getAttribute('msm_pn');
                beaconData.filter = parentElem.getAttribute('msm_filter');
                beaconData.sort = parentElem.getAttribute('msm_sort');
                beaconData.origin = parentElem.getAttribute('msm_origin');
                beaconData.dorigin = parentElem.getAttribute('msm_dorigin');
                beaconData.action = parentElem.getAttribute('msm_action');
                beaconData.rank = parentElem.getAttribute('msm_rank');
            }
        }
        else if (beaconData.srcType === "album") {
            if (buyBtn.parentNode.id === "AlbumBuy" || buyBtn.parentNode.id === "AlbumBuyNew") {
                parentElem = buyBtn.parentNode;
                beaconData.artistid = parentElem.getAttribute('msm_artistid');
                beaconData.searchid = parentElem.getAttribute('msm_searchid');
                beaconData.pagenum = parentElem.getAttribute('msm_pn');
                beaconData.filter = parentElem.getAttribute('msm_filter');
                beaconData.sort = parentElem.getAttribute('msm_sort'); 
                beaconData.origin = parentElem.getAttribute('msm_origin');
                beaconData.dorigin = parentElem.getAttribute('msm_dorigin'); 
                beaconData.action = parentElem.getAttribute('msm_action'); 
                beaconData.rank = parentElem.getAttribute('msm_rank');
            }
        }
        return beaconData;
    },

    MakeBeaconRequest: function(id, type, providers, isBuyButton) {
        var beaconData;            
        if (isBuyButton) {
            //buy button click tracking
            beaconData = { type :"musicbuybtn", srcType: type};
            if (id && id !== '') {
                if (type === "song")
                    beaconData.songid = id;
                else if (type === "album")
                    beaconData.albumid = id;
                else if (type === "playlist")
                    beaconData.playlistid = id;
            }

            if (!MySpace.Application.keyDisabled("DWBeaconMusicBuyButton")) {
                beaconData.prov = providers;
                //determine if lightbox will be shown
                if (MySpace.Application.keyDisabled("MusicJV_BuyButtonMultipleProviders"))
                    beaconData.lb = "0";
                else
                    beaconData.lb = "1";
            }   

            //add data for music search
            if (MySpace.ClientContext.FunctionalContext === "SiteSearch" && !MySpace.Application.keyDisabled("DWBeaconMusicSearch") && Purchase.ClickedBuyButton) {
                beaconData = Purchase.AddMusicSearchClickTracking(beaconData);
            }
        }
        else if (!MySpace.Application.keyDisabled("DWBeaconMusicBuyButton")) {
            //lightbox click tracking
            beaconData = { type : "musicbuylb", ptype: type, prov: providers };
        }

        if(beaconData)
            MySpace.Beacon.Request(beaconData);
            
    },

    ClickTrackingEnabled: function() {
        return MySpace.BeaconData && MySpace.Beacon &&
            (!MySpace.Application.keyDisabled("DWBeaconMusicBuyButton") ||
            MySpace.ClientContext.FunctionalContext === "SiteSearch" && !MySpace.Application.keyDisabled("DWBeaconMusicSearch"));
    }
}
/**
 * Ringtones Object definition
 */
var Ringtones = {
	Popup:null,
	
	open: function(currSong) 
	{
		var jambaURL = "";
		var aSong = []; 		//Temp array for a song: aSong[0] = artist | aSong[1] = song title
		        
		//Override popup function in global.js
		MySpace.UI.hideElements = function(tagNames, TorF) {
			for(name in tagNames)
			{
				if( tagNames[name] == "object" )
				{
					tagNames[name] = "";
				}
			}
			for(var j=0;j<tagNames.length;j++)
			{
				var t = document.getElementsByTagName(tagNames[j]);
				for(var i=0;i<t.length;i++)
				{
					if (TorF) t[i].setAttribute('origvis', t[i].style.visibility);    
					t[i].style.visibility = TorF? "hidden" : (t[i].getAttribute('origvis') ? t[i].getAttribute('origvis') : "");
				}
			}
		}
		
		if (currSong != "")
		{
			currSong = currSong.replace(/[^A-Za-z0-9\s:-]/g, "").replace(/[\s]/g, "+");
			aSong = currSong.split(":");
			jambaURL = MusicPlayerControl.JambaUrl + aSong[0];
			//Detect culture for Jamba generation
			switch (MySpace.Cookies.MSCulture.get_values().IPCulture.toLowerCase()) 
			{
				case "en-gb":
					//Create new window for Jamba for UK
					var newWindow = window.open(jambaURL, 'JambaRingtones', 'status=no, scrollbars=no, resizable=no, toolbar=no, location=no, directories=no, menubar=no, width=757, height=721');
					MySpaceMusic.checkForPopUpBlocker(newWindow);
					break;
				case "en-au":
					//Create new window for Jamba AU
					jambaURL = "http://ad.jamster.com.au/landingpages/campaigns/int_o_flash/myspacemusic/?adv_partner=0017&partner_var=Music&artist=" + aSong[0];
					var newWindow = window.open(jambaURL, 'JambaRingtones', 'status=no, scrollbars=no, resizable=no, toolbar=no, location=no, directories=no, menubar=no, width=757, height=721');
					MySpaceMusic.checkForPopUpBlocker(newWindow);
					break;
				case "en-nz":
					jambaURL = "http://ad.jamster.co.nz/landingpages/campaigns/int_o_flash/myspacemusic/?adv_partner=0017&partner_var=Music&artist=" + aSong[0];
					//Create new window for Jamba NZ
					var newWindow = window.open(jambaURL, 'JambaRingtones', 'status=no, scrollbars=no, resizable=no, toolbar=no, location=no, directories=no, menubar=no, width=757, height=721');
					MySpaceMusic.checkForPopUpBlocker(newWindow);
					break;
				default:
					//POMP will open up in new window
					if (MySpace.ClientContext.FunctionalContext == "PopUpPlayer")
					{
						var newWindow = window.open(jambaURL, 'JambaRingtones', 'status=no, scrollbars=yes, resizable=no, toolbar=no, location=no, directories=no, menubar=no, width=780, height=820');
						MySpaceMusic.checkForPopUpBlocker(newWindow);
					}
					else
					{
						content = "<iframe id='ringtonesIframe' width='763' height='820' scrolling='no' style='border:0;' src='" + jambaURL + "'></iframe>";
						var ringtonesPopup = MySpace.UI.Popup.create(content, '', Ringtones.close);



						$get('ringtonesIframe').style.display = 'block';
						ringtonesPopup.set_top(10);
						ringtonesPopup.set_width(773);
						for (var j = 0; j < MySpace.UI.getElementsByClassName('popup_wrapper').length; j++)
						{
							MySpace.UI.getElementsByClassName('popup_content')[j].style.padding = '0px';
							MySpace.UI.getElementsByClassName('popup_content')[j].style.width = '763px';
						}
						ringtonesPopup.show();				
					}
			}
		}
		
	},
    
	openBeta: function(artist) 
	{
		var jambaURL = "";
				        
		//Override popup function in global.js
		MySpace.UI.hideElements = function(tagNames, TorF) {
			for(name in tagNames)
			{
				if( tagNames[name] == "object" )
				{
					tagNames[name] = "";
				}
			}
			for(var j=0;j<tagNames.length;j++)
			{
				var t = document.getElementsByTagName(tagNames[j]);
				for(var i=0;i<t.length;i++)
				{
					if (TorF) t[i].setAttribute('origvis', t[i].style.visibility);    
					t[i].style.visibility = TorF? "hidden" : (t[i].getAttribute('origvis') ? t[i].getAttribute('origvis') : "");
				}
			}
		}
		
		if (artist != "")
		{
			artist = artist.replace(/[^A-Za-z0-9\s:-]/g, "").replace(/[\s]/g, "+");
			jambaURL = MusicPlayerControl.JambaUrl + artist;
			
			//Detect culture for Jamba generation
			switch (MySpace.Cookies.MSCulture.get_values().IPCulture.toLowerCase()) 
			{
				case "en-gb":
					//Create new window for Jamba UK
					var newWindow = window.open(jambaURL, 'JambaRingtones', 'status=no, scrollbars=no, resizable=no, toolbar=no, location=no, directories=no, menubar=no, width=757, height=721');
					MySpaceMusic.checkForPopUpBlocker(newWindow);
					break;
				case "en-au":
					//Create new window for Jamba AU
					jambaURL = "http://ad.jamster.com.au/landingpages/campaigns/int_o_flash/myspacemusic/?adv_partner=0017&partner_var=Music&artist=" + artist;
					var newWindow = window.open(jambaURL, 'JambaRingtones', 'status=no, scrollbars=no, resizable=no, toolbar=no, location=no, directories=no, menubar=no, width=757, height=721');
					MySpaceMusic.checkForPopUpBlocker(newWindow);
					break;
				case "en-nz":
					jambaURL = "http://ad.jamster.co.nz/landingpages/campaigns/int_o_flash/myspacemusic/?adv_partner=0017&partner_var=Music&artist=" + artist;
					//Create new window for Jamba NZ
					var newWindow = window.open(jambaURL, 'JambaRingtones', 'status=no, scrollbars=no, resizable=no, toolbar=no, location=no, directories=no, menubar=no, width=757, height=721');
					MySpaceMusic.checkForPopUpBlocker(newWindow);
					break;
				default:
					//POMP will open up in new window
					if (MySpace.ClientContext.FunctionalContext == "PopUpPlayer")
					{
						var newWindow = window.open(jambaURL, 'JambaRingtones', 'status=no, scrollbars=yes, resizable=no, toolbar=no, location=no, directories=no, menubar=no, width=780, height=820');
						MySpaceMusic.checkForPopUpBlocker(newWindow);
					}
					else
					{
						content = "<iframe id='ringtonesIframe' width='763' height='820' scrolling='no' style='border:0;' src='" + jambaURL + "'></iframe>";
						Ringtones.Popup = MySpace.UI.Popup.create(content, '', Ringtones.ClosePopupCallback);
						var currentPopupIndex = MySpace.UI.getElementsByClassName('popup_wrapper').length-1;
						
						//Styling
						$get('ringtonesIframe').style.display = 'block';
						Ringtones.Popup.set_top(10);
						Ringtones.Popup.set_width(768);
						MySpace.UI.getElementsByClassName('popup_x')[currentPopupIndex].style.background = 'transparent url(http://x.myspacecdn.com/modules/musicv2/static/img/poCloseButton.png) no-repeat 0';
						MySpace.UI.getElementsByClassName('popup_x')[currentPopupIndex].style.width = '43px';
						MySpace.UI.getElementsByClassName('popup_title')[currentPopupIndex].style.padding = '0px';
						MySpace.UI.getElementsByClassName('popup_title')[currentPopupIndex].style.height = '0px';
						MySpace.UI.getElementsByClassName('popup_title')[currentPopupIndex].style.display = 'none';
						MySpace.UI.getElementsByClassName('popup_content')[currentPopupIndex].style.padding = '0px';
						MySpace.UI.getElementsByClassName('popup_content')[currentPopupIndex].style.margin = '0px';
						MySpace.UI.getElementsByClassName('popup_content')[currentPopupIndex].style.border = '2px black solid';
						MySpace.UI.getElementsByClassName('popup_box')[currentPopupIndex].style.padding = '0px';
						MySpace.UI.getElementsByClassName('popup_box')[currentPopupIndex].style.border = '0px';
						MySpace.UI.getElementsByClassName('popup_buttons')[currentPopupIndex].style.padding = '0px';
						MySpace.UI.getElementsByClassName('popup_buttons')[currentPopupIndex].style.margin = '0px';
						MySpace.UI.getElementsByClassName('popup_x')[currentPopupIndex].style.top= '10px';

						Ringtones.Popup.show();				
					}
			}
		}		
	},
	
	close: function() {
	    var flash = MySpaceMusic.getPlayerFlashObject();
		if (flash != null)
		   flash.resumeAfterRingtonesClose();
	},
	
	//Function used after closing ringtones popup to open up purchase options popup
	ClosePopupCallback: function() {
		Ringtones.Popup._hide();
		Purchase.ButtonClicked();
	}
}

/**
 * MySpaceMusic Object definition
 */
var MySpaceMusic = {

    focusStatus: true,
    playerLoaded: false,
    prevSongID: null,
    prevArtistIDArray: null,
    isPlayingAudioAd: false,

    createPopUp: function(specificContent, popupW, popupH, invCloseBtn, module) {
        var customizedTitle = "";
        var customizedContent = specificContent;
        var divObj = document.createElement("div");
        var topPos = 50;
        var width = 100;

        var popupObj;
        if (module == "optin") {
            popupObj = MySpace.UI.Popup.create(customizedContent, "");
            popupObj.set_width(popupW + 18);
            if (MySpace.ClientContext.FunctionalContext == "PopUpPlayer" && module == "optin") {
                popupObj.set_top(0);
            }
            else {
                if (module == "optin" && Sys.Browser.agent == Sys.Browser.InternetExplorer && Sys.Browser.version == 6) {
                    popupObj.set_top(topPos);
                }
            }
        } else {
            divObj.innerHTML = "<div id='divWrapper' class='popup_wrapper' style='z-index:1000201;left:0px;width: " + width + "%;display:none;visibility:hidden;text-align:center;padding:auto auto auto auto;'><div class='appspopup_box' style='width:" + popupW + "px; height:" + popupH + "px; margin-left: auto;margin-right: auto;border: 4px solid #6698CB;'>" + invCloseBtn + "<div></div><div class='appspopup_content' style='margin:0 auto;'></div><div class='appspopup_buttons'></div></div></div>";
            popupObj = $create(MySpace.UI._Popup, { title: customizedTitle, content: customizedContent, left: 0, top: topPos }, null, null, divObj.firstChild);
        }

        return popupObj;
    },

    textFormat: function(text) {
        var argsCount = arguments.length - 1;
        for (var i = 0; i < argsCount; i++)
            text = text.replace(new RegExp("\\{" + i + "\\}", "gi"), arguments[i + 1]);
        return text;
    },

    getElementPosition: function(element) {
        var left = 0;
        var top = 0;
        if (element) {
            while (element.offsetParent) {
                left += element.offsetLeft;
                top += element.offsetTop;
                element = element.offsetParent;
            }
            left += element.offsetLeft;
            top += element.offsetTop;
        }

        return { x: left, y: top };
    },

    showPopupBlockerMessage: function() {
        var popupPopped = false;
        var iFrame = document.createElement('iframe');
        iFrame.setAttribute('src', '/modules/musicv2/pages/NoAmazonPopupMessaging.aspx');
        iFrame.setAttribute('id', 'amazonNoPopUp')
        iFrame.style.position = 'absolute';
        iFrame.setAttribute('allowTransparency', 'true');
        iFrame.setAttribute('frameBorder', '0');
        iFrame.style.backgroundColor = 'transparent';
        var iFrameHeight = 300;
        var iFrameWidth = 300;
        var swfDiv = document.getElementById(MusicPlayerControl.SwfObjectDiv);
        var swfPos = MySpaceMusic.getElementPosition(swfDiv);
        if (swfDiv.offsetHeight > iFrameHeight) {
            // regular player
            iFrame.style.top = swfPos.y + 'px';
        }
        else {
            // small player
            var pos_y = swfPos.y - (iFrameHeight - swfDiv.offsetHeight) / 2;
            iFrame.style.top = pos_y + 'px';
        }
        if ((parseInt(MusicPlayerControl.Height) == 1) && (parseInt(MusicPlayerControl.Width) == 1)) { // pixel player
            iFrame.style.position = 'fixed';
            iFrame.style.left = '44%';
            iFrame.style.top = '44%';
        } else {
            iFrame.style.left = swfPos.x + 'px';
            iFrame.style.width = iFrameWidth + 'px';
        }

        iFrame.style.height = iFrameHeight + 'px';
        iFrame.style.borderStyle = 'none';
        document.body.appendChild(iFrame);
    },

    /**
    * getPlayerFlashObject is used because we can't detect 'shell' on Profile players, as they've removed it.
    */
    getPlayerFlashObject: function() {
        var flashObj = document.getElementsByTagName('object');
        for (i in flashObj) {
            if (typeof (flashObj[i].playSong) != 'undefined')
                return flashObj[i];
        }

        return null;
    },

    /**
    * ****************** Public API called from Media Player ***********************
    */

    Focus: function() {
        MySpaceMusic.focusStatus = true;
    },

    Blur: function() {
        MySpaceMusic.focusStatus = false;
    },

    IsWindowFocused: function() {
        return MySpaceMusic.focusStatus;
    },

    onBuyClickedFromHTML: function(buyBtn, buyOptions) {
        if (document.getElementById('shell')) {
            if ((Sys.Browser.agent === Sys.Browser.Firefox) && (MySpace.ClientContext.FunctionalContext === 'UserViewProfile')) {
                Purchase.ClickedWhileSongPlaying = document.getElementById('shell').getElementsByTagName('object')[0].getPlayingState();
                if (Purchase.ClickedWhileSongPlaying)
                    document.getElementById('shell').getElementsByTagName('object')[0].pauseCurrentTrack();
            }
            else {
                Purchase.ClickedWhileSongPlaying = document.getElementById('shell').getPlayingState();
                if (Purchase.ClickedWhileSongPlaying)
                    document.getElementById('shell').pauseCurrentTrack();
            }
        }
        Purchase.ClickedBuyButton = buyBtn;
        MySpaceMusic.onBuyClicked(buyOptions);
    },

    onBuyClicked: function(buyOptions) {
        Purchase.BuyOptionObjects = buyOptions;
        Purchase.ButtonClicked();
    },

    onFindRingtoneClicked: function(artistArr, currSong) {
        if (MusicPlayerControl.AllowJamba)
            Ringtones.open(currSong)
    },

    /**
    * onPlayingTrack callback
    * 
    * @param {Object} songID
    * @param {Object} artistIDArray
    * @param {Object} genreIDs
    * @param {Object} isPremium
    */
    onPlayingTrack: function(songID, artistIDArray, genreIDs, isPremium) {
        if (MySpace.Ads && MySpace.Ads.BandType) {
            MySpace.Ads.BandType.Genre1 = genreIDs[0];
            MySpace.Ads.BandType.Genre2 = genreIDs[1];
            MySpace.Ads.BandType.Genre3 = genreIDs[2];
        }

        if (songID != MySpaceMusic.prevSongID && artistIDArray != MySpaceMusic.prevArtistIDArray) {

            if (document.getElementById('feedResult') != null) {
                if (artistIDArray[0] > 0) {
                    if (document.getElementById('ArtistFeeds') != null) {
                        MySpace.Web.Modules.MusicV2.Services.PopUpPlayer.GetMultipleArtistsUpdateFromArtistUpdatesApi(artistIDArray, MySpaceMusic.WebSvrManager.ArtistUpdateSuccess, MySpaceMusic.WebSvrManager.OnFailure);
                    } else {
                        MySpace.Web.Modules.MusicV2.Services.PopUpPlayer.GetMultipleArtistsUpdate(artistIDArray, MySpaceMusic.WebSvrManager.ArtistUpdateSuccess, MySpaceMusic.WebSvrManager.OnFailure);
                    }
                } else {
                    document.getElementById('feedResult').innerHTML = '<br/><div class="activityFeedNoUpdate">' + MySpaceRes.PopUpPlayer.NoUpdatesForThisArtist + '</div>';
                }
            }
            MySpaceMusic.prevSongID = songID;
            MySpaceMusic.prevArtistIDArray = artistIDArray;
        }

        /* This will update SimilarSongs module in pages where it exists. Verifies similar songs div is present before loading module */
        if (document.getElementById('msaaSimilarSongsDiv') != null)
        {
			if (typeof (Carousel) != 'undefined' && songID > 0 && songID != Carousel.seedSong) {
				if (typeof (PlayButton) != 'undefined' && !PlayButton.IsSimilarSong(PlayButton._oldElem)) {
					var metadata = document.getElementById('shell').getSongMetadata();
					var artistId = (metadata[6] != null) ? metadata[6] : -1;
					Carousel.loadModule(songID, artistId);
				}
			}
		}
    },

    onBuyAlbumClicked: function(ASIN, albumId, artistName, albumName) {
        Purchase.AlbumClicked("Amazon", ASIN, albumId, artistName, albumName);
    },

    onBuySongClicked: function(ASIN, songId, artistName, songName) {
        Purchase.SongClicked("Amazon", ASIN, songId, artistName, songName);
    },

    DisablePlayButtons: function() {
        //For charts (don't have ids :(
        try {
            jQuery.each($('.chrtSongd1d0CSS'), function(index, item) {
                $(item).html($(item).html().replace(/onmouseover/, 'offmouseover').replace(/onclick/, 'offclick').replace(/title/, 'offtitle').replace(/search_btn_play.gif/, 'search_btn_playDisabled.gif'));
            });
        } catch (Error) { }
        //For other pages
        try {
            images = document.getElementsByTagName('*');
            for (var i = 0; i < images.length; i++) {
                if (images[i].id.indexOf('PlayButton_') != -1 || images[i].id.indexOf('SimilarSong_') != -1) {
                    images[i].onclick = function() { };
                    try {
                        images[i].setAttribute('onclick', '');
                        $clearHandlers(images[i]);
                    } catch (ex2) { }
                    images[i].style['opacity'] = '.2';
                    images[i].style['filter'] = 'alpha(opacity=20)';
                    images[i].style['-ms-filter'] = 'progid:DXImageTransform.Microsoft.Alpha(Opacity=20)';
                }
            }
        } catch (ex) { }
    },

    EnablePlayButtons: function() {
        //For charts (don't have ids :(
        try {
            jQuery.each($('.chrtSongd1d0CSS'), function(index, item) {
                $(item).html($(item).html().replace(/offmouseover/, 'onmouseover').replace(/offclick/, 'onclick').replace(/offtitle/, 'title').replace(/search_btn_playDisabled.gif/, 'search_btn_play.gif'));
            });
        } catch (Error) { }
        //For other pages
        try {
            images = document.getElementsByTagName('*');
            for (var i = 0; i < images.length; i++) {
                if (images[i].id.indexOf('PlayButton_') != -1 || images[i].id.indexOf('SimilarSong_') != -1) {
                    images[i].style['opacity'] = '';
                    images[i].style['filter'] = '';
                    images[i].style['-ms-filter'] = '';
                    $addHandler(images[i], 'click', function() {
                        if ((typeof (PlayButton) !== 'undefined')) {
                            PlayButton.OnClickPlaySongButton(this);
                        }
                        else if ((typeof (ButtonControls) !== 'undefined')) {
                            ButtonControls.OnClickPlaySongButton(this);
                        }
                    });
                }
            }
        } catch (ex) { }
    },

    onLockPlayerControls: function() {
        MySpaceMusic.isPlayingAudioAd = true;
        MySpaceMusic.DisablePlayButtons();
    },

    onUnLockPlayerControls: function() {
        MySpaceMusic.EnablePlayButtons();
        MySpaceMusic.isPlayingAudioAd = false;
    },

    checkForPopUpBlocker: function(win) {
        if (win)
            win.focus();
        else
            MySpaceMusic.showPopupBlockerMessage();
    },

    MedRecRefresh: function(continuePlayback) {
        /* continuePlayback is handled only in UserViewProfile (profile players). */
        if (MySpace.ClientContext.FunctionalContext == "UserViewProfile")
            AdTooltip.open(continuePlayback);
        if (MySpace.ClientContext.FunctionalContext == "MusicDiscography")
            AdTooltip.open();
    },

    MedRecDismiss: function() {
        AdTooltip.close();
    },

    OptIn: function(userId, playlistId, songId, artistId, songName, albumId) {
        popupWidth = 530;
        popupHeight = 515;
        //		if (MySpace.ClientContext.FunctionalContext == "PopUpPlayer" && Sys.Browser.agent == Sys.Browser.InternetExplorer && Sys.Browser.version == 6) {
        //		     popupHeight = 505;
        //		}

        popupContent = "<iframe id='popupiframe' scrolling='no' style='border:0;overflow:hidden' src=" + "\"/modules/musicv2/pages/optindialog.aspx?userid=" + userId + "&songid=" + songId + "&playlistid=" + playlistId + "&artistid=" + artistId + "&albumid=" + albumId + "\" width='" + popupWidth + "' height='" + popupHeight + "'></iframe>";

        invCloseBtn = "<p class='popup_x' style='background:none; width:55px; height:25px; top:42px; margin:-28px 20px 0 0; padding:0 20px 0 0; cursor:pointer; float:right; position:relative;'></p>";
        popup = MySpaceMusic.createPopUp(popupContent, popupWidth, popupHeight, "", "optin");
        popup.show();

    },

    EnforceLogin: function() {
        try {
            if (window.XMLHttpRequest) {
                LoginObj.req = new XMLHttpRequest();
                LoginObj.req.onreadystatechange = LoginObj.LoginRedirect;
                LoginObj.req.open("GET", LoginObj.ajaxActionHandler, true);
                LoginObj.req.send(null);
                // IE/Windows ActiveX version
            } else if (window.ActiveXObject) {
                LoginObj.req = new ActiveXObject("Microsoft.XMLHTTP");
                if (LoginObj.req) {
                    LoginObj.req.onreadystatechange = LoginObj.LoginRedirect;
                    LoginObj.req.open("GET", LoginObj.ajaxActionHandler, true);
                    LoginObj.req.send();
                }
            }
        }
        catch (ex) { }
    },

    popupAllowed: function() {
        var popUpDetect = window.open('', '', 'width=1,height=1,left=0,top=0,scrollbars=no');

        if (popUpDetect) {
            var popupPopped = true;
            popUpDetect.close()
        } else {
            MySpaceMusic.showPopupBlockerMessage();
        }

        return popupPopped;
    },

    /**
    * Handle play stop event from Player
    */
    onStop: function(songID, artistUserIDs) {
        if (typeof (PlayButton) != "undefined") {
            Sys.UI.DomElement.removeCssClass(PlayButton._oldElem, PlayButton._oldElem.className);
            Sys.UI.DomElement.addCssClass(PlayButton._oldElem, PlayButton._oldClassName);
            PlayButton._oldElem.title = PlayButton._oldTitle;
            Sys.UI.DomElement.removeCssClass(PlayButton.oldParentElem, 'isPlaying');
        } else if (typeof (ButtonControls) != "undefined") {
            ButtonControls._oldElem.src = ButtonControls._oldSrc;
            ButtonControls._oldElem.title = ButtonControls._oldTitle;
            Sys.UI.DomElement.removeCssClass(ButtonControls.oldParentElem, 'isPlaying');
        }
    },

    onPausingCurrentTrack: function() {
        if (typeof SongList.SongItem.onPlayerPause == "function") {
            SongList.SongItem.onPlayerPause();
        }
    },
    onPlayingCurrentTrack: function() {
        if (typeof SongList.SongItem.onPlayerPlay == "function") {
            SongList.SongItem.onPlayerPlay();
        }
    },

    PlaySongInPOMP: function(songID, artistID, albumID, songName) {
        try {
            document.getElementById('shell').playSong(songID, artistID, albumID, songName);
        } catch (e) {
        }
    },

    onPlayerLoaded: function() {
        MySpaceMusic.playerLoaded = true;

        if ((typeof SongList.SongListView.onPlayerLoaded) != "undefined") {
            SongList.SongListView.onPlayerLoaded();
        }
    }
}

// Add our Focus/Blur via ASP DOM handlers
if (typeof ($addHandler) !== 'undefined') {
	if (Sys.Browser.agent === Sys.Browser.InternetExplorer) {
		$addHandler(document, "focusout", MySpaceMusic.Blur);
		$addHandler(document, "focusin", MySpaceMusic.Focus);
	} else if (Sys.Browser.agent === Sys.Browser.Safari) {
		$addHandler(window, "blur", MySpaceMusic.Blur);
		$addHandler(window, "focus", MySpaceMusic.Focus);
	} else { // Firefox
		$addHandler(window, "blur", MySpaceMusic.Blur);
		$addHandler(window, "focus", MySpaceMusic.Focus);
	}
}

var popup;

/**
 * XXX: This is being called from several pages. We need to sort it out.
 */
function ClosePopUp() {
	popup._hide();
	popupId = document.getElementById('divWrapper');
	document.body.removeChild(popupId);
}

/**
 * XXX: This is used from NoAmazonPopupMessaging.aspx. 
 * There's a huge amount of scriptLiterals on that page and they need be removed.
 */
killPopupBlockerMessaging = function() {
	popupFrame = document.getElementById('amazonNoPopUp');
	document.body.removeChild(popupFrame);
}



// <WebServiceGeneratedProxy Path="/Modules/MusicV2/Services/PopUpPlayer.asmx">
Type.registerNamespace('MySpace.Web.Modules.MusicV2.Services');
MySpace.Web.Modules.MusicV2.Services.PopUpPlayer = function() {
	MySpace.Web.Modules.MusicV2.Services.PopUpPlayer.initializeBase(this);
	this._timeout = 0;
	this._userContext = null;
	this._succeeded = null;
	this._failed = null;
}
MySpace.Web.Modules.MusicV2.Services.PopUpPlayer.prototype = {
	GetMultipleArtistsUpdate: function(ArtistIds, succeededCallback, failedCallback, userContext) {
		return this._invoke(MySpace.Web.Modules.MusicV2.Services.PopUpPlayer.get_path(), 'GetMultipleArtistsUpdate', false, { ArtistIds: ArtistIds }, succeededCallback, failedCallback, userContext);
	},
	GetArtistUpdate: function(ArtistId, succeededCallback, failedCallback, userContext) {
		return this._invoke(MySpace.Web.Modules.MusicV2.Services.PopUpPlayer.get_path(), 'GetArtistUpdate', false, { ArtistId: ArtistId }, succeededCallback, failedCallback, userContext);
	},
	GetMultipleArtistsUpdateFromArtistUpdatesApi: function(ArtistIds, succeededCallback, failedCallback, userContext) {
		return this._invoke(MySpace.Web.Modules.MusicV2.Services.PopUpPlayer.get_path(), 'GetMultipleArtistsUpdateFromArtistUpdatesApi', false, { ArtistIds: ArtistIds }, succeededCallback, failedCallback, userContext);
	}
}
MySpace.Web.Modules.MusicV2.Services.PopUpPlayer.registerClass('MySpace.Web.Modules.MusicV2.Services.PopUpPlayer', Sys.Net.WebServiceProxy);
MySpace.Web.Modules.MusicV2.Services.PopUpPlayer._staticInstance = new MySpace.Web.Modules.MusicV2.Services.PopUpPlayer();
MySpace.Web.Modules.MusicV2.Services.PopUpPlayer.set_path = function(value) { MySpace.Web.Modules.MusicV2.Services.PopUpPlayer._staticInstance._path = value; }
MySpace.Web.Modules.MusicV2.Services.PopUpPlayer.get_path = function() { return MySpace.Web.Modules.MusicV2.Services.PopUpPlayer._staticInstance._path; }
MySpace.Web.Modules.MusicV2.Services.PopUpPlayer.set_timeout = function(value) { MySpace.Web.Modules.MusicV2.Services.PopUpPlayer._staticInstance._timeout = value; }
MySpace.Web.Modules.MusicV2.Services.PopUpPlayer.get_timeout = function() { return MySpace.Web.Modules.MusicV2.Services.PopUpPlayer._staticInstance._timeout; }
MySpace.Web.Modules.MusicV2.Services.PopUpPlayer.set_defaultUserContext = function(value) { MySpace.Web.Modules.MusicV2.Services.PopUpPlayer._staticInstance._userContext = value; }
MySpace.Web.Modules.MusicV2.Services.PopUpPlayer.get_defaultUserContext = function() { return MySpace.Web.Modules.MusicV2.Services.PopUpPlayer._staticInstance._userContext; }
MySpace.Web.Modules.MusicV2.Services.PopUpPlayer.set_defaultSucceededCallback = function(value) { MySpace.Web.Modules.MusicV2.Services.PopUpPlayer._staticInstance._succeeded = value; }
MySpace.Web.Modules.MusicV2.Services.PopUpPlayer.get_defaultSucceededCallback = function() { return MySpace.Web.Modules.MusicV2.Services.PopUpPlayer._staticInstance._succeeded; }
MySpace.Web.Modules.MusicV2.Services.PopUpPlayer.set_defaultFailedCallback = function(value) { MySpace.Web.Modules.MusicV2.Services.PopUpPlayer._staticInstance._failed = value; }
MySpace.Web.Modules.MusicV2.Services.PopUpPlayer.get_defaultFailedCallback = function() { return MySpace.Web.Modules.MusicV2.Services.PopUpPlayer._staticInstance._failed; }
MySpace.Web.Modules.MusicV2.Services.PopUpPlayer.set_path("/Modules/MusicV2/Services/PopUpPlayer.asmx");
MySpace.Web.Modules.MusicV2.Services.PopUpPlayer.GetMultipleArtistsUpdate = function(ArtistIds, onSuccess, onFailed, userContext) { MySpace.Web.Modules.MusicV2.Services.PopUpPlayer._staticInstance.GetMultipleArtistsUpdate(ArtistIds, onSuccess, onFailed, userContext); }
MySpace.Web.Modules.MusicV2.Services.PopUpPlayer.GetArtistUpdate = function(ArtistId, onSuccess, onFailed, userContext) { MySpace.Web.Modules.MusicV2.Services.PopUpPlayer._staticInstance.GetArtistUpdate(ArtistId, onSuccess, onFailed, userContext); }
MySpace.Web.Modules.MusicV2.Services.PopUpPlayer.GetMultipleArtistsUpdateFromArtistUpdatesApi = function(ArtistIds, onSuccess, onFailed, userContext) { MySpace.Web.Modules.MusicV2.Services.PopUpPlayer._staticInstance.GetMultipleArtistsUpdateFromArtistUpdatesApi(ArtistIds, onSuccess, onFailed, userContext); }
// </WebServiceGeneratedProxy>

/**
 * MySpaceMusic.WebSvrManager Object definition
 */
MySpaceMusic.WebSvrManager = {
	ArtistUpdateSuccess: function(result, eventArgs) {
		if (result != null) {
		    var feedResult = document.getElementById('feedResult');
		    if (feedResult != null)
			    feedResult.innerHTML = result;
		}
	},
	OnFailure: function(msg) {
		// alert("Error MySpaceMusic.WebSvrManager: " + msg._message);
	}
}

