﻿var FF2 = (navigator.oscpu && navigator.userAgent.match("rv:1\.8\.1")) ? true : false;
var FF3 = (navigator.oscpu && navigator.userAgent.match("rv:1\.9")) ? true : false;
var FF35 = (navigator.oscpu && navigator.userAgent.match("Firefox/3.5")) ? true : false;
var IE6 = (navigator.userAgent.match("MSIE 6")) ? true : false;
var IE7 = (navigator.userAgent.match("MSIE 7")) ? true : false;
var IE8 = (navigator.userAgent.match("MSIE 8")) ? true : false;
var SAF = (navigator.userAgent.match("Safari")) ? true : false;
var MAC = (navigator.userAgent.match("Macintosh")) ? true : false;

var USER_GENDER_MALE = 1;
var USER_GENDER_FEMALE = 2;
var DEFAULT_PHOTO_MALE = "/skins/images/noPhoto_001.gif";
var DEFAULT_PHOTO_FEMALE = "/skins/images/noPhoto_002.gif";
var webServerAddress = "http://"+document.domain;

var userPhotosDirsArray = new Array();
var videoThumbnailsDirsArray = new Array();
var songPlaylist = {};//new Array();
var moodImages = new Array();

function userPhotosSearch(imgObj,userGender){
	
	if(imgObj == null) return;
	if(imgObj.src == null) return;

	if(top.location.href.indexOf("myspace") != -1) {
		var filenameWithFolder = imgObj.src;
		if(filenameWithFolder.indexOf("large") != -1) {
			imgObj.onerror = function(){}
			if(userGender == USER_GENDER_MALE){
				imgObj.src = DEFAULT_PHOTO_MALE;
			}else{
				imgObj.src = DEFAULT_PHOTO_FEMALE;
			}
		} else if(filenameWithFolder.indexOf("profile") != -1) {
			imgObj.src = imgObj.src.replace("profile","medium");
		} else if(filenameWithFolder.indexOf("medium") != -1) {
			imgObj.src = imgObj.src.replace("medium","large");
		}
	} else {
		var i = 0;

		var filenameWithFolder = imgObj.src;
		var folder = "";
		var filename = "";

		var dirIndex = 0;
		for(dirIndex = 0; dirIndex<userPhotosDirsArray.length ; dirIndex ++){
			if(filenameWithFolder.indexOf(userPhotosDirsArray[dirIndex]) != -1){
				break;
			}
		}

		if(dirIndex<userPhotosDirsArray.length-2){
			imgObj.src = imgObj.src.replace(userPhotosDirsArray[dirIndex],userPhotosDirsArray[dirIndex+1]);
		}else{
			imgObj.onerror = function(){}
			if(userGender == USER_GENDER_MALE){
				imgObj.src = DEFAULT_PHOTO_MALE;
			}else{
				imgObj.src = DEFAULT_PHOTO_FEMALE;
			}
		}
	}
}

function userPhotosSearchHomepage(imgObj,userGender){
	
	if(imgObj == null) return;
	if(imgObj.src == null) return;

	if(top.location.href.indexOf("myspace") != -1) 
	{
		var filenameWithFolder = imgObj.src;
		if(filenameWithFolder.indexOf("medium") != -1) 
		{
			imgObj.onerror = function(){}
			if(userGender == USER_GENDER_MALE){
				imgObj.src = DEFAULT_PHOTO_MALE;
			}else{
				imgObj.src = DEFAULT_PHOTO_FEMALE;
			}
		} 
	}
	
}


function videoThumbnailsSearch(imgObj,userGender){
	
	if(imgObj == null) return;
	if(imgObj.src == null) return;
	
	var filenameWithFolder = imgObj.src;
	if(filenameWithFolder.indexOf("thumb0") != -1) {
		imgObj.onerror = function(){}
		if(userGender == USER_GENDER_MALE){
			imgObj.src = DEFAULT_PHOTO_MALE;
		}else{
			imgObj.src = DEFAULT_PHOTO_FEMALE;
		}
	} else {
		if(filenameWithFolder.indexOf("thumb1") != -1) {
			imgObj.src = imgObj.src.replace("thumb1","thumb0");
		}
	}
	
}

function checkUserImageExist(imgObj,userGender){
	if(imgObj == null) return;
	if(imgObj.src == null) return;

	if (navigator.userAgent.toLowerCase().indexOf("firefox/3") != -1) {
		var filenameWithFolder = imgObj.src;
		if(filenameWithFolder.indexOf("large") != -1 && imgObj.naturalWidth == 0) {
			imgObj.onerror = function(){}
			if(userGender == USER_GENDER_MALE){
				imgObj.src = DEFAULT_PHOTO_MALE;
			}else{
				imgObj.src = DEFAULT_PHOTO_FEMALE;
			}
		} else if(filenameWithFolder.indexOf("profile") != -1 && imgObj.naturalWidth == 0) {
			imgObj.src = imgObj.src.replace("profile","medium");
		} else if(filenameWithFolder.indexOf("medium") != -1 && imgObj.naturalWidth == 0) {
			imgObj.src = imgObj.src.replace("medium","large");
		}
	}
}

function checkUserImageExistHomepage(imgObj,userGender){
	if(imgObj == null) return;
	if(imgObj.src == null) return;

	if (navigator.userAgent.toLowerCase().indexOf("firefox/3") != -1) {
		var filenameWithFolder = imgObj.src;
		if(filenameWithFolder.indexOf("medium") != -1 && imgObj.naturalWidth == 0) {
			imgObj.onerror = function(){}
			if(userGender == USER_GENDER_MALE){
				imgObj.src = DEFAULT_PHOTO_MALE;
			}else{
				imgObj.src = DEFAULT_PHOTO_FEMALE;
			}
		} 
	}
}

function checkVideoImageExist(imgObj,userGender){
	if(imgObj == null) return;
	if(imgObj.src == null) return;

	if (navigator.userAgent.toLowerCase().indexOf("firefox/3") != -1) {
		if(imgObj.naturalWidth == 0) {
			imgObj.onerror = function(){}
			if(userGender == USER_GENDER_MALE){
				imgObj.src = DEFAULT_PHOTO_MALE;
			}else{
				imgObj.src = DEFAULT_PHOTO_FEMALE;
			}
		}
	}
}

function runSearch(searchType,cRow,abc,param1,param2,param3,param4,param5,param6,param7,param8,param9)
{
	var str = "/actions/searchAction.do?sType=" + searchType;
	str += "&cRow=" + cRow;
	str += "&abc=" + abc;

	for(i = 1; i <= 9 ;i++){
		if (eval("param"+i) != undefined ){
			str += "&" + ("param"+i) + "=" + eval("param"+i);
		}
	}
	top.location = str;
}

function myWebpage()
{
	sendNewHref("/actions/myWebpage.do");
}

function searchSong()
{
	if(document.searchForSongForm.searchBy.value == 0)
	{
		top.location = "/actions/searchSongByArtistName.do?artistName=" + document.searchForSongForm.textField.value;
	}
	else if(document.searchForSongForm.searchBy.value == 1)
	{
		top.location = "/actions/searchSongBySongName.do?songName=" + document.searchForSongForm.textField.value;
	}
}

function searchArtistByName()
{
	top.location = "/actions/searchArtistByName.do?artistName=" + document.searchForArtistForm.textField.value;				
}


function addSongToLibrary(songID)
{
	try 
	{				
		ajaxController.init("/actions/addSongToLibrary.do?songId=" + songID, true,
			function (resp) 
			{		         
				if (resp.indexOf(resources.getMessage("afteroperation.addtolibrary.ok")) != -1)
				{
					popupDiv_statusMsg.init(resources.getMessage("afteroperation.addtolibrary.ok"), 14, false);
				}
				else if (resp == "")  //not loggin yet
				{  
					joinSite();
				}
			}
		);		    
	} catch(e) {}
}

// re-send activation email
function resendActivation()
{
	if(top.afterOperation)
	{
		setFocusOnAfterOperation();
		top.afterOperation.location = "/sendActivationEmailAgain.do";
	}
}


function addPerformerToFavorites(perfId,_pname,_applauseperm,_safetystate)
{
	if (_safetystate == 0) 
	{
		popupDivController.createPopupDiv_addPerformerToFavorites("/popupAddToFavorite.do?uid=" + perfId + "&nm=" + _pname + "&app=" + _applauseperm);
	} 
	else 
	{
		popupDivController.createPopupDiv_addPerformerToFavorites("/popupAddToFavorite.do?uid=" + perfId + "&nm=" + _pname + "&app=" + _applauseperm);
	}
	
}

function showUserProfile(uid)
{
	sendNewHref("/actions/showUserProfile.do?uid=" + uid);
}

function searchArtist()
{
	if(document.searchForArtistForm.searchBy.value == 0)
	{
		runSearch(3,0,'',document.searchForArtistForm.textField.value);
	}
	else if(document.searchForArtistForm.searchBy.value == 1)
	{
		runSearch(2,0,'',document.searchForArtistForm.textField.value);
	}
}

function joinSite()
{
	sendNewHref("/join.do?passedFrom=" + cleanURLForPassFrom(top.location.href));
}

// ********************************************************************
// This Method Sucks. Don't Use it. It will break the Recording Page!!!
// ********************************************************************
function joinForRate(_params)
{
	var x = setcookie("jfr",_params,360);
	var obj = new cookieObj();
	obj.createCookie("playerOnDemandFunction", 'if (parseInt(getcookie("songId")) != 0) {playSong(getcookie("songId"), 0)}', 365);                 
	sendNewHref("/join.do?passedFrom=" + cleanURLForPassFrom(top.location.href));
}
// ********************************************************************

function joinForRecord()
{
	var obj = new cookieObj();
	obj.createCookie("playerOnDemandFunction", escape('playSong(getcookie("songId"), 1)'), 365);                 
	sendNewHref("/join.do?passedFrom=" + cleanURLForPassFrom(top.location.href));
}
function joinForRecordFromSong(strSongId) {
	var obj = new cookieObj();
	obj.createCookie("playerOnDemandFunction", escape('playSong("0", 1)'), 365);                                 
	sendNewHref("/join.do?passedFrom=/actions/searchSongBySongId.do?songId="+strSongId);				
}

function joinForSongChain(strSongId) {
	var obj = new cookieObj();
	obj.createCookie("playerOnDemandFunction",escape("SongChainCookie"), 365);                                 
	sendNewHref("/join.do?passedFrom=/actions/searchSongBySongId.do?songId="+strSongId);				
}


// *********************************
// Function called from Homepage v2
//  - Checks for login
//  - Passes SongId to "SearchSongBySongId" page
function recordThisSong(songId) {
	// Create cookie object (from Prototype.js)
	var cookie = new cookieObj();
	// Set cookie value
	cookie.createCookie('reloadPlayerAfterInstall', 1, 365);
	// Pass SongId to page
	//joinForRecord_homepage(songId);
	sendNewHref("/join.do?passedFrom=/actions/searchSongBySongId.do?songId=" + songId);			
}
// *********************************
function joinForRecord_homepage(strSongId) {
	var obj = new cookieObj();
	obj.createCookie("playerOnDemandFunction", escape('playSong("0", 1)'), 365);                                 
	sendNewHref("/join.do?passedFrom=/actions/searchSongBySongId.do?songId="+strSongId);				
}

function loginSite(){
	sendNewHref("/login.do?passedFrom=" + cleanURLForPassFrom(top.location.href));
}


// Helper Function? Not of any use to me. Should this be deprecated?
//  - jkiesel (10/24/2008)
function cleanURLForPassFrom(_url)
{
	var w = top.location.href;
	w = w.substr(w.toLowerCase().indexOf(".com")+4,w.length);
	if(w.toLowerCase().indexOf("#")!=-1)
	{
		w = w.substr(0,w.toLowerCase().indexOf("#"));
	}
	return escape(w);
}

function store(){
	sendNewHref("/store.do");
}
function myAccount(){
	sendNewHref("/myAccount.do");
}
function myLibrary(){
	sendNewHref("/userLibrary.do");
}
function myRecordings(_sid){
	if(_sid){
		sendNewHref("/userRecordings.do?lastTriedRecording=" + _sid);
	}else{
		sendNewHref("/userRecordings.do");
	}
}
function myFavorites(){
	sendNewHref("/fanCentral.do?fav=1"); //userFavorites
}
function myFans(strTabId){
	if (typeof strTabId != "undefined") {
		sendNewHref("/fanCentral.do?id="+strTabId);
	}
	else {
		sendNewHref("/fanCentral.do"); //userFavorites
	}
}			
function updateProfile(){
	sendNewHref("/updateProfile.do");
}
function changePassword(){
	sendNewHref("/changePassword.do");
}
function homePage(){
	sendNewHref("/home.do");
}
function homepageRefresh(){
	sendNewHref("/home_refresh.do");
}

function downloadIE(){
	window.open('http://www.microsoft.com/windows/products/winfamily/ie/default.mspx','window','');
}
			function downloadFF(){
	window.open('http://www.mozilla.com/en-US/firefox/','window','');
}

function feedbackCentral(strTabId){
	if (typeof strTabId != "undefined") {
		sendNewHref("/feedbacksCentral.do?id="+strTabId);
	}
	else {
		sendNewHref("/feedbacksCentral.do");
	}				
}
function purchasePage(sid,songName){
	var str =  "/purchase.do?1=1";



	if(webServerAddress){
		try{
			if(webServerAddress.indexOf("myspace")==-1){
				str = webServerAddress.replace("http://","https://") + "/purchase.do?1=1";
			}
		}catch(e){}
	}

	if(sid) str += "&sid=" + sid;
	if(songName) str += "&songName=" + songName;
	sendNewHref(str);
}

function myAcctManagement() {
	sendNewHref("/editPaymentInfo.do");
}

function logout(){
	sendNewHref("/actions/logOff.do");
}             

function showSongProfile(_sid,_uid,_rid,_isComp){
	sendNewHref("/actions/showSongProfile.do?rid=" + _rid + "&sid=" + _sid + "&uid=" + _uid + ((_isComp) ? ("&compId=" + _isComp) : ("")));
}

function editSongProfile(_sid,_uid,_rid){
	sendNewHref("/actions/showSongProfile.do?edit=1&rid=" + _rid + "&sid=" + _sid + "&uid=" + _uid);
}

function fanClub(_uid,_ufname){
	sendNewHref("/showUserFanFavoriteList.do?uid="+_uid+"&uName="+_ufname);
}

function newsletterPref() {
	sendNewHref("/updateNewsPref.do");
}






var SONG_STATE_DEFAULT = 1;
var SONG_STATE_PLAYING = 2;
var SONG_STATE_PLAYED = 3;

var loadSongParams = {p:"",b:"",c:""};
var currentSong = "";

/*Ronit Added Feb 20*/
function setSongState(val,classVal){
	var row = document.getElementById("searchRow"+val);

	if(!row){
		return;
	}
	return;
	try{
		switch (classVal){
			case SONG_STATE_DEFAULT:  //default
				row.className = "searchRowPlayed";
			//	alert("SONG_STATE_DEFAULT - " + row.id);
			break;
			case SONG_STATE_PLAYING: //playing
				row.className = "searchRowPlayed";
			//	alert("SONG_STATE_PLAYING - " + row.id);
			break;
			case SONG_STATE_PLAYED: //played
				row.className = "searchRowPlayed";
			//	alert("SONG_STATE_PLAYED - " + row.id);
			break;
		}
	}catch(e){
		alert("Exception " + e);
	}
}

function playVideo(dur, file, uid, sid, rid, recLink)
{
	var backgroundImage="";
	var fileDuration=dur;
	var fileName=file;
	var scriptable="true";
	var userid = uid;
	var songid = sid;
	var recordid = rid;
	var recordingLink = "/actions/showSongProfile.do?";
	
	var songInfo = backgroundImage + "~" +
				   fileDuration + "~" +
				   fileName + "~" +
				   scriptable + "~" +
				   userid + "~" +
				   songid + "~" +
				   recordid + "~" +
				   recordingLink;
		
	document.getElementById("KMiniPlayer").SetVariable("info", songInfo);
}

function issueFSCmd() 
{
	playerController.sendMessageToKaraokePlayer(playerControllerCmd.MESSAGE_INITIATE_PLAYER ,1);                
}

function playSong(_params,_btn){	 			    
	var obj = new cookieObj();
	obj.createCookie("playerLastAction", _btn, 365);    
	if (parseInt(_params) != 0) {			        			        
		obj.createCookie("reloadPlayerAfterInstallSongId", parseInt(_params), 365);                 
		obj.createCookie("songId", parseInt(_params), 365);                 
	}
	else {
		obj.createCookie("reloadPlayerAfterInstallSongId", 0, 365);  
		obj.createCookie("songId", 0, 365);  
	}    
	
	playerController.songId = _params;
	playerController.btn = _btn;
	openPlayer(_params);     
									
	if (playerController.playerReadyTimer == null) {
		new PeriodicalExecuter(function(pe) {
			playerController.playerReadyTimer = pe;
			issueFSCmd();
		}, 0.1);                
	}
	else {
		loadSong(songPlaylist[playerController.songId],playerController.btn);
	}
	
	//if(!_crd){
	//	_crd = "";
	//}

	//if(currentSong != ""){ setSongState(currentSong,SONG_STATE_PLAYED); }

	/*var err;
	err = false;
	if(window.openPlayer && window.loadSong){  //window.status += "3";				    
		if(document.getElementById("MediaPlayer1")){					    
			if(document.getElementById("MediaPlayer1")){
				document.getElementById("MediaPlayer1").style.display = "block";
				document.MediaPlayer1.Play();
			}
			loadSongParams.p = songPlaylist[_params];
			loadSongParams.b = _btn;
			loadSongParams.c = _crd;
		}else{					
			loadSong(songPlaylist[_params],_btn,_crd);
			currentSong = _params;
			//setSongState(currentSong,SONG_STATE_PLAYING);
		}
		
		//playerController.setPlayerColor(playerController.getPlayerLastRequestedColor());                                                                            
		openPlayer(_params);																				


	}else{
		err = true;
	}
	if(err){
		temp = setTimeout("playSong('" + _params + "','" + _btn + "','" + _crd + "')",1000);
	}	
	*/			
	//for player debugging info		
	try {
		if ($("AVControl") != null) {
			AVXInfo._version = $("AVControl").sVersion.strip();
			AVXInfo._build = $("AVControl").sBuildDateTime.strip();                        
			
			$("playerDebugInfo").innerHTML = "Version: " + $("AVControl").sVersion;
			$("playerDebugInfo").innerHTML += " Build: " + $("AVControl").sBuildDateTime;                
		}
		else if ($("AVControlFF") != null) {
			AVXInfo._version = $("AVControlFF").sVersion.strip();
			AVXInfo._build = $("AVControlFF").sBuildDateTime.strip();
			if ($("playerDebugInfo") != null) {
				$("playerDebugInfo").innerHTML = "Version: " + $("AVControlFF").sVersion;                        
				$("playerDebugInfo").innerHTML += " Build: " + $("AVControlFF").sBuildDateTime;                
			}
		}
		//check to see if there's new version of the plugin
		AVXInfo.check4Update();
	} catch(e) {}                
}



/** ****************************************************************************************************************************
 * PLAYER STYLE FUNCTION 
 **************************************************************************************************************************** */
var _PLAYER_POS = 0;
var _FOOTER_POS = 0;    //store the height of bodyWrapper;
var _ALREADY_READJUST_POS = false;

function openPlayer(strSongId){	    	    
	if(document.getElementById("flashPlayerContainer")){
		if (_FOOTER_POS == 0) {
			//_FOOTER_POS = top.document.documentElement.scrollHeight;    
			if (BrowserDetect.browser == "Safari") {
				_FOOTER_POS = top.document.body.scrollHeight + "px";            
			}
			else
				_FOOTER_POS = top.document.documentElement.scrollHeight + "px";   
		}
		document.getElementById("flashPlayerContainer").className = "openPlayer";			
		
		//for bulletin feature
		if (bulletinController != null) {
			bulletinController.init(strSongId);			
			showBulletinThisForTestUsers();
		}

		try{	
			if (!_ALREADY_READJUST_POS) {
				_ALREADY_READJUST_POS = true;
				if ($("globalDetails") != null)     //this is for user profile page only
				{ 
					$("searchResults").style.paddingTop = "630px";
				}
				else if ($("lyricDiv") != null)     //this is the song profile page
				{
					if($("playerPlaceHolder"))
					{
						$("playerPlaceHolder").style.display = "none";
					}           
				}
			}
					
			if (_PLAYER_POS == 0) {				    				    
				_PLAYER_POS = $("flashPlayerContainer").offsetTop + $("flashPlayerContainer").offsetParent.offsetTop;
			}
			var tmpHeight = Math.abs(_PLAYER_POS - Math.ceil((document.documentElement.clientHeight-$("flashPlayerContainer").offsetHeight)/2));				
			top.scrollTo(0,tmpHeight);                
		}
		catch(e) {alert(e);}		
	}					
}



function closePlayer(){	   	    	    
	if(document.getElementById("flashPlayerContainer")){
		document.getElementById("flashPlayerContainer").className = "closePlayer";
		//for bulletin feature
		if (bulletinController != null)
			bulletinController.removeContent();
		//if(window.fixPositions) window.fixPositions('window');
		if ($("globalDetails") != null) {   //this is for user profile page only	        
			//window.fixPositions('window');
			$("searchResults").style.paddingTop = "158px"; 	            
			//if (BrowserDetect.browser == "Safari")
			//    $("bottomMenuCopyrights").style.top = top.document.body.scrollHeight + 5 + "px";            
			//else
			//    $("bottomMenuCopyrights").style.top = top.document.documentElement.scrollHeight + 5 + "px";   
			//$("bottomMenuCopyrights").style.visibility = "visible";            
		}
		else { 	            
			//$("bottomMenuCopyrights").style.top = _FOOTER_POS - 76 + "px";
			//$("bottomMenuCopyrights").style.visibility = "visible";
		}
		_ALREADY_READJUST_POS = false;
	}			
}



function continueLoadPlay(){
	document.getElementById("MediaPlayer1").style.display = "none";
	loadSong(loadSongParams.p,loadSongParams.b,loadSongParams.c);
}


function getexpirydate(nodays){
	var UTCstring;
	Today = new Date();
	nomilli=Date.parse(Today);
	Today.setTime(nomilli+nodays*24*60*60*1000);
	UTCstring = Today.toUTCString();
	return UTCstring;
}
function getcookie(cookiename) {

	 var cookiestring = "" + document.cookie;

	 var index1=cookiestring.indexOf(cookiename);
	 if (index1==-1 || cookiename=="") return "";

	 var index2=cookiestring.indexOf(";",index1);
	 if (index2==-1) index2=cookiestring.length;

	 if(index1 == index2 || cookiestring.indexOf("=",index1) >= index2) return "";

	 return unescape(cookiestring.substring(index1+cookiename.length+1,index2));
}

function setcookie(name,value,duration){
	cookiestring=name + "="+ escape(value) + ((duration && duration!=0) ? ";EXPIRES="+getexpirydate(duration) : "") + "; path=/";
	document.cookie=cookiestring;
	if(!getcookie(name)){
		return false;
	}else{
		return true;
	}
}

function setMeOnTop(){
	if(top.location != this.location){
		top.location = this.location;
	}
}

function popup_rememberMe(){
	openFAQPopup("/popupRememberMe.do");
}


function popup_VATList(){
	openFAQPopup("/popupVATList.do");
}

function popup_tellAFriend(){
	popupDivController.createPopupDiv_tellAFriend();                
}
function popup_tellAFriendCompetition(){
	openFAQPopup("/popupTellAFriend.do?compId=1",500,520);
}

function openSendToEmail(_sid,_rid,_compId,_isMySong,_uname,_uid,_justSaveRec,_perm,_mediaType){
	if(getAVControl()){
		//document.getElementById('AVControlFF');
		getAVControl().style.height="1px";
		getAVControl().style.width="1px";
	}
	if (_rid == 0) {
		try {
			var url = "/actions/retrieveLastRecordId.do?uid="+_uid+"&sid="+_sid+"&mediaType="+_mediaType;
			new Ajax.Request(url, {
				onSuccess: function(resp) {
					_rid = resp.responseText;
					if (_rid == 0) {
						popupDivController.createPopupDiv_shareWithFriendsProcessing();
					} else {
						popupDivController.createPopupDiv_shareWithFriends("/popupSendToFriends.do?rid="+_rid+"&sid="+_sid+"&compId="+_compId + "&uname=" + _uname + ((_isMySong == "true") ? "&ismysong=true" : "") + "&uid=" + _uid + "&justSaveRec=" + _justSaveRec + "&perm=" + _perm);
					}
				}
			});
		} catch(e) {alert(e)}
	} else {
		popupDivController.createPopupDiv_shareWithFriends("/popupSendToFriends.do?rid="+_rid+"&sid="+_sid+"&compId="+_compId + "&uname=" + _uname + ((_isMySong == "true") ? "&ismysong=true" : "") + "&uid=" + _uid + "&justSaveRec=" + _justSaveRec + "&perm=" + _perm);
	}
}

function popup_FAQTopic(_cid,_qid){
	openFAQPopup("/popupFAQTopic.do?catId="+_cid+"#"+_qid,500,462);
}

function popup_FAQQuestion(_cid,_qid){
	openFAQPopup("/popupFAQQuestion.do?catId="+_cid+"&qid="+_qid,500,520);
}

function popup_forgotPassword(){
	openFAQPopup("/popupForgotPassword.do");
}

function openFAQPopup(_lnk,_height,_width){
	window.open(_lnk,'faqPopup','scrollbars=yes,toolbar=no,menubar=no,status=no,location=no,top=0,left=0,resizable=yes,width=' + ((_width!="" && _width)?_width:'510') + ',height=' + ((_height!="" && _height)?_height:'230'));
}

function openGreetingCard(val){
	window.open("/popupPreviewGreetingCard.do?card=" + val,'greetingPopup','scrollbars=no,toolbar=no,menubar=no,status=no,location=no,top=0,left=0,resizable=no,width=360,height=200');
}
function getSponsorLogoPath(){
	//TO DO - ADD YOUR CODE TO GET THE PATH HERE
	playerController.sendMessageToKaraokePlayer(playerControllerCmd.MESSAGE_PARAMETER_RETURNED_SPONSOR_LOGO_PATH ,"http://www.google.com");
}

function howItWorks(){alert("no page yet");}
function purchaseOptions(){alert("no page yet");}
function helpCenter(){alert("no page yet");}
function pshowcaseTopSongs(){alert("no page yet");}

function pshowcaseLatestSubmissions(){
	sendNewHref("/actions/searchPerformersLastSubmission.do");
}
function competingLatestSubmissions(_compId){
	sendNewHref("/actions/randomCompetingSongs.do?compId=" + _compId);
}

function pshowcaseTopPerformers(){
	sendNewHref("/actions/searchTopPerformers.do");
}
function pshowcasePerformersSearch(){
	sendNewHref("/searchPerformers.do");
}
function currentContest(){
	sendNewHref("/competition.do?compId=10");
}



var JUMPTO_USER_RECORDINGS = 1;
var JUMPTO_SIMILAR_SONGS = 2;

function searchSongBySongId(_id,_where){
	if(_where){

		if(_where == JUMPTO_USER_RECORDINGS){
			location = "/actions/searchSongBySongId.do?jump=1&x=" + Math.random() + "&songId=" + _id + "#afterOperation";
		}else if(_where == JUMPTO_SIMILAR_SONGS){
			location = "/actions/searchSongBySongId.do?jump=1&x=" + Math.random() + "&songId=" + _id + "#searchResults2";
		}

	}else{
		var obj = new cookieObj();  
    	obj.deleteCookie("reloadPlayerAfterInstall");
		location = "/actions/searchSongBySongId.do?songId=" + _id;					
	}

}
function searchSongByArtistId(_id){
	sendNewHref("/actions/searchSongByArtistId.do?artistId=" + _id);
}

function searchSongByGenres(strGenreId){			    
	sendNewHref("/actions/searchSongByGenre.do?genre=" + strGenreId);
}

function showFavLatestRecs(){
	sendNewHref("/actions/searchFavPerfsLastSubmissionsAllSongs.do");
}

function aboutUs(){
	sendNewHref("/aboutUs.do");
}

function photoGallery(_uid,_uname){
	sendNewHref("/listPhotos.do?1=1" + (_uid ? "&uid="+_uid : "") + (_uname ? "&uname="+_uname : ""));
}

function termsOfUse(){
	popupDivController.createPopupDiv_termsOfUse();		
}
function subscriptionAgreement(){
	popupDivController.createPopupDiv_subscriptionAgreement();
}
function privacyPolicy(){
	popupDivController.createPopupDiv_privacyPolicy();
}
function termsOfPurchase(){
	popupDivController.createPopupDiv_termsOfPurchase();
}

function faq(){
	sendNewHref("/faqBrowser.do");
}

function contactUs(){
	sendNewHref("/contactUs.do");
}

function popup_showUserPic(picName,userName,photoCaption){
	openFAQPopup("/popupUserPhotoPreview.do?pic="+picName+((userName)?"&user="+userName:"")+((photoCaption)?"&photoCaption="+photoCaption:""),400,520);
}

function popup_myRecordingsLink(){
	openFAQPopup("/popupMyRecordingsLink.do",500,550);
}

function popup_topPerformers(){
	openFAQPopup("/popupTopPerformers.do?catId=6",400,520);
}

function popup_leaveUserFeedback(_uid,_ols,_recName){
	popupDivController.createPopupDiv_leaveUserFeedback("/actions/popupDisplayUserFriendVerification.do?uid=" + _uid + "&ols=" + _ols + "&recName=" + _recName);
}

function popup_leaveRecordingFeedback(_uid,_ols,_recName,_recId,_sid){
	popupDivController.createPopupDiv_leaveUserFeedback("/actions/popupDisplayUserFriendVerification.do?uid=" + _uid + "&ols=" + _ols + "&recName=" + _recName + "&recId=" + _recId + "&sid=" + _sid);
}

function popup_leaveUserPrivateFeedback(_uid,_ufname){
	openFAQPopup("/popupLeavePrivateFeedbackToUser.do?uid="+_uid+"&recName="+_ufname,330,520);
}

function highlight(obj){
	obj.focus();
	obj.select();
}

var isPopup = false;
function sendNewHref(_href){
	if(_href.indexOf("purchase")==-1){
		_href = _href.replace("http://","https://");
	}
	if(isPopup){
		window.opener.location.href = _href;
		window.close();			
	}else{
		window.location.href = _href;
	}
}

function myspaceLogin() {
	top.location.href = "/myspace/loginUser.do?passedFrom="+cleanURLForPassFrom(top.location.href);
}


var isInLoading = false;


/** feed opener **/

	var FEEDLOADER_REPLACE_CONTENT = 1;
	var FEEDLOADER_ADD_BOTTOM = 2;
	var FEEDLOADER_ADD_TOP = 3;
	var FEEDLOADER_DO_NOTHING = 4;

	var FEEDLOADER_METHOD_POST = 1;
	var FEEDLOADER_METHOD_GET = 2;

	function onFeedLoaded(_feed, _who,_what,_type,_method){
	    try
		{
			if(!document.getElementById(_who))
			{
				isInLoading = false;
				return;
			}
			else
			{
				switch(_type)
				{
					case FEEDLOADER_REPLACE_CONTENT:
						document.getElementById(_who).innerHTML = _feed;
						break;
					case FEEDLOADER_ADD_BOTTOM:
						document.getElementById(_who).innerHTML += _feed;
						break;
					case FEEDLOADER_ADD_TOP:
						document.getElementById(_who).innerHTML = _feed + document.getElementById(_who).innerHTML;
						break;
					case FEEDLOADER_DO_NOTHING:
						break;
					default:
						document.getElementById(_who).innerHTML = _feed;
						break;
				}
			}
	    } 
		catch(e) 
		{
			isInLoading = false;
		}
		
	    try {
	        $$("p.postMessage").each(function(elem) {
	           Effect.Fade(elem, {delay:1, duration:0.2}); 
	        });			        
	    } 
		catch(e) 
		{
			isInLoading = false;
		}
	    //window.onFeedLoaded = function(){};
	    onFeedInitiatedAndReady();
	    isInLoading = false;
	}
	function onFeedInitiatedAndReady(){}

	var historySize = 0;

	function openFeed(_who,_what,_type,_method){
        try 
		{
		    if(!window.feed) 
			{ 
				isInLoading = false; 
				return;
			}
		    if(!window.feed.location) 
			{ 
				isInLoading = false; 
				return;
			}
		    if(!window.feed.location.replace) 
			{ 
				isInLoading = false; 
				return;
			}
                                    
		    window.onFeedLoadedOld = function(_feed)
			{
			    try
				{
					if(!document.getElementById(_who))
					{
						isInLoading = false;
						return;
					}
					else
					{
						switch(_type)
						{
							case FEEDLOADER_REPLACE_CONTENT:
								document.getElementById(_who).innerHTML = _feed;
								break;
							case FEEDLOADER_ADD_BOTTOM:
								document.getElementById(_who).innerHTML += _feed;
								break;
							case FEEDLOADER_ADD_TOP:
								document.getElementById(_who).innerHTML = _feed + document.getElementById(_who).innerHTML;
								break;
							case FEEDLOADER_DO_NOTHING:
								break;
							default:
								document.getElementById(_who).innerHTML = _feed;
								break;
						}
					}
			    } 
				catch(e) 
				{
					isInLoading = false;
				}
				
			    try {
			        $$("p.postMessage").each(function(elem) {
			           Effect.Fade(elem, {delay:1, duration:0.2}); 
			        });			        
			    } 
				catch(e) 
				{
					isInLoading = false;
				}
			    //window.onFeedLoaded = function(){};
			    onFeedInitiatedAndReady();
			    isInLoading = false;
		    }

		    if(_method != FEEDLOADER_METHOD_POST)
			{
			    window.feed.location.replace(_what);
		    }
			else
			{
			    // create form
			    if(!document.getElementById("feedForm")){
				    var oDiv=document.createElement("FORM");
				    oDiv.name = "feedForm";
				    oDiv.method = "POST";
				    oDiv.id = "feedForm";
				    document.body.appendChild(oDiv);
			    }
			    var frm = document.getElementById("feedForm");

			    // clear old fields
			    while(0 < frm.children.length) frm.removeChild(frm.children(0));

			    if(_what.parameters){
				    for(var i = 0 ; i < _what.parameters.length; i++){
					    var oDiv=document.createElement("INPUT");
					    oDiv.type = "hidden";
					    oDiv.name = _what.parameters[i][0];
					    oDiv.value = _what.parameters[i][1];
					    frm.appendChild(oDiv);
				    }

			    }

			    frm.action = _what.address;
			    frm.target = "feed";
			    frm.submit();
		    }
		    isInLoading = true;
		} 
		catch(e) 
		{
			alert(e);
			isInLoading = false;
		}
	}

	function closeFeed(_who){
		if(!document.getElementById(_who)) return;
		document.getElementById(_who).innerHTML = "";
		//fixPositions('');
	}

function globalJsOnload() {
    try {     
    	showBulletinThisForTestUsers();
        dimmerLayerController.createDimmerLayer(); 
        
        //check to show ksolo member notice
        if (location.href.toLowerCase().indexOf("redir=1") != -1 && (document.referrer == null || document.referrer == ""))
		{
			popupDivController.createPopupDiv_kSoloMemberNotice("/jsp/popup_kSoloMemberNotice.jsp");
		}
            
		pluginController.init();
        BrowserDetect.init();
        executePlayerOnDemandFunction();
    } catch(e) {}
}

function globalJsOnUnload() {
    try {
        if ($("kSoloRecorder") != null) {        
            $("kSoloRecorder").bMonitorMute = true;          
        }
        else if ($("kSoloRecorderFF") != null) {
            $("kSoloRecorderFF").bMonitorMute = true;            
        }
    } catch(e) {}
}

function loadMyspaceAd() {
    try {
        if ($("teazer").innerHTML == "nonHomepage")
            $("teazer").innerHTML = '<iframe src="/jsp/nonHomepageAd.jsp" frameborder="0" scrolling="no"></iframe>';
        if ($("teazer").innerHTML == "homepage")
            $("teazer").innerHTML = '<iframe src="/jsp/homepageAd.jsp" frameborder="0" scrolling="no"></iframe>';
    } catch(e) {}
}

function executePlayerOnDemandFunction() {
    try {
        var obj = new cookieObj();
        var playerOnDemandFunction = obj.readCookie("playerOnDemandFunction");
         
        if (playerOnDemandFunction != null) {            
            eval(unescape(playerOnDemandFunction));
            obj.deleteCookie("playerOnDemandFunction");
        }        
    } catch(e) {}
}

function trimString(elementID,elementLength,passingString,htmlStart,htmlEnd){
	/* By Sam Darabi 
	This function calculates the length of the string and then if needed truncates and displays the '...' after the string accordingly.
	elementID = The element in the JSP file that contains the string (anchor, Span, Div, etc..) This has to be a unique ID on the page.
	elementLength = The Maximum length of elementID
	passingString = The String to be displayed/truncated
	htmlStart = Optional (if there is additional html code in the element that STARTS before the string pass here)
	htmlEnd = Optional (if there is additional html code in the element that ENDS after the string pass here)
	*/
	
	if(!htmlStart)htmlStart="";
	if(!htmlEnd)htmlEnd="";
	var object=document.getElementById(elementID)
	object.innerHTML=passingString;

	if(object.offsetWidth>elementLength || object.offsetHeight>20){
		try{
			var StringLength=passingString.length;
			while(object.offsetWidth>elementLength || object.offsetHeight>20){
				object.innerHTML=passingString.substring(0,StringLength);
				StringLength-=1;
			}
			object.innerHTML=passingString.substring(0,StringLength-1)+"...";
		}catch(e){}
	}
	object.innerHTML=htmlStart+object.innerHTML+htmlEnd;
	if(object.offsetWidth>elementLength){
		object.style.width=elementLength+"px";
	}
}


function showBulletinThisForTestUsers() {
    try {
        if (bulletinController._hdBltn == 0) {    //need to hide bulletin this
            if ($("bulletinThisWrapper") != null) {
                $("bulletinThisWrapper").style.display = "block";
            }
            if ($("bulletinThisWrapper_recordings") != null) {
                $("bulletinThisWrapper_recordings").style.display = "block";
            }
        }
    } catch(e) {}
} 

function checkPluginVersionAndUpdateDB(userPluginVer) {
	try {
		var instPluginVer = "";
		
		if ($("AVControl") != null) {
			instPluginVer = $("AVControl").sVersion;
		} else if ($("AVControlFF") != null) {
			instPluginVer = $("AVControlFF").sVersion;
		}
		
		if (instPluginVer != "") {
			userPluginVer = userPluginVer.replace(/,/g, '.');
			if(userPluginVer != instPluginVer) {
				new Ajax.Request("/actions/installCabResults.do?cv="+instPluginVer.replace(/\./gi, ",")+"&instResults=2", {
					onSuccess: function(resp) {}
				});
			}
		}
	} catch(e) {}
}

// Writes Flash Content to <div> element...
function generateFlashContentToDiv(div, width, height, id, src) 
{
    try 
	{
		// Write Html...
        var html = '<object width="'+width+'" height="'+height+'" id="'+id+'" data="'+src+'" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0">';
        html += '<param name="movie" value="'+src+'"/>';
        html += '<param name="allowfullscreen" value="false" />';
        html += '<param name="allowScriptAccess" value="always" />';
        html += '<param name="allowNetworking" value="all" />';
        html += '<param name="wmode" value="transparent" />';
        html += '<embed src="'+src+'" width="'+width+'" height="'+height+'" name="'+id+'" id="'+id+'" allowfullscreen="false" allowScriptAccess="always" allowNetworking="all" quality="high" align="middle" type="application/x-shockwave-flash" wmode="transparent" pluginspage="http://www.macromedia.com/go/getflashplayer"/>';
        html += '</object>'; 
		
		// Write to div...
		$(div).innerHTML = html;
    } 
	catch(e) {}
}

function sendSongChainReminder(SongChainID, msg){

	try {
		new Ajax.Request("/actions/resendSongChainInvite.do?chainId="+SongChainID+"&i="+Math.random(), {
			onSuccess: function(resp) {
				alert(msg);
			}
		});
	} catch(e) {}

}

function SongChainPopUp(OpenCloseSave){

/* 1 = Open the form
   2 = Cancel the form
   3 = Sumbit the form
*/

	try
	{
		if (OpenCloseSave==1){
			$("flashPlayer").style.visibility = "hidden";
			$("SongChainPopUp").style.display="block";
			$("SongChainDimmer").style.display="block";
			
			if(SAF){
            	top.document.getElementById("SongChainDimmer").style.height = document.body.scrollHeight+ "px";
			}else{                        
            	top.document.getElementById("SongChainDimmer").style.height = top.document.documentElement.scrollHeight + "px";
            }   
			
			/* Clear fields */
				$("SongChainFlag").innerHTML="";
				$("frm_Creator").innerHTML="";
				$("frm_Creator_email").innerHTML="";
				
				for(i=1;i<=3;i++){
					$("Participant"+i).value="Name";
					$("Participant"+i+"_email").value="Email";
					$("frm_part"+i).innerHTML="";
					$("frm_part"+i+"_email").innerHTML="";
				}
			/**/
			
			var creatorName = $("CreatorsName").innerHTML.replace(/<b>/,"");
			creatorName = creatorName.replace("</b>","");
			var creatorEmail = $("CreatorsEmail").innerHTML.replace(/<b>/,"");
			creatorEmail = creatorEmail.replace("</b>","");
			
			$("Creator").value=creatorName;
			$("Creator_email").value=creatorEmail;
		}
		if (OpenCloseSave==2){
			// clear all fields, in case user records again and saves as songchain
				$("SongChainFlag").innerHTML="";
				$("frm_Creator").innerHTML="";
				$("frm_Creator_email").innerHTML="";
				var SaveRecordState = $("DoNotStartRecording").innerHTML; // need to save this before we clear it. because we need to know if we should play the song or not after user cancels
				$("DoNotStartRecording").innerHTML="";
				for(i=1;i<=8;i++)$("err"+i).style.display="none";
				
				for(i=1;i<=3;i++){
					$("Participant"+i).style.color="#ccc";
					$("Participant"+i+"_email").style.color="#ccc";
					$("Participant"+i).value="Name";
					$("Participant"+i+"_email").value="Email";
					$("frm_part"+i).innerHTML="";
					$("frm_part"+i+"_email").innerHTML="";
				}
			/**/

			// User Cancelled - Hide PopUp
			$("flashPlayer").style.visibility = "visible";
			AVControl.style.visibility="visible";
			$("SongChainPopUp").style.display="none";
			$("SongChainDimmer").style.display="none";
			
			//User started the songchain from popup.. play the song
			if(SaveRecordState!=1)playSong("0", 0);
			
		}
		if (OpenCloseSave==3){
			
			/* VALIDATION SECTION */
				// set variables //
				var errFlag=0;
				var creator = trimMe($("Creator").value);
				var creator_e = trimMe($("Creator_email").value);
				var part1 = trimMe($("Participant1").value);
				var part1_e = trimMe($("Participant1_email").value);
				var part2 = trimMe($("Participant2").value);
				var part2_e = trimMe($("Participant2_email").value);
				var part3 = trimMe($("Participant3").value);
				var part3_e = trimMe($("Participant3_email").value);
				
				if(part1=="Name")part1="";
				if(part2=="Name")part2="";
				if(part3=="Name")part3="";
				if(part1_e=="Email")part1_e="";
				if(part2_e=="Email")part2_e="";
				if(part3_e=="Email")part3_e="";
				
				
			/**/
			
			/* Clear Error Messages */
			for(i=1;i<=8;i++)$("err"+i).style.display="none";
				
			/* Required Fields */
				if(creator==""){$("err1").style.display="block";errFlag=1;}
				if(creator_e==""){$("err2").style.display="block";errFlag=1;}
				if(part1==""){$("err3").style.display="block";errFlag=1;}
				if(part1_e==""){$("err4").style.display="block";errFlag=1;}
			/**/
			
			/* Email validation */
				if(!ValidateEmail(creator_e)){
					$("err2").style.display="block";
					errFlag=1;
				}
				if(!ValidateEmail(part1_e)){
					$("err4").style.display="block";
					errFlag=1;
				}
				
				if(part2_e!=""){
					if(!ValidateEmail(part2_e)){
						$("err6").style.display="block";
						errFlag=1;
					}
				}
				if(part3_e!=""){
					if(!ValidateEmail(part3_e)){
						$("err8").style.display="block";
						errFlag=1;
					}
				}				
			/**/
			
			/* If a user enters a name but forgets an email or vise versa */
				if(part2==""){
					if(part2_e!=""){
						$("err5").style.display="block";
						errFlag=1;
					}
				}
				if(part2_e==""){
					if(part2!=""){
						$("err6").style.display="block";
						errFlag=1;
					}
				}
				if(part3==""){
					if(part3_e!=""){
						$("err7").style.display="block";
						errFlag=1;
					}
				}
				if(part3_e==""){
					if(part3!=""){
						$("err8").style.display="block";
						errFlag=1;
					}
				}			
			/**/
			
			if(errFlag==1){
				return false;
			}
			
			/* END OF VALIDATION */
			
			
			/* Save form Values in hidden divs */
			
			$("SongChainFlag").innerHTML="1";
			$("frm_Creator").innerHTML=creator;
			$("frm_Creator_email").innerHTML=creator_e;
			
			$("frm_part1").innerHTML=part1;
			$("frm_part2").innerHTML=part2;
			$("frm_part3").innerHTML=part3;
			
			$("frm_part1_email").innerHTML=part1_e;
			$("frm_part2_email").innerHTML=part2_e;
			$("frm_part3_email").innerHTML=part3_e;

			$("SongChainPopUp").style.display="none";
			$("SongChainDimmer").style.display="none";
			
			$("flashPlayer").style.visibility = "visible";
			AVControl.style.visibility="visible";
			
			if($("DoNotStartRecording").innerHTML!=1){
				/* Start Recording */
				playSong("0", 1);
				playerController.sendMessageToKaraokePlayer(playerControllerCmd.MESSAGE_PARAMETER_START_SONG_CHAIN_MODE,true);	
			}
			else{
				// User started the song chain from PlugIn - need to resume save function again..
				var1=$("saveContents").innerHTML;
				var2=$("saveTrackid").innerHTML;
				var3=$("saveSongname").innerHTML;
				var4=$("saveNote").innerHTML;
				var5=$("saveKey").innerHTML;
				var6=$("saveMoodId").innerHTML;
				var7=$("saveMoodNote").innerHTML;
				var8=$("saveChainId").innerHTML;
				var9=$("saveChainOrder").innerHTML;
				var10=$("saveNewSongChainFlag").innerHTML;
				
				if (var4=="")var4=" ";
				
				pluginController.save(var1, var2, var3, var4, var5, var6, var7, var8, var9, var10);
			}
		}
	}
	catch(e){}
}	

function updateInput(txtBox){

	for(i=1;i<=3;i++){
		var tmpName=trimMe($("Participant"+i).value);
		var tmpEmail=trimMe($("Participant"+i+"_email").value);
		if (tmpName==""){
			$("Participant"+i).value="Name";
			$("Participant"+i).style.color="#ccc";
		}
		if (tmpEmail==""){
			$("Participant"+i+"_email").value="Email";
			$("Participant"+i+"_email").style.color="#ccc";
		}
	}
	
	if(txtBox.value=="Name"||txtBox.value=="Email"){
		txtBox.value="";
	}
	txtBox.style.color="#000000";
}


function trimMe(sString){
	while (sString.substring(0,1) == ' '){
		sString = sString.substring(1, sString.length);
	}
	while (sString.substring(sString.length-1, sString.length) == ' '){
		sString = sString.substring(0,sString.length-1);
	}
	return sString;
}

/* Email validation  */

function ValidateEmail(str) {

	var at="@"
	var dot="."
	var lat=str.indexOf(at)
	var lstr=str.length
	var ldot=str.indexOf(dot)
	if (str.indexOf(at)==-1){
	   return false
	}

	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
	   return false
	}
	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
	    return false
	}
	 if (str.indexOf(at,(lat+1))!=-1){
	    return false
	 }
	 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
	    return false
	 }
	 if (str.indexOf(dot,(lat+2))==-1){
	    return false
	 }
	 if (str.indexOf(" ")!=-1){
	    return false
	 }
	 return true
}

/* */


function generateFlashContent(width, height, id, value, lang) {
    try {
    	var LocalLang="en";
    	if(lang=="JP")LocalLang="ja";
    		
        document.writeln('<object width="'+width+'" height="'+height+'" id="'+id+'" data="'+value+'?lang='+LocalLang+'" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0">');
        document.writeln('<param name="movie" value="'+value+'?lang='+LocalLang+'"/>');
        document.writeln('<param name="allowScriptAccess" value="always" />');
        document.writeln('<param name="allowNetworking" value="all" />');
        document.writeln('<param name="wmode" value="transparent" />');
        document.writeln('<embed src="'+value+'?lang='+LocalLang+'" quality="high" width="'+width+'" height="'+height+'" name="'+id+'" id="'+id+'" align="middle" type="application/x-shockwave-flash" wmode="transparent" pluginspage="http://www.macromedia.com/go/getflashplayer"/>');
        document.writeln('</object>');        
    } catch(e) {}
}

function generateSponsorByContent(urlString) {
    try {
        new Ajax.Request("/actions/requestLogo.do?pos=sponsorby&fmt=string", {
            onSuccess: function(resp) {
                var imgSrc = resp.responseText.strip();
                var imgObj = document.getElementById("sponsorByImg");
                if (imgSrc.indexOf("blank.gif") == -1) {
                    imgObj.src = imgSrc;
                    imgObj.style.cursor = "pointer";
                    Event.observe(imgObj, "click", function() {window.open(urlString, "tlc");});                                   
                }
                else {
                    imgObj.style.display = "none";
                }
            }
        });
    } catch(e) {}
}

function generateCelebrityBadgeContent(urlString) {
    try {
        new Ajax.Request("/actions/requestLogo.do?pos=celebbadge&fmt=string&artistId=" + document.searchActionForm.artistId.value, {
            onSuccess: function(resp) {
                var imgSrc = resp.responseText.strip();
                var imgObj = document.getElementById("CelebrityBadgeImg");
                if (imgSrc.indexOf("blank.gif") == -1) {
                    imgObj.src = imgSrc;
                    imgObj.style.cursor = "pointer";
                    Event.observe(imgObj, "click", function() {window.open(urlString, "myspacecelebrity");});     
                    
                    var titleObj = document.getElementById("SectionTitle");
                    titleObj.style.width = "332px";
                }
                else {
                    imgObj.style.display = "none";
                }
            }
        });
    } catch(e) {}
}

function generateSkinBgContent(StageTest) {
	var sTest = StageTest;
    try{
		var SkinImgSrc=document.getElementById("google_ads_iframe_"+sTest+"US_Homepage_Skin_1554x1000").contentWindow.document.getElementById("aw0").innerHTML;
	   	var j=SkinImgSrc.indexOf('http');
	   	SkinImgSrc=SkinImgSrc.substr(j);
	   	var i=SkinImgSrc.indexOf('"');
	    SkinImgSrc=SkinImgSrc.substr(0,i);
	    document.body.style.background = "url("+SkinImgSrc+") fixed no-repeat center top";
	    //document.getElementById("footerMySpace").style.width="958px";
		
	}catch(e) {}
   /* try {
        new Ajax.Request("/actions/requestLogo.do?pos=homepage&fmt=string", {
            onSuccess: function(resp) {
                var imgSrc = resp.responseText.strip();                 
                if (imgSrc.indexOf("blank.gif") == -1) {
                    document.body.style.background = "url("+imgSrc+") fixed no-repeat center top";
                    $("popupContainer").innerHTML += '<a href="http://ad.n2434.doubleclick.net/jump/N2434.myspace/B3274476.7;sz=1x1;ord=[timestamp]?"><img border="0" width="1" height="1" src="http://ad.n2434.doubleclick.net/ad/N2434.myspace/B3274476.7;sz=1x1;ord=[timestamp]?"></a>';
                }
            }
        });
    } catch(e) {}*/
}

function generateFlashPlayerContent(width, height, id, value) {
    try {    
        pluginController.addPluginToPage();        				
        if (navigator.userAgent.toLowerCase().indexOf("ie") != -1) {        
            document.writeln('<object width="'+width+'" height="'+height+'" id="'+id+'" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0">');
            document.writeln('<param name="allowFullScreen" value="true" />');
            document.writeln('<param  name="menu" value="false" />');
            document.writeln('<param name="allowScriptAccess" value="sameDomain"/>');
            document.writeln('<param name="movie" value="'+value+'"/>');
            document.writeln('<param name="quality" value="high"/>');
			//document.writeln('<param name="wmode" value="transparent" />');
            document.writeln('</object>');
        }
        else {            
            document.writeln('<embed src="'+value+'" width="'+width+'" height="'+height+'" name="'+id+'" id="'+id+'" quality="high" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" menu="false" allowFullScreen="true" pluginspage="http://www.macromedia.com/go/getflashplayer"/>');            
        }            
    } catch(e) {}
}

// Writes Flash Content to <div> element...
function generateFlashMiniPlayerContentToDiv(div, width, height, id, value, initImage, initSong, initUid, initSid, initRid, lang) 
{
	var LocalLang="en";
    	if(lang=="JP")LocalLang="ja";
    try 
	{
		
		var html = '<embed src="'+value+'?lang='+LocalLang+'" ' +
				'wmode="transparent" ' +
				'quality="high" ' +
				'bgcolor="#ffffff" ' +
				'flashvars="info='+initImage+'~25000~'+initSong+'~true~'+initUid+'~'+initSid+'~'+initRid+'~'+webServerAddress+'/actions/showSongProfile.do?~false" ' +
				'width="'+width+'" ' +
				'height="'+height+'" ' +
				'name="'+id+'" ' +
				'id="'+id+'" ' +
				'align="middle" ' +
				'allowScriptAccess="sameDomain" ' +
				'type="application/x-shockwave-flash" ' +
				'menu="false" ' +
				'allowFullScreen="true" ' +
				'pluginspage="http://www.macromedia.com/go/getflashplayer"/>';

        if (IE6 || IE7 || IE8) 
		{
            html = '<object width="'+width+'" height="'+height+'" id="'+id+'" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0">';
            html += '<param name="allowFullScreen" value="true" />';
            html += '<param  name="menu" value="false" />';
            html += '<param name="allowScriptAccess" value="sameDomain"/>';
            html += '<param name="movie" value="'+value+'?lang='+LocalLang+'"/>';
            html += '<param name="quality" value="high"/>';            
            html += '<param name="bgcolor" value="#ffffff" />';       
            html += '<param name="wmode" value="transparent" />'; 
            html += '<param name="flashvars" value="info='+initImage+'~25000~'+initSong+'~true~'+initUid+'~'+initSid+'~'+initRid+'~'+webServerAddress+'/actions/showSongProfile.do?~false" />'; 
            html += '</object>';
        }
		
		// Write to div...
		$(div).innerHTML = html;
    } 
	catch(e) {}
}

function generateFlashMiniPlayerContent(width, height, id, value, initImage, initSong, initUid, initSid, initRid) {
    try 
	{
        if (IE6 || IE7 || IE8)  
		{
            document.writeln('<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="'+width+'" height="'+height+'" id="'+id+'" align="middle">');
            document.writeln('<param name="allowFullScreen" value="true" />');
            document.writeln('<param  name="menu" value="false" />');
            document.writeln('<param name="allowScriptAccess" value="sameDomain"/>');
            document.writeln('<param name="movie" value="'+value+'"/>');
            document.writeln('<param name="quality" value="high"/>');            
            document.writeln('<param name="bgcolor" value="#ffffff" />');       
            document.writeln('<param name="wmode" value="transparent" />'); 
            document.writeln('<param name="flashvars" value="info='+initImage+'~25000~'+initSong+'~true~'+initUid+'~'+initSid+'~'+initRid+'~'+webServerAddress+'/actions/showSongProfile.do?~false" />'); 
            document.writeln('</object>');
        }
        else 
		{            
            document.writeln('<embed src="'+value+'" wmode="transparent" quality="high" bgcolor="#ffffff" flashvars="info='+initImage+'~25000~'+initSong+'~true~'+initUid+'~'+initSid+'~'+initRid+'~'+webServerAddress+'/actions/showSongProfile.do?~false" width="'+width+'" height="'+height+'" name="'+id+'" id="'+id+'" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" menu="false" allowFullScreen="true" pluginspage="http://www.macromedia.com/go/getflashplayer"/>');            
        }            		
    } 
	catch(e) {}
}
var dimmerLayerController = {    
    createDimmerLayer : function() {
        try {
            if (top.document.getElementById("dimmerLayer") == null) {
                var newDiv = top.document.createElement("div");
                newDiv.id = "dimmerLayer";
                newDiv.style.position = "absolute";        
                newDiv.style.top = "0px";
                newDiv.style.left = "0px";
                newDiv.style.width = "100%";       
                top.document.body.appendChild(newDiv); 
                top.document.getElementById("dimmerLayer").style.background = "#8F8F8F";
                top.document.getElementById("dimmerLayer").style.zIndex = "1000";
                top.document.getElementById("dimmerLayer").style.opacity = "0.6";
                top.document.getElementById("dimmerLayer").style.filter = "alpha(opacity=60)";
                top.document.getElementById("dimmerLayer").style.display = "none";
            }            
        } catch(e) {}
    },
    
    openDimmerLayer : function() {
        try {            
            top.document.getElementById("dimmerLayer").style.display = "block";
            if(SAF){
            	top.document.getElementById("dimmerLayer").style.height = document.body.scrollHeight+ "px";
			}else{                        
            	top.document.getElementById("dimmerLayer").style.height = top.document.documentElement.scrollHeight + "px";
            }      
        } catch(e) {}
    },
    
    closeDimmerLayer : function() {
        try {
            top.document.getElementById("dimmerLayer").style.display = "none";
        } catch(e) {}
    }
}

Event.observe(window, "load", globalJsOnload);
Event.observe(window, "unload", globalJsOnUnload);
Event.observe(top.document, "click", function(event) {    
    try {
        popupDiv_statusMsg._posX = Event.pointerX(event);
        popupDiv_statusMsg._posY = Event.pointerY(event);    
    } catch(e) {}
});

var AVXInfo = {
    _version : "",  //currently installed version
    _build : "",    //currently installed build
    _newVersion : "",   //new version
    _changelog : "",    //new version changelog
    _majorUpgrade : null,
            
    check4Update : function() {      
        this.checkNewVersion();        
    },

    checkNewVersion : function() {
    	var KsoloInstalltxt;
    	if (navigator.userAgent.match("Macintosh")){
    		KsoloInstalltxt = "/playerBase/kSolo_Install_Mac_ver.txt"
    	}else{
    		KsoloInstalltxt = "/playerBase/kSolo_Install_ver.txt"
    	}
        new Ajax.Request(KsoloInstalltxt, {
            onSuccess: function(resp) {
                //alert(AVXInfo._version);
                var objArr = eval('('+resp.responseText.strip()+')');                
                AVXInfo._changelog = objArr.changelog;
                AVXInfo._newVersion = objArr.version.strip();
                var curVerArr = AVXInfo._version.split(".");
                var newVerArr = objArr.version.strip().split(".");
                                       
                for (var i = 0; i < curVerArr.length; i++) {
                    //alert(parseInt(newVerArr[i])+","+parseInt(curVerArr[i]));
                    if (parseInt(newVerArr[i]) >  parseInt(curVerArr[i])) {                                                
                        if (i == 0 || i == 1 || i == 2) {
                            AVXInfo._majorUpgrade = true;
                        }   
                        else if (i == 3 && AVXInfo._majorUpgrade == null) {
//uncomment on next plugin version
//                            AVXInfo._majorUpgrade = true; // This forces an upgrade
                            AVXInfo._majorUpgrade = false;  
                        }
                    }                           
                    else if (parseInt(newVerArr[i]) <  parseInt(curVerArr[i])) {                        
                        break;
                    }
                }   
                if (AVXInfo._majorUpgrade != null) {   //there's new version available
                    if (AVXInfo._majorUpgrade) {
                        pluginUpgrade.startUpgradeProcess();                        
                    }
                    else if (!AVXInfo._majorUpgrade) {
                        var cookie = new cookieObj();
                        var lastCheck4PluginUpgradeTs = cookie.readCookie("lastCheck4PluginUpgradeTs");
                        var lastCheck4PluginUpgradeVer = cookie.readCookie("lastCheck4PluginUpgradeVer");
                        var nowTs = new Date().getTime();
                        
                        //we only proceed with upgrade process when it has been 7 days since last time we show 
                        //the upgrade popup or there's a newer version since last time the user did not want the upgrade 
                        if ((lastCheck4PluginUpgradeTs == null) ||
                            (lastCheck4PluginUpgradeTs != null &&
                                Math.abs(parseInt(nowTs)-parseInt(lastCheck4PluginUpgradeTs))/1000 > 86400*parseInt(resources.getMessage("popup.pluginNewVerUpgrade.numOfDayToCheckAgain"))) ||
                            (lastCheck4PluginUpgradeVer != null &&
                                AVXInfo.haveNewerVersion(lastCheck4PluginUpgradeVer, AVXInfo._newVersion))) {
                         
                            pluginUpgrade.startUpgradeProcess();                        
                        }             
                    }
                }
                else {
                    //we do not have new version, so update the db
                    AVXInfo.updateVerInDb();
                }
            }
        }); 
    },
    
    haveNewerVersion : function(curVer, newVer) {
        try {
            var curVerArr = curVer.strip().split(".");
            var newVerArr = newVer.strip().split(".");
            for (var i = 0; i < curVerArr.length; i++) {                
                if (parseInt(newVerArr[i]) >  parseInt(curVerArr[i])) {                        
                    return true;
                }                           
                else if (parseInt(newVerArr[i]) <  parseInt(curVerArr[i])) {                        
                    return false;
                }
            }
            return false;
        } catch(e) {}
    },
    
    updateVerInDb : function() {   
        var obj = new cookieObj();
        var curVerCookie = obj.readCookie("pluginVer");         
        if (curVerCookie != null) {
            new Ajax.Request("/actions/installCabResults.do?cv="+this._version.replace(/\./gi, ",")+"&instResults=2", {
                onSuccess: function(resp) {
                    obj.deleteCookie("pluginVer");
                }
            }); 
        }
    }
}

var pluginUpgrade = {
    _stopPlayingSongRepeater : null,
    _stopPlayingSongOriginalTime : 0,
    
    startUpgradeProcess : function() {
        try {
            this._stopPlayingSongOriginalTime = new Date().getSeconds();
            this._stopPlayingSongRepeater = window.setInterval(function() {pluginUpgrade.stopPlayingSong();}, 1);
			AVXInfo._majorUpgrade ? this.createPopupPluginNewVerDiv_mandatory() : this.createPopupPluginNewVerDiv_optional();
            /*
		    this.FFZIndexFix();
	        dimmerLayerController.openDimmerLayer();
			if (AVXInfo._majorUpgrade) {
                //alert('major');
                this.createPopupPluginNewVerDiv_mandatory();
				//popupDiv_upgradePlayer.createDiv();
            }
            else if (!AVXInfo._majorUpgrade) {
                //alert('minor');
                this.createPopupPluginNewVerDiv_optional();
				//popupDiv_upgradePlayer.createDiv(); 
            }
            this.positionPopup();
			*/
        } catch(e) {}
    },
    
    createPopupPluginNewVerDiv_optional : function() {
        try {            
            if ($("popup_pluginNewVerWrapper") == null) {
                var body = document.body;
                var newDiv = document.createElement("div");
                newDiv.id = "popup_pluginNewVerWrapper";
				newDiv.className = "ClearFix";                                
                newDiv.style.position = "absolute";                                
                newDiv.style.left = parseInt(document.documentElement.clientWidth/2) - 377 + "px";
                newDiv.style.top = parseInt(document.documentElement.clientHeight/2) - 85 + document.documentElement.scrollTop + "px";  
                newDiv.style.zIndex = 2000;
                newDiv.innerHTML = '<div id="popup_topBtnWrapper" class="popup_topBtnWrapper" onmouseover="this.className=\'popup_topBtnWrapperHover\'" onmouseout="this.className=\'popup_topBtnWrapper\'" onclick="pluginUpgrade.noUpgradeNow();"></div>' +
					'<div id="popup_topWrapper"></div>' +
					'<div id="popup_middleWrapper" class="ClearFix">' +
						'<div id="popup_pluginNewVerTxt">' + 
							'<iframe src="/jsp/popup_upgradePlayer.jsp?isMandantory=false" allowtransperancy="true" frameborder="0" height="135" scrolling="no" width="420"></iframe>' + 
						'</div>' +
						'<input type="button" value="' + resources.getMessage("popup.pluginNewVerUpgrade.btnTxtOk") + '" onclick="pluginUpgrade.upgradeNow()" />' +
					'</div>' +
					'<div id="popup_bottomWrapper"></div>';
		        this.FFZIndexFix();
	            dimmerLayerController.openDimmerLayer();
                body.appendChild(newDiv); 
				this.positionPopup();             
            }            
        } catch(e) {}
    },
    
    createPopupPluginNewVerDiv_mandatory : function() {
        try {
            if ($("popup_pluginNewVerWrapper") == null) {
                var body = document.body;
                var newDiv = document.createElement("div");
                newDiv.id = "popup_pluginNewVerWrapper";
				newDiv.className = "ClearFix";
                newDiv.style.position = "absolute";                
                newDiv.style.left = parseInt(document.documentElement.clientWidth/2) - 377 + "px";
				newDiv.style.top = parseInt(document.documentElement.clientHeight/2) - 85 + document.documentElement.scrollTop + "px";
                newDiv.style.zIndex = 2000;
                newDiv.innerHTML = '<div id="popup_topWrapper"></div>' +
					'<div id="popup_middleWrapper" class="ClearFix">' +
						'<div id="popup_pluginNewVerTxt">' + 
							'<iframe src="/jsp/popup_upgradePlayer.jsp?isMandantory=true" allowtransperancy="true" frameborder="0" height="135" scrolling="no" width="420"></iframe>' + 
						'</div>' +
						'<input type="button" value="' + resources.getMessage("popup.pluginNewVerUpgrade.btnTxtOk") + '" onclick="pluginUpgrade.upgradeNow()" />' +
					'</div>' +
					'<div id="popup_bottomWrapper"></div>';
		        this.FFZIndexFix();
	            dimmerLayerController.openDimmerLayer();
                body.appendChild(newDiv); 
				this.positionPopup();              
            }            
        } catch(e) {}
    },
    
    FFZIndexFix : function() {
        try {
            //this is because wmode=transparent issue with current version flash player #9,0,28,0            
            if ($("kSoloRecorderFF") != null || $("flashPlayer") != null) {
                closePlayer();
            }
            if ($("userPhotos") != null) {                    
                $("userPhotos").style.visibility = "hidden";                    
            }   
        } catch(e) {}
    },
    
    stopPlayingSong : function() {
        try {
            window.pluginController.stop();
            var newTime = new Date().getSeconds();
            if (Math.abs(pluginUpgrade._stopPlayingSongOriginalTime-newTime) > 10) {
                window.clearInterval(pluginUpgrade._stopPlayingSongRepeater);
            }
        } catch(e) {}
    },
    
    positionPopup : function() {
        try {                        
            new Draggable("popup_pluginNewVerWrapper", {starteffect:null, endeffect:null});
        } catch(e) {}
    },        
    
    noUpgradeNow : function() {
        try {
            var cookie = new cookieObj();
            cookie.createCookie("lastCheck4PluginUpgradeTs", new Date().getTime(), 365);
            cookie.createCookie("lastCheck4PluginUpgradeVer", AVXInfo._newVersion, 365);
            new Effect.Shrink("popup_pluginNewVerWrapper", {
				direction: 'center', 
				duration: 0.4,
				afterFinish: function() {
					dimmerLayerController.closeDimmerLayer();
					var obj = new cookieObj();
					var songId = obj.readCookie("reloadPlayerAfterInstallSongId");  
					if ($("flashPlayerContainer") != null && songId != null) {
						var obj = new cookieObj();	                                                                        
						openPlayer(obj.readCookie("reloadPlayerAfterInstallSongId"));
					}
					if ($("userPhotos") != null) {
						$("userPhotos").style.visibility = "visible";                    
					}
				}
			});
        } catch(e) {}
    },
    
    upgradeNow : function() {
        try {
            var cookie = new cookieObj();
            cookie.deleteCookie("lastCheck4PluginUpgradeTs");
            cookie.deleteCookie("lastCheck4PluginUpgradeVer");
            new Effect.Shrink("popup_pluginNewVerWrapper", {direction: 'center', duration: 0.4, afterFinish: function() {top.location.href = "/installCab.do";}});            
        } catch(e) {}
    }
}

//generic popup controller
var popupDivController = {
    FFZIndexFix : function() {
        try {
            //this is because wmode=transparent issue with current version flash player #9,0,28,0
            if ($("kSoloRecorderFF") != null || $("flashPlayer") != null) {
                closePlayer();
            }
            if ($("userPhotos") != null) {                    
                $("userPhotos").style.visibility = "hidden";                    
            }                    
        } catch(e) {}
    },
            
    createPopupDiv_tellAFriend : function() {
        try {            
            this.FFZIndexFix();
            dimmerLayerController.openDimmerLayer();                                                   
            popupDiv_tellAFriend.createDiv();                          
        } catch(e) {}
    },
    
    createPopupDiv_leaveUserFeedback : function(strUrl) {
        try {            
            this.FFZIndexFix();
            dimmerLayerController.openDimmerLayer();
			//this.openPopupAsIframe(350,strUrl,false);
            popupDiv_leaveUserFeedback.createDiv(strUrl);      
        } catch(e) {}
    },
    
    createPopupDiv_addPerformerToFavorites : function(strUrl) {
        try {            
            this.FFZIndexFix();
            dimmerLayerController.openDimmerLayer();
            popupDiv_addPerformerToFavorites.createDiv(strUrl);      
        } catch(e) {}
    },
    
    createPopupDiv_shareWithFriends : function(strUrl) {
        try {            
            this.FFZIndexFix();
            dimmerLayerController.openDimmerLayer();
            popupDiv_shareWithFriends.createDiv(strUrl);      
        } catch(e) {}
    },
    
    createPopupDiv_shareWithFriendsProcessing : function() {
        try {            
            this.FFZIndexFix();
            dimmerLayerController.openDimmerLayer();
            popupDiv_shareWithFriends.createDivProcessing();      
        } catch(e) {}
    },
    
    createPopupDiv_termsOfUse : function() {
        try 
		{            
            this.FFZIndexFix();
            dimmerLayerController.openDimmerLayer();
			this.openPopupAsIframe(400,'/popupTermsOfUse.do',true);      
        } 
		catch(e) {}
    },
    
    createPopupDiv_subscriptionAgreement : function() {
        try 
		{            
            this.FFZIndexFix();
            dimmerLayerController.openDimmerLayer();
			this.openPopupAsIframe(400,'/subscriptionAgreement.do',true);      
        } 
		catch(e) {}
    },
    
    createPopupDiv_termsOfPurchase : function() {
        try 
		{            
            this.FFZIndexFix();
            dimmerLayerController.openDimmerLayer();
			this.openPopupAsIframe(400,'/popupTermsOfPurchase.do',false);    
        } 
		catch(e) {}
    },
    
    createPopupDiv_privacyPolicy : function() {
        try 
		{            
            this.FFZIndexFix();
            dimmerLayerController.openDimmerLayer();
			this.openPopupAsIframe(400,'/popupPrivacyPolicy.do',false);    
        } 
		catch(e) {}
    },    
    
    createPopupDiv_kSoloMemberNotice : function(strUrl) {
        try {
            $("medRecAd").style.display = "none";            
            this.FFZIndexFix();
            dimmerLayerController.openDimmerLayer();
			this.openPopupAsIframe(250,strUrl,false);              
        } 
		catch(e) {}
    },    
    
    closePopup : function() {
        try {          
            dimmerLayerController.closeDimmerLayer();            
            bulletinController._fromNewlyCreatedRec = false;
            popupDiv_shareWithFriends._justSaveRec = "false";
            popupDiv_shareWithFriends._perm = "public";
            $("popup_wrapper").remove();
            var createLink = false;
            if($("isRecordingView")){createLink = true;}

			var obj = new cookieObj();
			var songId = obj.readCookie("reloadPlayerAfterInstallSongId");                
			if ($("flashPlayerContainer") != null && songId != null) 
			{
				var obj = new cookieObj();	                    
				openPlayer(obj.readCookie("reloadPlayerAfterInstallSongId"));
			}
			if ($("userPhotos") != null) 
			{
				$("userPhotos").style.visibility = "visible";                    
			}

            if(getAVControl() && pluginController.getCaptureMode()==1){
				getAVControl().style.width="227px";
				getAVControl().style.height="170px";
			}
        } 
		catch(e) {}
    },

    openPopupAsIframe : function(height, src, includeButton) {
        try 
		{
			popupDivController.openPopupAsIframeWidth(400, height, src, includeButton);
        } 
		catch(e) {}
    },

    openPopupAsIframeWidth : function(width, height, src, includeButton) {
        try 
		{
			//alert ("clientWidth=" + document.documentElement.clientWidth + 
			//	", clientHeight=" + document.documentElement.clientHeight + 
			//	", scrollTop=" + document.documentElement.scrollTop);

			var overWidthCorrection = 0;
			var halfWidthPopup = parseInt(width / 2);
			var halfWidthWindow = parseInt(document.documentElement.clientWidth / 2);
			var halfHeightPopup = parseInt(height / 2);
			var halfHeightWindow = parseInt(document.documentElement.clientHeight / 2);
			var scrollTop = parseInt(document.documentElement.scrollTop);
			if(SAF) scrollTop = parseInt(document.body.scrollTop);

			// Fixes "LEFT" position if window > 960px
			if (document.documentElement.clientWidth > 960)
			{
				overWidthCorrection = (document.documentElement.clientWidth - 960) / 2;
			}
			
			var newDiv = document.createElement("div");
			newDiv.id = "popup_wrapper";
			newDiv.style.display = "block";
			newDiv.style.position = "absolute";
			newDiv.style.left = (halfWidthWindow - halfWidthPopup - overWidthCorrection) + "px";
			newDiv.style.top = (halfHeightWindow - halfHeightPopup + scrollTop - 50) + "px";  
			newDiv.style.zIndex = 2000;                
			newDiv.innerHTML = '<div id="popup_topWrapper" style="width:' + (width + 65) + 'px;"></div>' +
				'<div id="popup_middleWrapper" style="min-height:' + height + 'px;_height:' + height + 'px;width:' + (width + 65) + 'px;">' +
					'<iframe id="popup_iframe" allowtransperancy="true" frameborder="0" height="' + height + '" scrolling="vertical" src="' + src + '"></iframe>' + 
				'</div>';
			if (includeButton)
			{
				newDiv.innerHTML += '<div id="popup_buttonWrapper" style="width:' + (width + 65) + 'px;">' + 
					'<input type="button" class="button" value="' + resources.getMessage("popup.close") + '" onclick="popupDivController.closePopup()" />' + 
				'</div>';
			}
			newDiv.innerHTML += '<div id="popup_bottomWrapper" style="width:' + (width + 65) + 'px;"></div>';
			popupDivController.fixPopupForIE6();
			document.body.appendChild(newDiv);
        } 
		catch(e) {}
    },    
    
    fixPopupForIE6 : function() {
        try 
		{
			// IE6 has weird bug where the popout won't appear. 
			// This fixes it, but I don't know why.
			if (IE6)
			{
				//alert("IE6");
				var oNewDiv = document.createElement("div");
				var oText = document.createTextNode("");
				oNewDiv.appendChild(oText);
				document.body.appendChild(oNewDiv);
			}
        } 
		catch(e) {}
    },    
    
    adjustPopupMiddleHeight : function(heightAdjustment) {
        try 
		{
			// Add in 50px because parent method adds this much to the height...
			var heightFinal = parseInt(popupDiv_addPerformerToFavorites._popup_middleWrapperHeight + heightAdjustment + 50);
			$("popup_middleWrapper").style.height = heightFinal + "px";
			$("popup_iframe").style.height = heightFinal + "px";
        } 
		catch(e) {}
    }
}

//object to handle tell a friend popup
var popupDiv_tellAFriend = {
    _iframeHeight : 428,
    _popup_middleWrapperHeight : 414,
    _offsetHeight4FF : 30,
    
    createDiv : function() {
        try {
            if ($("popup_wrapper") == null) {
                var body = document.body;
                var newDiv = document.createElement("div");
                newDiv.id = "popup_wrapper";                                
                newDiv.style.position = "absolute";   
                newDiv.style.display = "none";                              
                newDiv.style.left = parseInt(document.documentElement.clientWidth/2) - 400 + "px";
                newDiv.style.top = parseInt(document.documentElement.clientHeight/2) - Math.ceil(this._iframeHeight/2) + document.documentElement.scrollTop + "px";            
                newDiv.style.zIndex = 2000;                
                newDiv.innerHTML = '<div id="popup_topBtnWrapper" class="popup_topBtnWrapper" style="z-index:1" onmouseover="this.className=\'popup_topBtnWrapperHover\'" onmouseout="this.className=\'popup_topBtnWrapper\'" onclick="popupDivController.closePopup()"></div>' +
					'<div id="popup_topWrapper"></div>' +
					'<div id="popup_middleWrapper">' +
						'<iframe id="popup_iframe" src="/popupTellAFriend.do" frameborder="0" scrolling="no" allowtransperancy="true"></iframe>' + 
					'</div>' +                                    
					'<div id="popup_bottomWrapper"></div>';
                body.appendChild(newDiv);                
            }                                 
        } catch(e) {}
    },
    
    tellFriendPageOnload : function() {
        try {
            document.body.style.backgroundColor = "#fcf4e2";            
            document.getElementById("bodyWrapper").style.height = this._iframeHeight + "px";            
            //top.document.getElementById("popup_wrapper").style.display = "block";            
            
            if ($("errorsList") != null) {
                if (navigator.userAgent.toLowerCase().indexOf("firefox") != -1) {
                    top.document.getElementById("popup_iframe").style.height = this._iframeHeight + $("errorsList").offsetHeight - 22 + "px";
                    top.document.getElementById("popup_middleWrapper").style.height = this._popup_middleWrapperHeight + $("errorsList").offsetHeight - 20 + "px";
                }
                else {
                    top.document.getElementById("popup_iframe").style.height = this._iframeHeight + $("errorsList").offsetHeight + 2 + "px";
                    top.document.getElementById("popup_middleWrapper").style.height = this._popup_middleWrapperHeight + $("errorsList").offsetHeight + 16 + "px";
                }
            } 
            else {
                if (navigator.userAgent.toLowerCase().indexOf("firefox") != -1) {
                    top.document.getElementById("popup_iframe").style.height = this._iframeHeight - this._offsetHeight4FF - 2 + "px";
                    top.document.getElementById("popup_middleWrapper").style.height = this._popup_middleWrapperHeight - this._offsetHeight4FF + "px";
                }
                else {                
                    top.document.getElementById("popup_iframe").style.height = this._iframeHeight + "px";
                    top.document.getElementById("popup_middleWrapper").style.height = this._popup_middleWrapperHeight + "px";                
                } 
            }         
        } catch(e) {}
    },
    
    tellFriendSuccessPageOnload : function() {
        try {                        
            if (navigator.userAgent.toLowerCase().indexOf("firefox") != -1) {
                top.document.getElementById("popup_iframe").style.height = "120px";
                top.document.getElementById("popup_middleWrapper").style.height = "115px";
            }
            else {
                document.body.style.backgroundColor = "#fcf4e2";            
                document.getElementById("bodyWrapper").style.height = "130px";
                top.document.getElementById("popup_iframe").style.height = "130px";
                top.document.getElementById("popup_middleWrapper").style.height = "130px";                
            }
        } catch(e) {}
    }
}

//object to handle leave feedback popup
var popupDiv_leaveUserFeedback = {
    _iframeHeight : 315,
    _popup_middleWrapperHeight : 315,    
    _addToFavDivHeight : 0,
    
    createDiv : function(strUrl) {
        try 
		{
			//alert("clientWidth=" + document.documentElement.clientWidth + 
			//	", clientHeight=" + document.documentElement.clientHeight + 
			//	", scrollTop=" + document.documentElement.scrollTop);

			var width = 400;
			var overWidthCorrection = 0;
			var height = this._popup_middleWrapperHeight + 50;
			var halfWidthPopup = parseInt(width / 2);
			var halfWidthWindow = parseInt(document.documentElement.clientWidth / 2);
			var halfHeightPopup = parseInt(height / 2);
			var halfHeightWindow = parseInt(document.documentElement.clientHeight / 2);
			var scrollTop = parseInt(document.documentElement.scrollTop);
			if(SAF) scrollTop = parseInt(document.body.scrollTop);

			// Fixes "LEFT" position if window > 960px
			if (document.documentElement.clientWidth > 960)
			{
				overWidthCorrection = (document.documentElement.clientWidth - 960) / 2;
			}

			var newDiv = document.createElement("div");
			newDiv.id = "popup_wrapper";
			newDiv.style.display = "block";
			newDiv.style.position = "absolute";
			newDiv.style.left = (halfWidthWindow - halfWidthPopup - overWidthCorrection) + "px";
			newDiv.style.top = (halfHeightWindow - halfHeightPopup + scrollTop - 50) + "px";            
			newDiv.style.zIndex = 2000;               
			newDiv.innerHTML = '<div id="popup_topBtnWrapper" class="popup_topBtnWrapper" style="z-index:1" onmouseover="this.className=\'popup_topBtnWrapperHover\'" onmouseout="this.className=\'popup_topBtnWrapper\'" onclick="popupDivController.closePopup()"></div>' +
				'<div id="popup_topWrapper"></div>' +
				'<div id="popup_middleWrapper" style="min-height:' + height + 'px;_height:' + height + 'px;width:' + (width + 65) + 'px;">' +
					'<iframe id="popup_iframe" src="' + strUrl + '" frameborder="0" height="' + height + '" scrolling="no" allowtransperancy="true"></iframe>' + 
				'</div>' +                                  
				'<div id="popup_bottomWrapper"></div>';
			popupDivController.fixPopupForIE6();
			document.body.appendChild(newDiv);
        } 
		catch(e) {alert(e);}
    }
}

//object to handle add to favorite popup
var popupDiv_addPerformerToFavorites = {
    _iframeHeight : 150,
    _popup_middleWrapperHeight : 150,    
    
    createDiv : function(strUrl) {
        try 
		{
			//alert("clientWidth=" + document.documentElement.clientWidth + 
			//	", clientHeight=" + document.documentElement.clientHeight + 
			//	", scrollTop=" + document.documentElement.scrollTop);

			var width = 400;
			var overWidthCorrection = 0;
			var height = this._popup_middleWrapperHeight + 50;
			var halfWidthPopup = parseInt(width / 2);
			var halfWidthWindow = parseInt(document.documentElement.clientWidth / 2);
			var halfHeightPopup = parseInt(height / 2);
			var halfHeightWindow = parseInt(document.documentElement.clientHeight / 2);
			var scrollTop = parseInt(document.documentElement.scrollTop);
			if(SAF) scrollTop = parseInt(document.body.scrollTop);

			// Fixes "LEFT" position if window > 960px
			if (document.documentElement.clientWidth > 960)
			{
				overWidthCorrection = (document.documentElement.clientWidth - 960) / 2;
			}

			var newDiv = document.createElement("div");
			newDiv.id = "popup_wrapper";
			newDiv.style.display = "block";
			newDiv.style.position = "absolute";
			newDiv.style.left = (halfWidthWindow - halfWidthPopup - overWidthCorrection) + "px";
			newDiv.style.top = (halfHeightWindow - halfHeightPopup + scrollTop - 50) + "px";            
			newDiv.style.zIndex = 2000;               
			newDiv.innerHTML = '<div id="popup_topBtnWrapper" class="popup_topBtnWrapper" style="z-index:1" onmouseover="this.className=\'popup_topBtnWrapperHover\'" onmouseout="this.className=\'popup_topBtnWrapper\'" onclick="popupDivController.closePopup()"></div>' +
				'<div id="popup_topWrapper"></div>' +
				'<div id="popup_middleWrapper" style="min-height:' + height + 'px;_height:' + height + 'px;width:' + (width + 65) + 'px;">' +
					'<iframe id="popup_iframe" src="' + strUrl + '" frameborder="0" height="' + height + '" scrolling="no" allowtransperancy="true"></iframe>' + 
				'</div>' +                                    
				'<div id="popup_bottomWrapper"></div>';
			popupDivController.fixPopupForIE6();
			document.body.appendChild(newDiv);
        } 
		catch(e) {alert("createDiv(), e=" + e);}
    }
}

//object to handle share with friends popup
var popupDiv_shareWithFriends = 
{
	_height : (IE6 || IE7) ? 180 : 160,
	_iframeHeight : 250,
	_codeHeight : 70,//_codeHeight : (IE6 || IE7) ? 90 : 70,	
	_isExpandedEmail : false,
	_isExpandedCode : false,
    _blogLink : "",
    _embedCodeContent : "",
    _embedUrl : "",
    _embedCode : "",  
    _justSaveRec : "false",  
    _perm : "public",
    
    createDiv : function(strUrl) {
        try 
		{
			if($("bulletinSongUrlWrapper") && $("bulletinSongCodeWrapper"))
			{
				this._embedCodeContent = '<div id="embedCodeWrapper" style="display:none">' + 
					$("bulletinSongUrlWrapper").innerHTML + "<br/>" + 
					$("bulletinSongCodeWrapper").innerHTML + '</div>';
			}
			var hostName = document.location.host;
			var rid = strUrl.toQueryParams().rid;
			var sid = strUrl.toQueryParams().sid;
			var uid = strUrl.toQueryParams().uid;
			this._justSaveRec = strUrl.toQueryParams().justSaveRec;                                
			this._perm = strUrl.toQueryParams().perm; 
			
			//alert("clientWidth=" + document.documentElement.clientWidth + 
			//	", clientHeight=" + document.documentElement.clientHeight + 
			//	", scrollTop=" + document.documentElement.scrollTop);

			var width = 400;
			var overWidthCorrection = 0;
			var halfWidthPopup = parseInt(width / 2);
			var halfWidthWindow = parseInt(document.documentElement.clientWidth / 2);
			var halfHeightPopup = parseInt(this._height / 2);
			var halfHeightWindow = parseInt(document.documentElement.clientHeight / 2);
			var scrollTop = parseInt(document.documentElement.scrollTop);
			if(SAF) scrollTop = parseInt(document.body.scrollTop);
			// Fixes "LEFT" position if window > 960px
			if (document.documentElement.clientWidth > 960)
			{
				overWidthCorrection = (document.documentElement.clientWidth - 960) / 2;
			}

			var newDiv = document.createElement("div");
			newDiv.id = "popup_wrapper";
			newDiv.style.display = "block";
			newDiv.style.position = "absolute";
			newDiv.style.left = (halfWidthWindow - halfWidthPopup - overWidthCorrection) + "px";
			newDiv.style.top = (halfHeightWindow - halfHeightPopup + scrollTop - 50) + "px";        
			
			newDiv.style.zIndex = 2000;   
			newDiv.innerHTML = '<div id="popup_topBtnWrapper" class="popup_topBtnWrapper" style="z-index:1" onmouseover="this.className=\'popup_topBtnWrapperHover\'" onmouseout="this.className=\'popup_topBtnWrapper\'" onclick="popupDivController.closePopup()"></div>' +
				'<div id="popup_topWrapper"></div>' +                                    
				'<div id="popup_title">' + resources.getMessage("popup.sharewithfriend.title") + '</div>' +
				'<div id="popup_middleWrapper" style="min-height:' + this._height + 'px;_height:' + this._height + 'px;width:' + (width + 65) + 'px;">' +
					'<div id="popup_headerBg"></div>' +
					'<div id="popup_blog"><a id="popup_blogLink" href="javascript:void(0);" onclick="popupDiv_shareWithFriends.blogLinkClickFunc()"><span id="popup_blogLinkTxt">' + resources.getMessage("popup.sharewithfriend.blogBulletin") + '</span></a></div>' +
					'<div id="popup_email">' + 
						'<a id="popup_emailLink" href="javascript:void(0);" onclick="popupDiv_shareWithFriends.expandCollapseEmail();"><span id="popup_emailLinkTxt" class="popup_emailLinkTxt">' + resources.getMessage("popup.sharewithfriend.email") + '</span></a>' + 
						'<div id="popup_email_iframe" style="display:none;min-height:' + this._iframeHeight + 'px;_height:' + this._iframeHeight + 'px;">' +
							'<iframe id="popup_iframe" src="' + strUrl + '" frameborder="0" height="' + this._iframeHeight + '" scrolling="no" allowtransperancy="true"></iframe>' + 
						'</div>' +
					'</div>' +
					'<div id="popup_code">' +
						'<a id="popup_codeLink" href="javascript:void(0);" onclick="popupDiv_shareWithFriends.expandCollapseCode();"><span id="popup_codeLinkTxt" class="popup_codeLinkTxt">' + resources.getMessage("popup.sharewithfriend.embedCode") + '</span></a>' +
						this._embedCodeContent.replace(/bulletinSongUrl_txt/gi, "bulletinSongUrl2_txt").replace(/bulletinSongCode_txt/gi, "bulletinSongCode2_txt").replace(/bulletinSongUrl_inputBox/gi, "bulletinSongUrl2_inputBox").replace(/bulletinSongCode_inputBox/gi, "bulletinSongCode2_inputBox") + 
					'</div>' +
				'</div>' +
				'<div id="popup_bottomWrapper"></div>';

			popupDivController.fixPopupForIE6();
			document.body.appendChild(newDiv);
			bulletinController._fromNewlyCreatedRec = true; //this is special case when user just finish saving a new rec
							
			if (this._embedCodeContent != "")  //we only update url/code for single song/rec
			{
				document.getElementById("bulletinSongUrl2_txt").innerHTML = resources.getMessage("bulletin.recording.songUrl") + ":";
				document.getElementById("bulletinSongCode2_txt").innerHTML = resources.getMessage("bulletin.recording.songCode") + ":";
				document.getElementById("bulletinSongUrl2_inputBox").value = "http://"+hostName+"/actions/showSongProfile.do?rid="+rid+"&sid="+sid+"&uid="+uid;
				document.getElementById("bulletinSongCode2_inputBox").value = $('bulletinSongCode_inputBox').value;
			} 
        } 
		catch(e) {}
    },
    
    createDivProcessing : function() {
        try 
		{ 			
			//alert("clientWidth=" + document.documentElement.clientWidth + 
			//	", clientHeight=" + document.documentElement.clientHeight + 
			//	", scrollTop=" + document.documentElement.scrollTop);

			var width = 400;
			var overWidthCorrection = 0;
			var halfWidthPopup = parseInt(width / 2);
			var halfWidthWindow = parseInt(document.documentElement.clientWidth / 2);
			var halfHeightPopup = parseInt(this._height / 2);
			var halfHeightWindow = parseInt(document.documentElement.clientHeight / 2);
			var scrollTop = parseInt(document.documentElement.scrollTop);
			if(SAF) scrollTop = parseInt(document.body.scrollTop);

			// Fixes "LEFT" position if window > 960px
			if (document.documentElement.clientWidth > 960)
			{
				overWidthCorrection = (document.documentElement.clientWidth - 960) / 2;
			}

			var newDiv = document.createElement("div");
			newDiv.id = "popup_wrapper";
			newDiv.style.display = "block";
			newDiv.style.position = "absolute";
			newDiv.style.left = (halfWidthWindow - halfWidthPopup - overWidthCorrection) + "px";
			newDiv.style.top = (halfHeightWindow - halfHeightPopup + scrollTop - 50) + "px";            
			newDiv.style.zIndex = 2000;  
            newDiv.innerHTML = '<div id="popup_topBtnWrapper" class="popup_topBtnWrapper" style="z-index:1" onmouseover="this.className=\'popup_topBtnWrapperHover\'" onmouseout="this.className=\'popup_topBtnWrapper\'" onclick="popupDivController.closePopup()"></div>' +
				'<div id="popup_topWrapper"></div>' +                                    
				'<div id="popup_title"></div>' +
				'<div id="popup_middleWrapper" style="min-height:' + this._height + 'px;_height:' + this._height + 'px;width:' + (width + 65) + 'px;">' +                                  
					'<div id="popup_headerBg"></div>' +
					'<div id="popup_processing">' + resources.getMessage("popup.sharewithfriend.processing") + '</div>' +
				'</div>' +
				'<div id="popup_bottomWrapper"></div>';

			popupDivController.fixPopupForIE6();
			document.body.appendChild(newDiv);
        } 
		catch(e) {}
    },
    
    blogLinkClickFunc : function() {
        try 
		{
            bulletinController.submitBulletin4Song();
        } 
		catch(e) {}
    },

    expandCollapseDivs : function() {
        try 
		{
			if (IE6 || IE7)
			{
				var heightTotal = this._height;
				if (this._isExpandedEmail) { heightTotal = parseInt(heightTotal + this._iframeHeight); }
				if (this._isExpandedCode) { heightTotal = parseInt(heightTotal + this._codeHeight); }
				$("popup_middleWrapper").style.height = heightTotal + "px";
				//alert(heightTotal);
			}
        } 
		catch(e) {}
    },

    expandCollapseEmail : function() {
        try 
		{
			if ($("popup_email_iframe").style.display == "none")
			{
				$("popup_email_iframe").style.display = "block";
				this._isExpandedEmail = true;
			}
			else
			{
				$("popup_email_iframe").style.display = "none";
				this._isExpandedEmail = false;
			}

			this.expandCollapseDivs();
        } 
		catch(e) {}
    },
    
    expandCollapseCode : function() {
        try 
		{
			if ($("embedCodeWrapper").style.display == "none")
			{
				$("embedCodeWrapper").style.display = "block";
				this._isExpandedCode = true;
			}
			else
			{
				$("embedCodeWrapper").style.display = "none";
				this._isExpandedCode = false;
			}

			this.expandCollapseDivs();
        } 
		catch(e) { alert(e); }
    },
    
    sendToFriendsPageOnload : function() {
        try {            
            var err = "";
            if ($("errorsList") != null) 
			{
                $("errorsList").immediateDescendants().each(function(elem) {
                    err += elem.innerHTML.replace(/<strong>/gi, "").replace(/<\/strong>/gi, "") + "\n";                    
                });                               
                alert(err);
            }            
        } catch(e) {}
    }
}

//object to handle verify user when leaving feedback popup
var popupDiv_verifyUserFriend = {
    _iframeHeight : 203,
    _popup_middleWrapperHeight : 198,
    _offsetHeight4FF : 6,    
    
    verifyUserFriendPageOnload : function() {
        try 
		{
            //document.body.style.backgroundColor = "#fcf4e2";            
            //document.getElementById("bodyWrapper").style.height = this._iframeHeight + "px";
            //top.document.getElementById("popup_wrapper").style.display = "block";
            
            if ($("errorsList") != null) 
			{
	 		    //replace the error message from "Insert your accurate E-mail Address" to "Insert Oleg accurate E-mail Address" 
                if ($("errorsList").innerHTML.indexOf(resources.getMessage("errors.email").split("<strong>")[0]) != -1)
				{                    
                    $("errorsList").innerHTML = $("errorsList").innerHTML.replace(resources.getMessage("errors.email").split(" ")[1], document.forms[0].recName.value+"'s");
                }
				/*
                if (navigator.userAgent.toLowerCase().indexOf("firefox") != -1) {
                    top.document.getElementById("popup_iframe").style.height = this._iframeHeight + $("errorsList").offsetHeight - 6 + "px";
                    top.document.getElementById("popup_middleWrapper").style.height = this._popup_middleWrapperHeight + $("errorsList").offsetHeight + 2 + "px";
                }
                else {
                    top.document.getElementById("popup_iframe").style.height = this._iframeHeight + $("errorsList").offsetHeight + 2 + "px";
                    top.document.getElementById("popup_middleWrapper").style.height = this._popup_middleWrapperHeight + $("errorsList").offsetHeight + 10 + "px";
                }
				*/
            }
			/*
            else {
                if (navigator.userAgent.toLowerCase().indexOf("firefox") != -1) {
                    top.document.getElementById("popup_iframe").style.height = this._iframeHeight - this._offsetHeight4FF - 2 + "px";
                    top.document.getElementById("popup_middleWrapper").style.height = this._popup_middleWrapperHeight - this._offsetHeight4FF + "px";
                }
                else {                                  
                    top.document.getElementById("popup_iframe").style.height = this._iframeHeight + "px";
                    top.document.getElementById("popup_middleWrapper").style.height = this._popup_middleWrapperHeight + "px";                
                }  
            } 
			*/
        } catch(e) {}
    },
    
    userFriendInfoIncorrectPageOnload : function() {
		/*
        try {                        
            if (navigator.userAgent.toLowerCase().indexOf("firefox") != -1) {
                top.document.getElementById("popup_iframe").style.height = "120px";
                top.document.getElementById("popup_middleWrapper").style.height = "115px";
            }
            else {
                document.body.style.backgroundColor = "#fcf4e2";            
                document.getElementById("bodyWrapper").style.height = "130px";
                top.document.getElementById("popup_iframe").style.height = "130px";
                top.document.getElementById("popup_middleWrapper").style.height = "130px";                
            }
        } catch(e) {}
		*/
    }
}

/*
// Commented Out - Not Needed - jkiesel - 11/4/2008
//object to handle verify user when leaving feedback popup - authorized
var popupDiv_leaveFeedbackAuthorize = {
    leaveFeedbackAuthorizePageOnload : function() {
        try {                        
            if (navigator.userAgent.toLowerCase().indexOf("firefox") != -1) {
                top.document.getElementById("popup_iframe").style.height = "132px";
                top.document.getElementById("popup_middleWrapper").style.height = "127px";
            }
            else {
                document.body.style.backgroundColor = "#fcf4e2";                            
                top.document.getElementById("popup_iframe").style.height = "140px";
                top.document.getElementById("popup_middleWrapper").style.height = "142px";                
            }
        } catch(e) {}
    }
}
*/


//object to handle verify user when leaving feedback popup - blocked
var popupDiv_userFeedbackBlocked = {
    userFeedbackBlockedPageOnload : function() {
        try {                                    
            if (navigator.userAgent.toLowerCase().indexOf("firefox") != -1) {
                top.document.getElementById("popup_iframe").style.height = "122px";
                top.document.getElementById("popup_middleWrapper").style.height = "117px";
            }
            else {
                document.body.style.backgroundColor = "#fcf4e2";            
                document.getElementById("bodyWrapper").style.height = "130px";
                top.document.getElementById("popup_iframe").style.height = "130px";
                top.document.getElementById("popup_middleWrapper").style.height = "132px";                
            }
                        
            top.document.getElementById("popup_wrapper").style.display = "block";
        } catch(e) {}
    }
}

//bulletin object to handle bulletin functionality
/**
*business rules : blog/bulletin link is always displayed
*Song page - rate and feedback, and share with friends is never to be displayed
*Song recording page - rate and feedback, and share with friends are not to be displayed
*if its your own recording
*verify all cases prior to changing
*/
var bulletinController = {
    _hdBltn : 0, //for bulletin feature testers
    _songId : "0",
    _flashEmbededStr : "",  //for embeded flash code
    _fromNewlyCreatedRec : false,
    _isCurrentUser : false,
    
    init : function(strSongId) {
        try {            
            this._songId = strSongId;
            //cheolho:if you feel you need to comment this out.. ask me 
            //this.generateContent();
        } catch(e) {}
    },
    
    /**
    *10/11/08 -  added div on searchSongBySongId page, to not display the leave feedback and share with divs
    *probably can be removed, but not enough time to do regression testing on all other areas this code is 
    *shared.  hopefully searchSongBySongId is not used on any other page ?
    */
    generateContent : function(locallang) {
        try {                        
            if ($("bulletinWrapper") == null) {
                var newDiv = document.createElement("div");
                newDiv.id = "bulletinWrapper";
                
                
                var inrHtml = "";
                inrHtml = '<div id="bulletinLinksWrapper" class="ClearFix">' +
							'<div id="bulletinLinkBlogThis" blogLink="bulletinController.submitBulletin4Song()"><a href="javascript:bulletinController.submitBulletin4Song();">' + resources.getMessage("bulletin.songs.blogThis") + '</a></div>';
				if(!$('searchSongBySongId')){
					if(this._isCurrentUser == false){
						inrHtml +=	'<div id="bulletinLinkLeaveFeedback"></div>';
					}
					inrHtml +=	'<div id="bulletinLinkShareWithFriends"></div>';
				} 
				inrHtml	+= '</div>' +
					    '<div id="bulletinSongUrlWrapper">' +
							'<span class="bulletin_inputLbl" id="bulletinSongUrl_txt">' + resources.getMessage("bulletin.songs.songUrl") + ':</span>' +
							'<span class="bulletin_inputBox">' +
								'<input id="bulletinSongUrl_inputBox" type="text" readonly="yes" onclick="this.select()" value="" />' +
							'</span>' + 
						'</div>' +
						'<div id="bulletinSongCodeWrapper">' +
							'<span class="bulletin_inputLbl" id="bulletinSongCode_txt">' + resources.getMessage("bulletin.songs.songCode") + ':</span>' +
							'<span class="bulletin_inputBox">' +
								'<input id="bulletinSongCode_inputBox" type="text" readonly="yes" onclick="this.select()" value="" />' +
							'</span>' +
						'</div>';

				newDiv.innerHTML = inrHtml; 
				
                $("flashPlayerContainer").appendChild(newDiv);
                new Tooltip("bulletinLinkBlogThis", resources.getMessage("bulletin.songs.tooltip.bulletinLinkBlogThis"),{min_distance_x:-150});
                if(!$('searchSongBySongId')){
                	if(this._isCurrentUser == false){
                		new Tooltip("bulletinLinkLeaveFeedback", resources.getMessage("bulletin.songs.tooltip.bulletinLinkLeaveFeedback"), {min_distance_x:-150});
                	}
                	new Tooltip("bulletinLinkShareWithFriends", resources.getMessage("bulletin.songs.tooltip.bulletinLinkShareWithFriends"), {min_distance_x:-150});
                }
                new Tooltip("bulletinSongUrlWrapper", resources.getMessage("bulletin.songs.tooltip.songUrl"),{min_distance_x:-150});
                new Tooltip("bulletinSongCodeWrapper", resources.getMessage("bulletin.songs.tooltip.songCode"),{min_distance_x:-150});

				this.updateBulletinUrlCodeVal(locallang);            
				this.updateBulletinTxt4UI();
            }                
        } catch(e) {}
    },
    
    removeContent : function() {
        try {
            //this is for "blog/bulletin this" and embed code features in share with friends popup            
            if (document.getElementById("bulletinLinkBlogThis") != null) {                
                popupDiv_shareWithFriends._blogLink = document.getElementById("bulletinThisWrapper").getAttribute('blogLink');
               popupDiv_shareWithFriends._embedCodeContent = '<div id="embedCodeWrapper" style="display:none">' + document.getElementById("bulletinSongUrlWrapper").innerHTML + "<br/>" + document.getElementById("bulletinSongCodeWrapper").innerHTML + '</div>';
            }
            else if (document.getElementById("bulletinThisWrapper_recordings") != null) {
                popupDiv_shareWithFriends._blogLink = document.getElementById("bulletinLinkBlogThis").getAttribute('blogLink');
            }
                       
            if ($("bulletinWrapper") != null)
                $("bulletinWrapper").remove(); 
        } catch(e) {}
    },

    addContent : function() {
        try {
            //this is for "blog/bulletin this" and embed code features in share with friends popup
            //Cheolho: changed function, to not effect whatever the f* the other function was doing.            
            if (document.getElementById("bulletinLinkBlogThis") != null) {
                popupDiv_shareWithFriends._embedCodeContent = 
	                '<div id="embedCodeWrapper" style="display:none">' + 
	                $("bulletinSongUrlWrapper").innerHTML + "<br/>" + 
	                $("bulletinSongCodeWrapper").innerHTML + 
	                '</div>';
	                
            }
            var sharlinks = document.createElement("div");
            sharlinks.appendChild($("bulletinSongUrlWrapper"));
            $('popup_codeLinkTxt').appendChild(sharlinks);
        } catch(e) {alert(e);}
    },
    
    updateBulletinUrlCodeVal : function(locallang) { //this is only be used by 1 song or 1 rec
    	var lang="en";
    	if (locallang=="JP")lang="ja";
    	if (locallang=="US")lang="en";
    	if (locallang=="CH")lang="zh-CN";
    	
        try {
            if ($("songId_"+this._songId) != null) {
                var songUrl = $("songId_"+this._songId).getAttribute("href");
            }
            else if (location.href.toLowerCase().indexOf("searchsongbysongid.do") != -1 || //this is for song profile
                        location.href.toLowerCase().indexOf("/music/") != -1) { //this is for song profile
                var songUrl = location.href;
            }
            //on edit song properties the Recording URL input box was getting edit=1 to the string , needs to be removed
            if(songUrl.indexOf("edit=1") > -1){
            	var conArr = songUrl.split("edit=1&");
            	songUrl = conArr[0] + conArr[1];
            } 
            $("bulletinSongUrl_inputBox").value = songUrl;
            popupDiv_shareWithFriends._embedUrl = songUrl;
            
            var hostName = document.location.host;
            if (location.href.toLowerCase().indexOf("mywebpage.do") != -1   //for homepage
                    || location.href.toLowerCase().indexOf("userrecordings.do") != -1   //for my recordings page
                    || location.href.toLowerCase().indexOf("showuserprofile.do") != -1  //for user profile page
                    || location.href.toLowerCase().indexOf("showsongprofile.do") != -1  //for song profile page
                    || location.href.toLowerCase().indexOf("showsong.do") != -1  //for song profile page
                    || location.href.toLowerCase().indexOf("showsongsentbyemail.do") != -1) {  //for link from share a friend's email                    
                
                //for single rec
                var rid = $("songId_"+bulletinController._songId).getAttribute("rid");
                var uid = $("songId_"+bulletinController._songId).getAttribute("uid");
                var sid = $("songId_"+bulletinController._songId).getAttribute("sid");
                var avType = $("songId_"+bulletinController._songId).getAttribute("avType");
                var imageUrl = $("songId_"+bulletinController._songId).getAttribute("imageUrl");
                var vidUrl = $("songId_"+bulletinController._songId).getAttribute("vidUrl");
                var duration = $("songId_"+bulletinController._songId).getAttribute("vidDuration");
                if(avType == 2){
                	bulletinController._flashEmbededStr = "<object type='application/x-shockwave-flash' allowScriptAccess='always' allowNetworking='all' allowFullScreen='true' height='264' width='320' data='"+webServerAddress+"/player/KMiniPlayer.swf?lang="+lang+"'><param name='allowScriptAccess' value='always' /><param name='allowNetworking' value='all' /><param name='allowFullScreen' value='true' /><param name='quality' value='high' /> <param name='wmode' value='transparent' /> <param name='flashvars' value='info="+imageUrl+"~"+duration+"~"+vidUrl+"~false~"+uid+"~"+sid+"~"+rid+"~http://"+hostName+"/actions/showSongProfile.do?' /><param name='movie' value='"+webServerAddress+"/player/KMiniPlayer.swf?lang="+lang+"' /></object>";
                }else{
                    bulletinController._flashEmbededStr = "<object type='application/x-shockwave-flash' allowScriptAccess='always' allowNetworking='all' allowFullScreen='true' height='102' width='474' data='http://"+hostName+"/OneRecordingList.do?uid="+uid+"&rid="+rid+"&globalDomain="+hostName+"&lang="+lang+"'><param name='allowScriptAccess' value='always' /><param name='allowNetworking' value='all' /><param name='allowFullScreen' value='true' /><param name='movie' value='http://"+hostName+"/OneRecordingList.do?uid="+uid+"&rid="+rid+"&globalDomain="+hostName+"&lang="+lang+"' /><param name='quality' value='high' /><param name='wmode' value='transparent' /></object>";
                }
            }
            else {  //for single song                
                if (bulletinController._songId == "0")
                    var songId = $("songId4Bulletin").innerHTML;
                else
                    var songId = bulletinController._songId;
                    
                bulletinController._flashEmbededStr = "<object type='application/x-shockwave-flash' allowScriptAccess='always' allowNetworking='all' allowFullScreen='true' height='102' width='474' data='http://"+hostName+"/OneSongList.do?sid="+songId+"&globalDomain="+hostName+"&lang="+lang+"'><param name='allowScriptAccess' value='always' /><param name='allowNetworking' value='all' /><param name='allowFullScreen' value='true' /><param name='movie' value='http://"+hostName+"/OneSongList.do?sid="+songId+"&globalDomain="+hostName+"&lang="+lang+"' /><param name='quality' value='high' /><param name='wmode' value='transparent' /></object>";
            }
            $("bulletinSongCode_inputBox").value = bulletinController._flashEmbededStr;
            popupDiv_shareWithFriends._embedCode = bulletinController._flashEmbededStr;
        } catch(e) {}
    },
    
    updateBulletinTxt4UI : function() {
        try {
            if (location.href.toLowerCase().indexOf("mywebpage.do") != -1   //for homepage
                    || location.href.toLowerCase().indexOf("userrecordings.do") != -1   //for my recordings page
                    || location.href.toLowerCase().indexOf("showuserprofile.do") != -1  //for user profile page
                    || location.href.toLowerCase().indexOf("showsongsentbyemail.do") != -1  //for link from share a friend's email
                    || location.href.toLowerCase().indexOf("showsongprofile.do") != -1  //for user's recording song profile page
                    || location.href.toLowerCase().indexOf("showsong.do") != -1  //for user's recording song profile page
                    || location.href.toLowerCase().indexOf("/recordings/") != -1) { //for all pages under recordings tab
                $("bulletinSongUrl_txt").innerHTML = resources.getMessage("bulletin.recording.songUrl") + ":";
                $("bulletinSongCode_txt").innerHTML = resources.getMessage("bulletin.recording.songCode") + ":";
            }
        } catch(e) {}
    },
            
    generateBulletinForm4MyRecs : function(strUsername, strUserId, localLang) {    //this is for multiple recs
        try {
        	var lang="en"
        	if (localLang=='JP'){
        		lang="ja";
        	}
            var hostName = document.location.host;
            bulletinController._flashEmbededStr = "<object type='application/x-shockwave-flash' allowScriptAccess='always' allowNetworking='all' allowFullScreen='true' height='370' width='500' data='http://"+hostName+"/MyRecordingsList.do?uid="+strUserId+"&globalDomain="+hostName+"&lang="+lang+"'>" +
					"<param name='allowScriptAccess' value='always' />" +
					"<param name='allowNetworking' value='all' />" +
					"<param name='allowFullScreen' value='true' />" +
					"<param name='movie' value='http://"+hostName+"/MyRecordingsList.do?uid="+strUserId+"&globalDomain="+hostName+"&lang="+lang+"' />" +
					"<param name='quality' value='high' /><param name='wmode' value='transparent' />" +
				"</object>";
            var title = resources.getMessage("bulletin.recordings.checkout").replace(/!!my!!/gi, strUsername + "'s");
			var body = resources.getMessage("bulletin.recordings.body").replace(/!!my!!/gi, strUsername + "'s"); 
            
			if (strUsername == "my") 
			{
                title = resources.getMessage("bulletin.recordings.checkout").replace(/!!my!!/gi, strUsername);
                body = resources.getMessage("bulletin.recordings.body").replace(/!!my!!/gi, strUsername);                        
            }
            
			//cheolho: hack because somewhere this var gets overwritten, so set it back prior to blog link
			bulletinController._flashEmbededStr = $('bulletinSongCode_inputBox').value;
            var postToUrl = 'http://www.myspace.com/Modules/PostTo/Pages/?' + 't=' + encodeURIComponent(title) +
				'&c=' + encodeURIComponent(body+"<br/><br/>"+bulletinController._flashEmbededStr) + '&u=' + '&l=1';
            window.open(postToUrl);
                                
        } 
		catch(e) {}
    },
    
    generateBulletinForm4Rec : function() {
        try {            
            if (($("songId_"+bulletinController._songId) != null && $("songId_"+bulletinController._songId).getAttribute("perm") == "private") ||
                    popupDiv_shareWithFriends._perm == "private") {
                alert(resources.getMessage("bulletin.recordings.private.err"));                                                        
            }
            else {
                //alert(popupDiv_shareWithFriends._justSaveRec);
                if (popupDiv_shareWithFriends._justSaveRec == "true") {
                    var title = resources.getMessage("bulletin.recording.checkout").replace(/!!my!!/gi, "my");
                    var body = resources.getMessage("bulletin.recording.body").replace(/!!my!!/gi, "my");  
                }
                else if ($("songId_"+bulletinController._songId) != null && $("songId_"+bulletinController._songId).getAttribute("isMyRecording") == "false") {                        
                    var title = resources.getMessage("bulletin.recording.checkout").replace(/!!my!!/gi, $("songId_"+bulletinController._songId).getAttribute("userFName") + "'s");
                    var body = resources.getMessage("bulletin.recording.body").replace(/!!my!!/gi, $("songId_"+bulletinController._songId).getAttribute("userFName") + "'s");                                        
                }
                else {
                    var title = resources.getMessage("bulletin.recording.checkout").replace(/!!my!!/gi, "my");
                    var body = resources.getMessage("bulletin.recording.body").replace(/!!my!!/gi, "my");  
                }
                //cheolho: hack because somewhere this var gets overwritten, so set it back prior to blog link
				bulletinController._flashEmbededStr = $('bulletinSongCode_inputBox').value;
                var postToUrl = 'http://www.myspace.com/Modules/PostTo/Pages/?' + 't=' + encodeURIComponent(title) +
                                '&c=' + encodeURIComponent(body+"<br/><br/>"+bulletinController._flashEmbededStr) + '&u=' + '&l=1';
                window.open(postToUrl);     
            }
        } catch(e) {}
    },
    
    generateBulletinForm4Song : function() {
        try {                                    
            var title = resources.getMessage("bulletin.songs.checkout");
            var body = resources.getMessage("bulletin.songs.body");
            
            var postToUrl = 'http://www.myspace.com/Modules/PostTo/Pages/?' + 't=' + encodeURIComponent(title) +
                            '&c=' + encodeURIComponent(body+"<br/><br/>"+bulletinController._flashEmbededStr) + '&u=' + '&l=1';
            window.open(postToUrl);  
        } catch(e) {}
    },
    
    submitBulletin4MyRecs : function(strUsername, strUserId, LocalLang) { //if strUsername != "" then this is someone else's recordings
        try {
            this.generateBulletinForm4MyRecs(strUsername, strUserId, LocalLang);
        } catch(e) {}
    },

    generateBulletinLinks : function(suid, perm, uname, rid, uid, sid) {
    	try 
		{
			// Leave Feedback...
			if($("bulletinLinkLeaveFeedback")){
				var linkFb = document.createElement('a');
	    		linkFb.href = uid != '' ? "javascript:playerController.showFeedbackWindow();" : "javascript:joinSite();";
				linkFb.innerHTML = resources.getMessage("bulletin.songs.leaveFeedback");
		    	$("bulletinLinkLeaveFeedback").appendChild(linkFb);
	    	}
			
			// Share With Friends...
			var linkSf = document.createElement('a');
			var jsParams = sid + "," + rid + ",null,'" + ((suid == uid) ? "true" : "false") + "','" + uname + "','" + suid + "'," + perm + ",''";
    		linkSf.href = "javascript:openSendToEmail(" + jsParams + ");";
			linkSf.innerHTML = resources.getMessage("bulletin.songs.shareWithFriends");
	    	$("bulletinLinkShareWithFriends").appendChild(linkSf);

    	} catch(e) {}    	
    },
    
    submitBulletin4Song : function() {
        try {            
            if (location.href.toLowerCase().indexOf("mywebpage.do") != -1   //for homepage
                    || location.href.toLowerCase().indexOf("userrecordings.do") != -1   //for my recordings page
                    || location.href.toLowerCase().indexOf("showuserprofile.do") != -1  //for user profile page
                    || location.href.toLowerCase().indexOf("showsongprofile.do") != -1  //for song profile page
                    || location.href.toLowerCase().indexOf("showsong.do") != -1  //for song profile page
                    || location.href.toLowerCase().indexOf("showsongsentbyemail.do") != -1  //for link from share a friend's email  
                    || bulletinController._fromNewlyCreatedRec) { //this is special case when user just finish saving a rec 
                this.generateBulletinForm4Rec();                    
            }
            else {                    
                this.generateBulletinForm4Song();
            }                                
        } catch(e) {}
    }
}

//object to handle status message popup
var popupDiv_statusMsg = {  
    _posX : 0,
    _posY : 0,
        
    init : function(strMsg, numHeight, isCentered) {
        try 
		{
			if(getAVControl())
			{
				getAVControl().style.height="1px";
				getAVControl().style.width="1px";
			}
            popupDiv_statusMsg.createDiv(strMsg, numHeight, isCentered);
        } 
		catch(e) {}
    },
    
    createDiv : function(strMsg, numHeight, isCentered) {
        try 
		{
			if ($("popup_wrapper")) { $("popup_wrapper").remove(); }
				
			//alert("clientWidth=" + document.documentElement.clientWidth + 
			//	", clientHeight=" + document.documentElement.clientHeight + 
			//	", scrollTop=" + document.documentElement.scrollTop);

			var width = 400;
			var overWidthCorrection = 0;
			var halfWidthPopup = parseInt(width / 2);
			var halfWidthWindow = parseInt(document.documentElement.clientWidth / 2);
			var halfHeightPopup = parseInt(numHeight / 2);
			var halfHeightWindow = parseInt(document.documentElement.clientHeight / 2);
			var scrollTop = parseInt(document.documentElement.scrollTop);
			if(SAF) scrollTop = parseInt(document.body.scrollTop);

			// Fixes "LEFT" position if window > 960px
			if (document.documentElement.clientWidth > 960)
			{
				overWidthCorrection = (document.documentElement.clientWidth - 960) / 2;
			}

			var newDiv = document.createElement("div");
			newDiv.id = "popup_wrapper";
			newDiv.style.display = "block";
			newDiv.style.position = "absolute";
			newDiv.style.left = (halfWidthWindow - halfWidthPopup - overWidthCorrection) + "px";
			newDiv.style.top = (halfHeightWindow - halfHeightPopup + scrollTop - 50) + "px";
			if (!isCentered) { newDiv.style.top = popupDiv_statusMsg._posY + "px"; }
			newDiv.style.zIndex = 2000; 
            newDiv.innerHTML = '<div id="popup_topWrapper"></div>' +
				'<div id="popup_middleWrapper" style="height:' + numHeight + 'px">' + strMsg + '</div>' +
				'<div id="popup_bottomWrapper"></div>';

			popupDivController.fixPopupForIE6();
			document.body.appendChild(newDiv);

            Effect.Fade("popup_wrapper", {delay:0.8, duration:0.4, 
            afterFinish:function()
			{
				if(getAVControl() && pluginController.getCaptureMode()==1)
				{
					getAVControl().style.width="227px";
					getAVControl().style.height="170px";
				}
            }});          
        } catch(e) {}
    }
}

//object to handle captcha functionality
var captchaController = {
    createCoverLayer : function() {
        try {
            if ($("captchaCoverDiv") != null)
				$("captchaCoverDiv").remove();
				
			var newDiv = document.createElement("div");
			newDiv.id = "captchaCoverDiv";                                
			newDiv.style.position = "absolute";                			
			newDiv.style.top = "0px";
			newDiv.style.left = "0px";
			newDiv.style.width = "100%"; 
			newDiv.style.height = document.documentElement.clientHeight + "px";
			document.body.appendChild(newDiv); 
			$("captchaCoverDiv").setStyle({backgroundColor: '#fcf4e2', 'z-index': 1000, opacity: 0});  			
        } catch(e) {}
    },
    
    createDimmerLayer : function() {
        try {
            if ($("captchaDimmerDiv") != null)
				$("captchaDimmerDiv").remove();
				
			var newDiv = document.createElement("div");
			newDiv.id = "captchaDimmerDiv";                                
			newDiv.style.position = "absolute";                
			newDiv.style.top = Math.ceil(top.document.getElementById("popup_wrapper").offsetHeight/2) - 117 + "px";             
			newDiv.style.left = "49px";                								
			newDiv.style.width = "350px"; 
			newDiv.style.height = "208px";
			document.body.appendChild(newDiv); 			
			$("captchaDimmerDiv").setStyle({backgroundColor: '#000', 'z-index': 1000, opacity: 0.7});  
        } catch(e) {}
    },            
       
    createDimmerLayerWithErr : function() {
        try {
            if ($("captchaDimmerDiv") != null)
				$("captchaDimmerDiv").remove();
				
			var newDiv = document.createElement("div");
			newDiv.id = "captchaDimmerDiv";                                
			newDiv.style.position = "absolute";                
			newDiv.style.top = Math.ceil(top.document.getElementById("popup_wrapper").offsetHeight/2) - 117 + "px";             
			newDiv.style.left = "49px";                								
			newDiv.style.width = "350px"; 
			newDiv.style.height = "208px";
			document.body.appendChild(newDiv); 			
			$("captchaDimmerDiv").setStyle({backgroundColor: '#000', 'z-index': 1000, opacity: 0.7});  
        } catch(e) {}
    },
    
    createCaptchaContent : function() {
        try {                        
            if ($("captchaContentDiv") != null)
				$("captchaContentDiv").remove();												
				
			var newDiv = document.createElement("div");
			newDiv.id = "captchaContentDiv";          
			newDiv.style.top = Math.ceil(top.document.getElementById("popup_wrapper").offsetHeight/2) - 108 + "px";
			newDiv.style.left = "58px";                            
			newDiv.innerHTML = '<span style="font-weight:bold">' + resources.getMessage("captcha.info1") + '</span>' + 
								'<img value="" id="captchaVerifyImg" src="' + resources.getMessage("captcha.imageUrl") + '" style="margin: 6px 0px 0px 10px"/>' +
								'<br /><input id="captchaVerifyTxt" type="text" value="" name="captcha" style="width:294px;margin: 2px 0px 0px 10px" onkeydown="captchaController.captureKeyDown(event)" />' +
								'<span onclick="captchaController.captchaRefresh();" style="float:left;cursor:pointer;text-decoration:underline;color:#001BFF;margin: 8px 0px 0px 0px">' + resources.getMessage("captcha.info4") + '</span>' +
								'<span style="float:right"><input id="captchaVerifySubmitBtn" type="button" value="' + resources.getMessage("captcha.submit") + '" onclick="captchaController.captchaSubmit();" style="font-size:14px;margin: 2px 0px 0px 0px" /><input type="button" style="margin: 2px 0px 0px; font-size: 14px;" onclick="captchaController.captchaClose();" value="' + resources.getMessage("captcha.close") + '" id="captchaVerifyCloseBtn"/></span>';
			document.body.appendChild(newDiv);
			$("captchaContentDiv").setStyle({position: 'absolute', width: '320px', height: '178px',
										padding: '5px', border: 'solid 1px #fff', backgroundColor: '#DFDFDF', 'z-index': 2000});
        } catch(e) {}
    },       
    
    createCaptchaContentWithErr : function() {
        try {    
            if ($("captchaContentDiv") != null)
				$("captchaContentDiv").remove();												
				
			var newDiv = document.createElement("div");
			newDiv.id = "captchaContentDiv";          
			newDiv.style.top = Math.ceil(top.document.getElementById("popup_wrapper").offsetHeight/2) - 108 + "px";
			newDiv.style.left = "58px";                            
			newDiv.innerHTML = '<span id="captchaErrMsg1" style="position:absolute;font-weight:bold;color:#c00;display:block">' + resources.getMessage("captcha.info3") + '</span>' + 
								'<span id="captchaErrMsg2" style="display:none;position:absolute;font-weight:bold">' + resources.getMessage("captcha.info2") + '</span>' + 
								'<img value="" id="captchaVerifyImg" src="' + resources.getMessage("captcha.imageUrl") + '" style="margin: 18px 0px 0px 10px"/>' +
								'<br /><input id="captchaVerifyTxt" type="text" value="" name="captcha" style="width:294px;margin: 2px 0px 0px 10px" onkeydown="captchaController.captureKeyDown(event)" />' +
								'<span onclick="captchaController.captchaRefresh();" style="float:left;cursor:pointer;text-decoration:underline;color:#001BFF;margin: 8px 0px 0px 0px">' + resources.getMessage("captcha.info4") + '</span>' +
								'<span style="float:right"><input id="captchaVerifySubmitBtn" type="button" value="' + resources.getMessage("captcha.submit") + '" onclick="captchaController.captchaSubmit();" style="font-size:14px;margin: 2px 0px 0px 0px" /><input type="button" style="margin: 2px 0px 0px; font-size: 14px;" onclick="captchaController.captchaClose();" value="' + resources.getMessage("captcha.close") + '" id="captchaVerifyCloseBtn"/></span>';
			document.body.appendChild(newDiv);
			$("captchaContentDiv").setStyle({position: 'absolute', width: '320px', height: '178px',
										padding: '5px', border: 'solid 1px #fff', backgroundColor: '#DFDFDF', 'z-index': 2000});   												        
										
		    Effect.Fade("captchaErrMsg1", {delay:2.0, duration:0.2,
		                            afterFinish : function() {		                                
		                                Effect.Appear("captchaErrMsg2", {duration:0.5});
		                            }});
        } catch(e) {}
    },
    
    captchaInit : function() {
        try {
            $("submitButton").disabled = true;
            this.createCoverLayer();
            this.createDimmerLayer();
            this.createCaptchaContent();
            $("captchaVerifyTxt").focus();
        } catch(e) {}
    },
    
    captchaInitWithErr : function() {
        try {
            $("submitButton").disabled = true;
            this.createCoverLayer();
            this.createDimmerLayerWithErr();
            this.createCaptchaContentWithErr();
            $("captchaVerifyTxt").focus();
        } catch(e) {}
    },
    
    captchaInit4FanCental : function(strUid) {
        try {        
            $("captchaVerifySubmitBtn_"+strUid).style.display = "";                
            $("captchaVerifySubmitBtn4EditApplause_"+strUid).style.display = "none";                
            $("shoutout_"+strUid).disabled = true;
            if ($("email_"+strUid) != null)
                $("email_"+strUid).disabled = true;
            $("captchaDimmerDiv_"+strUid).style.display = "block";
            $("captchaContentDiv_"+strUid).style.display = "block";
            this.captchaRefresh4FanCental(strUid);           
        } catch(e) {}
    },
    
    captchaInit4EditApplause : function(strUid) {
        try {          
            $("captchaVerifySubmitBtn_"+strUid).style.display = "none";                
            $("captchaVerifySubmitBtn4EditApplause_"+strUid).style.display = "";                  
            $("shoutout_"+strUid).disabled = true;
            $("captchaDimmerDiv_"+strUid).style.display = "block";
            $("captchaContentDiv_"+strUid).style.display = "block";
            this.captchaRefresh4FanCental(strUid);           
        } catch(e) {}
    },
    
    captchaInit4FeedbackCental : function(strUid) {
        try {                    
            $("feedback_"+strUid).disabled = true;
            $("captchaDimmerDiv_"+strUid).style.display = "block";
            $("captchaContentDiv_"+strUid).style.display = "block";
            this.captchaRefresh4FeedbackCental(strUid);           
        } catch(e) {}
    },
    
    captchaRefresh : function() {
        try {
            $("captchaVerifyImg").src = $("captchaVerifyImg").src + "?" + Math.random();
            $("captchaVerifyTxt").value = "";
            $("captchaVerifyTxt").focus();
        } catch(e) {}
    },
    
    captchaRefresh4FanCental : function(strUid) {
        try {
            $("captchaVerifyImg_"+strUid).src = resources.getMessage("captcha.imageUrl") + "?" + Math.random();
            $("captchaVerifyTxt_"+strUid).value = "";
            $("captchaVerifyTxt_"+strUid).focus();
        } catch(e) {}
    },
    
    captchaRefresh4FeedbackCental : function(strUid) {
        try {
            $("captchaVerifyImg_"+strUid).src = resources.getMessage("captcha.imageUrl") + "?" + Math.random();
            $("captchaVerifyTxt_"+strUid).value = "";
            $("captchaVerifyTxt_"+strUid).focus();
        } catch(e) {}
    },
    
    captchaSubmit : function() {
        try {
            $("captcha").value = $("captchaVerifyTxt").value;            
            new Effect.Fade("captchaContentDiv", {duration: 0.2,
                                afterFinish:function() {
                                    document.forms[0].submit()
                                }
                            });
            new Effect.Fade("captchaDimmerDiv", {duration: 0.2});
        } catch(e) {}
    },
    
    captchaSubmit4FanCental : function(_uid,_msg,_safety,_applauseperm) {
        try {
            if(_applauseperm == 1) {
			    centralInState = WAITING_BECOME_A_FAN;
		    } else {
			    centralInState = WAITING_BECOME_A_FAN_NEED_AUTH;
		    }
    		
		    var email = "";
		    if (document.getElementById("shoutoutForm_" + _uid + "_form").email) {
			    email = document.getElementById("shoutoutForm_" + _uid + "_form").email.value;
		    }
		                     
            new Effect.Fade("captchaContentDiv_"+_uid, {duration: 0.2,
                                afterFinish:function() {
                                    //openFeed("",{address:"/actions/becomeAFan.do",parameters:new Array(["uids",_uid],["shoutout",_msg],["email",email],["safetyStatus",_safety],["captcha",$("captchaVerifyTxt_"+_uid).value])},FEEDLOADER_DO_NOTHING,FEEDLOADER_METHOD_POST);
                                    new Ajax.Request("/actions/becomeAFan.do", {
                                                        parameters : {uids:_uid, shoutout:_msg, email:email, safetyStatus:_safety, captcha:$("captchaVerifyTxt_"+_uid).value},
                                                        onSuccess : function(resp) {                                                            
                                                            //alert(resp.responseText.replace(/\<html\>\<body\>\<script\>/gi, "").replace(/\<\/script\>\<\/body\>\<\/html\>/gi, "").strip());
                                                            eval(resp.responseText.replace(/\<html\>\<body\>\<script\>/gi, "").replace(/\<\/script\>\<\/body\>\<\/html\>/gi, "").strip());                                                            
                                                        }
                                                    });
                                }
                            });
            new Effect.Fade("captchaDimmerDiv_"+_uid, {duration: 0.2});
        } catch(e) {}
    },
    
    captchaSubmit4EditApplause : function(_uid,_msg,_safety,_applauseperm) {
        try {
            if(_applauseperm == 1) {
			    centralInState = WAITING_EDIT_SHOUTOUT;
		    } else {
			    centralInState = WAITING_EDIT_SHOUTOUT_NEED_AUTH;
		    }
    		
		    var email = "";
		    if (document.getElementById("shoutoutForm_" + _uid + "_form").email) {
			    email = document.getElementById("shoutoutForm_" + _uid + "_form").email.value;
		    }
		                     
            new Effect.Fade("captchaContentDiv_"+_uid, {duration: 0.2,
                                afterFinish:function() {
                                    //openFeed("",{address:"/actions/editShoutout.do",parameters:new Array(["uids",_uid],["shoutout",_msg],["email",email],["safetyStatus",_safety])} ,FEEDLOADER_DO_NOTHING,FEEDLOADER_METHOD_POST);
                                    new Ajax.Request("/actions/editShoutout.do", {
                                                        parameters : {uids:_uid, shoutout:_msg, email:email, safetyStatus:_safety, captcha:$("captchaVerifyTxt_"+_uid).value},
                                                        onSuccess : function(resp) {                                                            
                                                            //alert(resp.responseText.replace(/\<html\>\<body\>\<script\>/gi, "").replace(/\<\/script\>\<\/body\>\<\/html\>/gi, "").strip());
                                                            eval(resp.responseText.replace(/\<html\>\<body\>\<script\>/gi, "").replace(/\<\/script\>\<\/body\>\<\/html\>/gi, "").strip());                                                            
                                                            //$("bottomMenuCopyrights").style.top = top.document.documentElement.scrollHeight + 5 + "px";
                                                            //if (BrowserDetect.browser == "Safari")
                                                            //    $("bottomMenuCopyrights").style.top = top.document.body.scrollHeight + 5 + "px";            
                                                            //else
                                                            //    $("bottomMenuCopyrights").style.top = top.document.documentElement.scrollHeight + 5 + "px";   
                                                        }
                                                    });
                                }
                            });
            new Effect.Fade("captchaDimmerDiv_"+_uid, {duration: 0.2});
        } catch(e) {}
    },
    
    captchaSubmit4FeedbackCental : function(_uid,_frmname,_resplace) {
        try {
            var frm = document[_frmname];
			if(!frm) return;

			var hrf = "/actions/iframeLeaveFeedbackToUser.do";
		                     
            new Effect.Fade("captchaContentDiv_"+_uid, {duration: 0.2,
                                afterFinish:function() {
                                    //openFeed(_resplace,hrf,FEEDLOADER_REPLACE_CONTENT);
                                    new Ajax.Request(hrf, {
                  					method : 'post',
                  					parameters : {captcha:$("captchaVerifyTxt_"+_uid).value, pid:frm.pid.value, uid:frm.uid.value, ols:frm.ols.value, central:'1', fid:frm.fid.value, RECORDID:frm.RECORDID.value, SONGID:frm.SONGID.value, feedback:frm.feedback.value},                                                        
                                      onSuccess : function(resp) {                                                            
                                          captchaController.captchaClose4FeedbackCental(_uid);
                                          if (resp.responseText.strip() == "success") {
                                              closeLeave(_uid);
                                          }
                                          else {
                                              alert(resp.responseText.strip());
                                              captchaController.captchaInit4FeedbackCental(_uid);
                                          }
                                          //eval(resp.responseText.replace(/\<html\>\<body\>\<script\>/gi, "").replace(/\<\/script\>\<\/body\>\<\/html\>/gi, "").strip());                                                            
                                      }
                                  });
                                }
                            });
            new Effect.Fade("captchaDimmerDiv_"+_uid, {duration: 0.2});
        } catch(e) {}
    },
    
    captchaClose : function() {
        try {            	
            if ($("captchaCoverDiv") != null)
				$("captchaCoverDiv").remove();	
			$("submitButton").disabled = false;            
            new Effect.Fade("captchaContentDiv", {duration: 0.2});
            new Effect.Fade("captchaDimmerDiv", {duration: 0.2});            
        } catch(e) {}
    },
    
    captchaClose4FanCental : function(strUid) {
        try {            	
            $("shoutout_"+strUid).disabled = false;			            
            $("shoutout_"+strUid).focus();
            if ($("email_"+strUid) != null)
                $("email_"+strUid).disabled = false;
            $("captchaDimmerDiv_"+strUid).style.display = "none";
            $("captchaContentDiv_"+strUid).style.display = "none";         
        } catch(e) {}
    },
    
    captchaClose4FeedbackCental : function(strUid) {
        try {            	
            $("feedback_"+strUid).disabled = false;			            
            $("feedback_"+strUid).focus();
            $("captchaDimmerDiv_"+strUid).style.display = "none";
            $("captchaContentDiv_"+strUid).style.display = "none";         
        } catch(e) {}
    },
    
    captureKeyDown : function(e) {
        try {
            e = !e ? window.event : e;            
            if (e.keyCode == 13) {      //Enter key is pressed                
                $("captchaVerifySubmitBtn").click();                
            }
        } catch(e) {}
    },
    
    captureKeyDown4FavPage : function(e, strId) {
        try {
            e = !e ? window.event : e;            
            if (e.keyCode == 13) {      //Enter key is pressed
                if ($("captchaVerifySubmitBtn_"+strId).style.display == "none") {
                    $("captchaVerifySubmitBtn4EditApplause_"+strId).click();
                }
                else if ($("captchaVerifySubmitBtn4EditApplause_"+strId).style.display == "none") {
                    $("captchaVerifySubmitBtn_"+strId).click();
                }
            }
        } catch(e) {}
    },
    
    captureKeyDown4FeedbackPage : function(e, strId) {
        try {
            e = !e ? window.event : e;            
            if (e.keyCode == 13) {      //Enter key is pressed                
                $("captchaVerifySubmitBtn_"+strId).click();                
            }
        } catch(e) {}
    }
}

var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};

var Utf8 = {

    // public method for url encoding
    encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // public method for url decoding
    decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;
        
        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }

}

//1. at least two recommendation boxes need to be on page
//2. this implementation is not thread safe, in order to ensure boxes
//load correctly b=? box number needs to be appended to each url
//so referring box that called the url loads correctly
var recom = {    
    _idx : "1",
    _onPageLoad : true,
    _onPageLoadIdx : "4",
    _onPageLoadLastIdx : "4",
    _dataObj : [{type:'',url:''}, {type:'',url:''}, {type:'',url:''}, {type:'',url:''}, {type:'',url:''}],
    _order : ["1", "2"],
    _onPageLoadBoxTracker : ["1", "2"],
    
    init : function(idx) {
        try {
            this._idx = idx;
            if (this._dataObj[idx-1].type == "recording") {
                this.getRecordingData();                 
            }
            else if (this._dataObj[idx-1].type == "song") {
                this.getSongData();
            }
            else if (this._dataObj[idx-1].type == "artist") {
                this.getArtistData();
            }
        } catch(e) {}
    },
    
    initDataObj : function(dataArr) {
        try {
            for (var i = 0; i < dataArr.length; i++) {
                this.setDataObj(i, dataArr[i].type, dataArr[i].url);
            }            
        } catch(e) {}
    },
    
    setDataObj : function(idx, type, url) {
        try {
            recom._dataObj[idx].type = type;
            recom._dataObj[idx].url = url;
        } catch(e) {}
    },
    
    //don't use this for page load - TODO:rename
    //Use onPageload with two arrays as parameters.
    onPageLoad : function(onPageLoadIdx, onPageLoadLastIdx, dataArr) {
        try {            
            recom._onPageLoadIdx = onPageLoadIdx;
            recom._onPageLoadLastIdx = onPageLoadLastIdx;
            recom.initDataObj(dataArr);
            recom.init(onPageLoadIdx);
        } catch(e) {}
    },
    
    onPageLoad : function(orderArr, dataArr) {
        try {
            recom._onPageLoadIdx = orderArr[0];
            onPageLoadIdx = orderArr[0];
            recom._onPageLoadLastIdx = orderArr[1];
            recom._order = orderArr;
            recom.initDataObj(dataArr);
            recom.init(onPageLoadIdx);
        } catch(e) {}
    },
    
    showHide : function() {
        try {
            if ($("recomBoxHeaderLnk"+this._idx).getAttribute("selected") == null || $("recomBoxHeaderLnk"+this._idx).getAttribute("selected") == "0") {
                $("recomBoxHeader"+this._idx).className = "recomBoxHeaderSelected";
                $("recomBoxHeaderLnk"+this._idx).className = "recomBoxHeaderLnkSelected";                                
                $("recomBoxHeaderLnk"+this._idx).setAttribute("selected", "1");
                new Effect.BlindDown("recomBoxContent"+this._idx, {duration:0.3, afterFinish:function() {
                		if($("recomBoxContent"+this._idx))
                        	$("recomBoxContent"+this._idx).style.position = "static";
                        if (recom._onPageLoad && recom._idx != recom._onPageLoadLastIdx) {
                            //recom._onPageLoad = false;
                            recom.init(recom._onPageLoadLastIdx);                     
                        }
                    }
                });                
            }
            else {
                $("recomBoxHeader"+this._idx).className = "recomBoxHeader";
                $("recomBoxHeaderLnk"+this._idx).className = "recomBoxHeaderLnk";     
                $("recomBoxHeaderLnk"+this._idx).setAttribute("selected", "0");           
                new Effect.BlindUp("recomBoxContent"+this._idx, {duration:0.3, beforeStart:function() {
                        $("recomBoxContent"+recom._idx).style.position = "relative";                        
                    }
                });
            }            
        } catch(e) {}
    },
    
    getRecordingData : function() {
        try {                                    
            if ($("recomBoxContent"+this._idx).innerHTML.strip() == "") {
                $("recomBoxContent"+this._idx).innerHTML = '<div class="ajaxLoading"></div>';
                new Ajax.Request(this._dataObj[this._idx-1].url, {
                    onSuccess: function(resp) {
                        recom.renderRecordingData(resp.responseText);
                    }
                });
            }
            this.showHide();
        } catch(e) {}
    },
    
    renderRecordingData : function(resp) {
        try {
            var jsonData = eval('('+resp+')');
            var objArr = new Array();
            if(jsonData.recordings.length > 0){
            	var box = jsonData.recordings[0].box;
            	var userName="";
            	var tipText = "";
            	var fullFname="";
            	var profileTipText="";
	            for (var i = 0; i < jsonData.recordings.length; i++) {
	            	var songName=decodeURIComponent(jsonData.recordings[i].songName);
	            	if(songName.length > 30){
	            		songName = songName.substring(0, 30) + '...';
	            	}
	            	fullFname = decodeURIComponent(jsonData.recordings[i].fName).replace(/\+/g, ' ');
	                var strArr = new Array();
	                strArr[0] = '<div class="recomRowRecording">';
	                if (jsonData.recordings[i].isVideo == "1"){
	                	tipText = resources.getMessage("recommendation.tooltip.listen").replace("<username>", fullFname);
	                	strArr[1] = '<a class="userPhoto" href="javascript:showSongProfile('+jsonData.recordings[i].sId+','+jsonData.recordings[i].uId+','+jsonData.recordings[i].rId+');" title="'+tipText+'">';
	                }else{
	                	tipText = resources.getMessage("recommendation.tooltip.watch").replace("<username>", fullFname);
	                	strArr[1] = '<a class="userPhoto" href="javascript:showSongProfile('+jsonData.recordings[i].sId+','+jsonData.recordings[i].uId+','+jsonData.recordings[i].rId+');" title="'+tipText+'">';
	                }
	                if (jsonData.recordings[i].isVideo == "2") {
	                	if (jsonData.recordings[i].gender == "male")
		                    strArr[2] = '<img src="'+jsonData.recordings[i].photoUrl+'" onerror="videoThumbnailsSearch(this,USER_GENDER_MALE);"  onload="checkVideoImageExist(this,USER_GENDER_MALE);"/>';
		                else
		                    strArr[2] = '<img src="'+jsonData.recordings[i].photoUrl+'" onerror="videoThumbnailsSearch(this,USER_GENDER_FEMALE);"  onload="checkVideoImageExist(this,USER_GENDER_FEMALE);"/>';
	                } else {
	                	if (jsonData.recordings[i].gender == "male")
		                    strArr[2] = '<img src="'+jsonData.recordings[i].photoUrl+'" onerror="userPhotosSearch(this,USER_GENDER_MALE);"  onload="checkUserImageExist(this,USER_GENDER_MALE);"/>';
		                else
		                    strArr[2] = '<img src="'+jsonData.recordings[i].photoUrl+'" onerror="userPhotosSearch(this,USER_GENDER_FEMALE);"  onload="checkUserImageExist(this,USER_GENDER_FEMALE);"/>';
	                }
	                if (jsonData.recordings[i].isVideo == "1")
	                    strArr[3] = '<div class="audioPlayBtn"></div>';
	                else
	                    strArr[3] = '<div class="videoPlayBtn"></div>';
	                strArr[4] = '</a>';
	                if(window.location.host=="karaoke.jp.myspace.com"){

		                if(songName.length > 20 ){
		                	songName= songName.substring(0, 20)+'...';
		                }
		            }	                
	                strArr[5] = '<a class="songName" href="javascript:showSongProfile('+jsonData.recordings[i].sId+','+jsonData.recordings[i].uId+','+jsonData.recordings[i].rId+');" title="'+decodeURIComponent(jsonData.recordings[i].songName)+'">'+songName+'</a>';
	                strArr[6] = '<div class="fromTxt">'+resources.getMessage("recommendation.from")+':&nbsp;</div>';
	                userName = unescape(decodeURIComponent(jsonData.recordings[i].fName).replace(/\+/g, ' '));
	                if(userName.length > 20 ){
	                	userName = userName.substring(0, 20)+'...';
	                }
	                profileTipText = resources.getMessage("recommendation.tooltip.viewprofile").replace("<username>", fullFname);
	                strArr[7] = '<a class="userFirstName" href="javascript:showUserProfile('+jsonData.recordings[i].uId+');" title="'+profileTipText+'"><span>'+userName+'</span></a>';
				    strArr[8] = '<div class="extraInfoCol1Header">'+resources.getMessage("recommendation.plays")+'</div>';
				    strArr[9] = '<div class="extraInfoCol1Txt">'+jsonData.recordings[i].playNum+'</div>';
				    strArr[10] = '<div class="extraInfoCol2Header">'+resources.getMessage("recommendation.feedback")+'</div>';
				    strArr[11] = '<div class="extraInfoCol2Txt">'+jsonData.recordings[i].fbNum+'</div>';
	                strArr[12] = '</div>';
	                
	                objArr[i] = strArr.join("");
	            }
	            $("recomBoxContent"+box).innerHTML = objArr.join("");
	            if (recom._onPageLoad && this._idx == recom._onPageLoadLastIdx) {
	            	recom._onPageLoad = false;
	            }
				// Adjust height for recordsets < 5
				if(jsonData.recordings.length < 5) {
					var countRecords = jsonData.recordings.length;
					var heightAdjustment = (countRecords - 1) * 6;
	        		$("recomBoxContent"+this._idx).style.height = parseInt((countRecords * 85) - heightAdjustment) + "px";
				}
	        }else{
	        	var strArr = new Array();
	            strArr[0] = '<div class="recomRowRecording">';
	            strArr[1] = resources.getMessage("recommendation.none");
	            strArr[2] = '</div>';
	        	$("recomBoxContent"+this._idx).innerHTML = "";
	            $("recomBoxContent"+this._idx).innerHTML = strArr.join("");
	        	$("recomBoxContent"+this._idx).style.height = "40px";
	        	if (recom._onPageLoad){
	        		this.showHide();
	        		this.emptyListRecover(this._idx);
	        	}
	        }
        } catch(e) {}
    },
    
    getSongData : function() {
        try {                                             
            if ($("recomBoxContent"+this._idx).innerHTML.strip() == "") {
                $("recomBoxContent"+this._idx).innerHTML = '<div class="ajaxLoading"></div>';
                new Ajax.Request(this._dataObj[this._idx-1].url, {
                    onSuccess: function(resp) {
                        //alert(resp.responseText);           
                        recom.renderSongData(resp.responseText);                        
                    }
                });
            }            
            this.showHide();
        } catch(e) {alert(e);}
    },
    renderSongData : function(resp) {
        try {
            var jsonData = eval('('+resp+')');
            var objArr = new Array();
            if(jsonData.recordings.length > 0){
            	var box = jsonData.recordings[0].box;
	            for (var i = 0; i < jsonData.recordings.length; i++) {
	            	var songName=decodeURIComponent(jsonData.recordings[i].songName);
	            	if(songName.length > 35){
	            		songName = songName.substring(0, 35) + '...';
	            	}
	                var strArr = new Array();
	                strArr[0] = '<div class="recomRowSong">';                
	                strArr[1] = '<a href="javascript:searchSongBySongId('+jsonData.recordings[i].sId+');" style="cursor:pointer;" title="'+decodeURIComponent(jsonData.recordings[i].songName)+'"><div class="playBtn"></div></a>';
	                strArr[2] = '<a href="javascript:searchSongBySongId('+jsonData.recordings[i].sId+');" class="songName" title="'+decodeURIComponent(jsonData.recordings[i].songName)+'">'+songName+'</a>';                                
	                strArr[3] = '<a href="'+decodeURIComponent(jsonData.recordings[i].artistLink)+'" class="artistName" title="'+decodeURIComponent(jsonData.recordings[i].artistName)+'">'+decodeURIComponent(jsonData.recordings[i].artistName)+'</a>';
	                strArr[4] = '</div>';
	                
	                objArr[i] = strArr.join("");
	            }
	            $("recomBoxContent"+box).innerHTML = objArr.join("");
	            if (recom._onPageLoad && this._idx == recom._onPageLoadLastIdx) {
	            	recom._onPageLoad = false;
	            }
	        }else{
	        	var strArr = new Array();
	            strArr[0] = '<div class="recomRowRecording">';
	            strArr[1] = resources.getMessage("recommendation.none");
	            strArr[2] = '</div>';
	        	$("recomBoxContent"+this._idx).innerHTML = "";
	            $("recomBoxContent"+this._idx).innerHTML = strArr.join("");
	        	if (recom._onPageLoad){
	        		this.showHide();
	        		this.emptyListRecover(this._idx);
	        	}
	        }
        } catch(e) {
        }
    },
    
    getArtistData : function() {
        try {                                             
            if ($("recomBoxContent"+this._idx).innerHTML.strip() == "") {
                $("recomBoxContent"+this._idx).innerHTML = '<div class="ajaxLoading"></div>';
                new Ajax.Request(this._dataObj[this._idx-1].url, {
                    onSuccess: function(resp) {
                        //alert(resp.responseText);           
                        recom.renderArtistData(resp.responseText);                        
                    }
                });
            }            
            this.showHide();
        } catch(e) {alert(e);}
    },
    
    renderArtistData : function(resp) {
        try {
            var jsonData = eval('('+resp+')');
            var objArr = new Array();
            
            if(jsonData.artists.length > 0){
            	var box = jsonData.artists[0].box;
            	var artistLength = 0;
	            for (var i = 0; i < jsonData.artists.length; i++) {
	                var strArr = new Array();
					strArr.push('<table style="border-left:none;border-right:none;" ><tr><td style="padding:8px 0px 5px 7px;" colspan="2">');
					strArr.push('<a href="'+decodeURIComponent(jsonData.artists[i].artistLink)+'" style="color:#008fff;font-weight:bold;font-size:9px;" title="'+decodeURIComponent(jsonData.artists[i].artistName)+'">'+decodeURIComponent(jsonData.artists[i].artistName)+'</a>');
					strArr.push('</td></tr><tr>');
					artistLength = jsonData.artists[i].songs.length 
					for(var j=0;j<artistLength;j++){
						strArr.push('<td style="padding:1px 0px 5px 7px;">');
						strArr.push('<a href="javascript:searchSongBySongId('+jsonData.artists[i].songs[j].sid+');" style="color:#868383;font-weight:bold;font-size:9px;" title="'+decodeURIComponent(jsonData.artists[i].songs[j].songName)+'">'+decodeURIComponent(jsonData.artists[i].songs[j].songName)+'</a>');
						if(artistLength==2 && j==0 ){
							strArr.push(",");
						}
						strArr.push('</td>');
					}
					strArr.push('</tr></table>');
	                objArr[i] = strArr.join("");
	            }
	            $("recomBoxContent"+box).innerHTML = objArr.join("");
	            if (recom._onPageLoad && this._idx == recom._onPageLoadLastIdx) {
	            	recom._onPageLoad = false;
	            }
	        }else{
	        	var strArr = new Array();
	            strArr[0] = '<div class="recomRowRecording">';
	            strArr[1] = resources.getMessage("recommendation.none");
	            strArr[2] = '</div>';
	        	$("recomBoxContent"+this._idx).innerHTML = "";
	            $("recomBoxContent"+this._idx).innerHTML = strArr.join("");
	        	if (recom._onPageLoad){
	        		this.showHide();
	        		this.emptyListRecover(this._idx);
	        	}
	        }
        } catch(e) {}
    },
    
    getNextOrderIndex : function(curInd) {
    	var ind = -1;
    	try{
			for(var i=0;i<recom._order.length;i++){
				if(curInd == recom._order[i]){
					var next = i+1;
					ind = recom._order[next];
					break;
				}
			}
		} catch(e) {}
    	return ind;
    }, 
    //cheolho:giant hack.. sorry for who every has to maintain.
    //purpose... on load need to not open the box, and grab the
    //next index in the list of ordered items, and set onPageLoadIdx or Lastidx
    //if empty list is returned
    emptyListRecover : function(curInd){
       	if (recom._onPageLoad) {
       		var tryNextInd = this.getNextOrderIndex(curInd);
       		if(tryNextInd == -1){
       			recom._onPageLoad = false;
       		}else{
       			if (this._idx  == recom._onPageLoadLastIdx){
        			recom._onPageLoadLastIdx = tryNextInd;
        			recom._idx = tryNextInd;
        			recom.init(recom._onPageLoadLastIdx);
        		}else{
        			recom._onPageLoadIdx = tryNextInd;
        			recom._idx = tryNextInd;
					var laseNextInd = this.getNextOrderIndex(tryNextInd);
					if(laseNextInd == -1){
       					recom._onPageLoad = false;
       				}else{
       					recom._onPageLoadLastIdx = laseNextInd;
       				}
        			recom.init(recom._onPageLoadIdx);		        			
        		}
       		}
       	}
    }
}

var feedbackController = {
    _uid : "",
    _ufname : "",
    _sid : "",
    _rid : "",
    _startRow : "",
        
    init : function(uid, ufname, startRow, sid, rid) 
	{
        try 
		{
        	this._uid = uid;
        	this._ufname = ufname;
        	this._startRow = startRow;
        	this._sid = sid;
        	this._rid = rid;        	
            this.getFb();
        } 
		catch(e) {alert(e)}
    },
    
    getFb : function() 
	{
    	try
		{
    		if ($("fbContent").innerHTML.indexOf("ajaxLoading") != "-1") {                
                var url = "/actions/listFeedbacks.do?uid="+this._uid+"&sid="+this._sid+"&rid="+this._rid+"&startRow="+this._startRow+"&ufname="+this._ufname;
                new Ajax.Request(url, {onSuccess:feedbackController.getFb_cb});
            }
    	} 
		catch(e) {alert(e)}
    },
    
    getFb_cb : function(resp) 
	{
    	try 
		{
    		//alert(resp.responseText);                         
            $("fbContent").innerHTML = resp.responseText;
    	} 
		catch(e) {alert(e)}
    }
}


/********************************************************************************************/
function doDynamicTooltip(div)
{
	var obj = document.getElementById(div);
	if (obj)
	{
		var escaped = escape(obj.innerHTML)
		ddrivetip(escaped);
	}
}

function getAVControl(){
	if($('AVControlFF')){
		return $('AVControlFF');
	}else if($('AVControl')){
		return $('AVControl');
	}else{
		return null;
	}	
}
function closeAVX() {
  try {
  	
  	if(top.location.href.indexOf("recordSongChain.do") != -1) {
		// Need to restore Participant's Original Background Volume if this was a song chain before shutting down
  		AVControl.fMusicScale = $("StoreBGVolume").innerHTML;
  		AVControl.SaveSettings();
  	}
    AVControl.Shutdown();
  } catch(e) {}
}

/********************************************************************************************/
/********************************************************************************************/
/*** Shared : MySpace Header ****************************************************************/

var mshdr_disappeardelay = 250 //menu disappear speed onMouseout (in miliseconds)
var mshdr_enableanchorlink = 0 //Enable or disable the anchor link when clicked on? (1 = e, 0 = d)
var mshdr_hidemenu_onclick = 1 //hide menu when user clicks within menu? (1 = yes, 0 = no)

/////No further editting needed

var mshdr_ie5 = document.all;
var mshdr_ns6 = document.getElementById && !document.all;

function mshdr_getposOffset(what, offsettype)
{
	
	var totaloffset = (offsettype == "left") ? what.offsetLeft : what.offsetTop;
	//alert(what.offsetLeft);
	var parentEl = what.offsetParent;
	
	while (parentEl != null)
	{
		//totaloffset = (offsettype == "left") ? totaloffset + parentEl.offsetLeft : totaloffset + parentEl.offsetTop;
		totaloffset = (offsettype == "left") ? totaloffset : totaloffset + parentEl.offsetTop;
		parentEl = parentEl.offsetParent;
	}
	return totaloffset;
}

function mshdr_showhide(obj, e, visible, hidden)
{
	if (mshdr_ie5 || mshdr_ns6)
	{
		dropmenuobj.style.left = dropmenuobj.style.top = -500;
	}
	if (e.type == "click" && obj.visibility == hidden || e.type == "mouseover")
	{
		obj.visibility = visible;
	}
	else if (e.type == "click")
	{
		obj.visibility = hidden;
	}
}

function mshdr_iecompattest()
{
	return (document.compatMode && document.compatMode != "BackCompat") ? document.documentElement : document.body
}

function mshdr_clearbrowseredge(obj, whichedge)
{
	var edgeoffset = 0
	if (whichedge == "rightedge")
	{
		var windowedge = mshdr_ie5 && !window.opera ? mshdr_iecompattest().scrollLeft + mshdr_iecompattest().clientWidth - 15 : window.pageXOffset + window.innerWidth - 15
		dropmenuobj.contentmeasure = dropmenuobj.offsetWidth;
		if (windowedge-dropmenuobj.x < dropmenuobj.contentmeasure)
		{
			edgeoffset = dropmenuobj.contentmeasure-obj.offsetWidth;
		}
	}
	else
	{
		var topedge = mshdr_ie5 && !window.opera? mshdr_iecompattest().scrollTop : window.pageYOffset
		var windowedge = mshdr_ie5 && !window.opera ? mshdr_iecompattest().scrollTop + mshdr_iecompattest().clientHeight - 15 : window.pageYOffset + window.innerHeight - 18
		dropmenuobj.contentmeasure = dropmenuobj.offsetHeight;
		if (windowedge-dropmenuobj.y < dropmenuobj.contentmeasure) //move up?
		{
			edgeoffset = dropmenuobj.contentmeasure + obj.offsetHeight;
			if ((dropmenuobj.y - topedge) < dropmenuobj.contentmeasure) //up no good either?
			{
				edgeoffset = dropmenuobj.y + obj.offsetHeight - topedge;
			}
		}
	}
	return edgeoffset
}

function mshdr_dropdownmenu(obj, e, dropmenuID)
{
	if (window.event)
	{
		event.cancelBubble = true;
	}
	else if (e.stopPropagation)
	{
		e.stopPropagation();
	}
	if (typeof dropmenuobj != "undefined") //hide previous menu
	{
		dropmenuobj.style.visibility = "hidden";
	}
	mshdr_clearhidemenu();
	if (mshdr_ie5||mshdr_ns6)
	{
		obj.onmouseout = mshdr_delayhidemenu;
		dropmenuobj = document.getElementById(dropmenuID);
		if (mshdr_hidemenu_onclick) dropmenuobj.onclick = function()
		{
			dropmenuobj.style.visibility = 'hidden';
		}
		dropmenuobj.onmouseover = mshdr_clearhidemenu;
		dropmenuobj.onmouseout = mshdr_ie5 ? function() { mshdr_dynamichide(event)} : function(event) { mshdr_dynamichide(event)}
		mshdr_showhide(dropmenuobj.style, e, "visible", "hidden");
		dropmenuobj.x = mshdr_getposOffset(obj, "left");
		dropmenuobj.y = mshdr_getposOffset(obj, "top");
		if(!IE6){
			dropmenuobj.style.left = dropmenuobj.x - mshdr_clearbrowseredge(obj, "rightedge") + "px";
			dropmenuobj.style.top = dropmenuobj.y - mshdr_clearbrowseredge(obj, "bottomedge") + obj.offsetHeight+"px";
		}
		else{
			if(dropmenuID=="myspaceHeader-SubNav"){
				dropmenuobj.style.left = dropmenuobj.x - mshdr_clearbrowseredge(obj, "rightedge") + "px";
				dropmenuobj.style.top = dropmenuobj.y - mshdr_clearbrowseredge(obj, "bottomedge") + obj.offsetHeight+"px";
			}
		}
	}
	return mshdr_clickreturnvalue();
}

function mshdr_clickreturnvalue()
{
	return ((mshdr_ie5||mshdr_ns6) && !mshdr_enableanchorlink) ? false : true;
}

function mshdr_contains_mshdr_ns6(a, b) 
{
	while (b.parentNode)
	if ((b = b.parentNode) ==  a)
	return true;
	return false;
}

function mshdr_dynamichide(e)
{
	if (mshdr_ie5 && !dropmenuobj.contains(e.toElement))
	{
		mshdr_delayhidemenu();
	}
	else if (mshdr_ns6 && e.currentTarget !=  e.relatedTarget && !mshdr_contains_mshdr_ns6(e.currentTarget, e.relatedTarget))
	{
		mshdr_delayhidemenu();
	}
}

function mshdr_delayhidemenu()
{
	delayhide = setTimeout("dropmenuobj.style.visibility = 'hidden'", mshdr_disappeardelay);
}

function mshdr_clearhidemenu()
{
	if (typeof delayhide != "undefined")
	clearTimeout(delayhide);
}
/********************************************************************************************/



/********************************************************************************************/
/********************************************************************************************/
/*** Shared : Textbox Limiter ***************************************************************/
function textLimit(field,maxlen) 
{
	if(field.value.length > maxlen)
	{
		while(field.value.length > maxlen)
		{
			field.value=field.value.replace(/.$/,'');
		}
	}

	var charsLeft = document.getElementById("charsLeft");
	if (charsLeft)
	{
		var chars = maxlen - field.value.length;
		charsLeft.innerHTML = chars.toString();
	}
}
function textLimitOnSubmit(id,maxlen,message) 
{
	var field = document.getElementById(id);
	if (field && field.value)
	{
		if(field.value.replace(/ /g,'').length > maxlen)
		{
			alert(message);
			return false;
		}
	}

	return true;
}

// Does Ajax Request and populates <DIV>'s Inner HTML
function ks_doAjaxRequest(url, div, substringBody)
{
	try 
	{
		new Ajax.Request(url, 
		{
			onSuccess: function(resp) 
			{
				$(div).innerHTML = substringBody ? getInnerHtmlOfBody(resp.responseText) : resp.responseText;
			}
		});
	} 
	catch(e) {}
}

// Get's the <BODY> tag's InnerHTML
function getInnerHtmlOfBody(html) 
{
	var iBodySt = html.indexOf("<body>");
	var iLength = html.length;
	html = html.substring(iBodySt);
	var iBodyEd = html.indexOf("</body>");
	html = html.substring(0, iBodyEd);

	return html;
}

function closePopupWindow() 
{
	try 
	{        
		$("popup_wrapper").remove();
	} 
	catch(e) {}
}


function toggleAllCheckboxes(cbx, suffix, div)
{
	if (cbx.checked == true)
	{
		setCheckboxValue(div,true);
		$("lblSelectAll" + suffix).style.display = "none";
		$("lblUnSelectAll" + suffix).style.display = "";
	}
	else
	{
		setCheckboxValue(div,false);
		$("lblSelectAll" + suffix).style.display = "";
		$("lblUnSelectAll" + suffix).style.display = "none";
	}
}

function setCheckboxValue(_where,_value)
{
	var elmnt = document.getElementById(_where).getElementsByTagName("input");
	if(elmnt){
		for(i=0;i<elmnt.length;i++){
			if(elmnt[i].type){
				if(elmnt[i].type.toLowerCase() == "checkbox"){
					elmnt[i].checked = _value;
				}
			}
		}
	}
}

/* MySpace Footer */
function HidesrchMenuList(){

	//setTimeout("document.getElementById('srchMenuListBox_Footer').style.display='none';",2200);
	document.getElementById('srchMenuListBox_Footer').style.display='none';
}
function ShowsrchMenuList(){

	document.getElementById('srchMenuListBox_Footer').style.display='block';
}

function setListType(srchItem){
	document.getElementById('SrchTypetxt').innerHTML=srchItem;
	document.getElementById('srchMenuListBox_Footer').style.display='none';
}
function SubmitSrchForm(){
	switch(document.getElementById('SrchTypetxt').innerHTML)
	{
		case "Web":
			document.getElementById('srchTypeFooter').value='tweb';
			break;
		case "MySpace":
			document.getElementById('srchTypeFooter').value='tms';
			break;
		case "Music":
			document.getElementById('srchTypeFooter').value='tmusic';
			break;
		case "Video":
			document.getElementById('srchTypeFooter').value='tvid';
			break;
		case "Images":
			document.getElementById('srchTypeFooter').value='timages';
			break;
		case "People":
			document.getElementById('srchTypeFooter').value='tpeople';
			break;
		default:
			document.getElementById('srchTypeFooter').value='tpeople';
			break;
	}
		document.myspaceSearchForm2.submit();
}


