//**VARIABLES**//
var baseURL = '';

var user        = new Object;
user.guid       = '';
user.token      = '';
user.username   = '';
user.userid     = '';
user.partnerId  = 87;
user.isReg      = 'N';
user.cookieGuid = '';
user.flashGuid  = '';

var anonHTTP     = '';

var flashplayer  = '';

//*************************//
//**Loading Content Pages**//
//*************************//

function setContentFrame(fileName){
	document.getElementById("mainContent").src = fileName;
}

function setBuilderFrame(fileName){
	document.getElementById("playlistContent").src = fileName;
}

function gotoUserPage(userid, params){
	var random  = Math.round((Math.random()*32767)+1);
	if(params != undefined){
		document.getElementById("mainContent").src = "content/userProfile.php?u=" + user.guid + "&id=" + userid + "&rand=" + random + params;
	}else{
		document.getElementById("mainContent").src = "content/userProfile.php?u=" + user.guid + "&id=" + userid + "&rand=" + random;
	}
}

function gotoTagPage(tagId){
	if(tagId != '' && tagId != undefined){
		var random  = Math.round((Math.random()*32767)+1);
		document.getElementById("mainContent").src = "content/tag.php?u=" + user.guid + "&tid=" + tagId + "&rand=" + random;
	}
}

//New//
function gotoTagSection(section, tagId){
	if(section != '' && section != undefined){
		var random  = Math.round((Math.random()*32767)+1);
		if( section == 'artist' )	//Default tag page
			document.getElementById("mainContent").src = "content/tag.php?u=" + user.guid + "&tid=" + tagId + "&rand=" + random;
		else if( section == 'album' ) //Albums tag page
			document.getElementById("mainContent").src = "content/tag_albums.php?u=" + user.guid + "&tid=" + tagId + "&rand=" + random;
		else if( section == 'playlist' ) //Playlists tag page
			document.getElementById("mainContent").src = "content/tag_playlists.php?u=" + user.guid + "&tid=" + tagId + "&rand=" + random;
	}
}
//

function gotoArtist(artistId, playit, params){
	if(artistId != '' && artistId != undefined){
        var random  = Math.round((Math.random()*32767)+1);
		if(playit == "play"){
			if(playlistEditMode == true){
        document.getElementById("mainContent").src = "content/artist.php?u=" + user.guid + "&id=" + artistId + "&cpid=" + currentPlaylistId + "&play=true&rand=" + random;
			}else{
				document.getElementById("mainContent").src = "content/artist.php?u=" + user.guid + "&id=" + artistId + "&play=true&rand=" + random;
			}
		}else if(playit == "tracks"){
			if(playlistEditMode == true){
 				document.getElementById("mainContent").src = "content/artist.php?u=" + user.guid + "&id=" + artistId + "&cpid=" + currentPlaylistId + "&rand=" + random;
			}else{
				document.getElementById("mainContent").src = "content/artist.php?u=" + user.guid + "&id=" + artistId + "&rand=" + random;
			}
		}else if(playit == "tagFav"){
			if(playlistEditMode == true){
				document.getElementById("mainContent").src = "content/artist.php?u=" + user.guid + "&id=" + artistId + "&action=tagFav&cpid=" + currentPlaylistId + params + "&rand=" + random;
			}else{
				document.getElementById("mainContent").src = "content/artist.php?u=" + user.guid + "&id=" + artistId + "&action=tagFav" + params + "&rand=" + random;
			}
		}else{
			if(playlistEditMode == true){
				document.getElementById("mainContent").src = "content/artist.php?u=" + user.guid + "&id=" + artistId + "&cpid=" + currentPlaylistId + "&rand=" + random;
			}else{
				if(params != undefined){
					document.getElementById("mainContent").src = "content/artist.php?u=" + user.guid + "&id=" + artistId + params + "&rand=" + random;
				}else{
					document.getElementById("mainContent").src = "content/artist.php?u=" + user.guid + "&id=" + artistId + "&rand=" + random;
				}
			}
		}
	}
}

function artist_link(aid){
	gotoArtist(aid);
}

function gotoArtistSection(pageName, artistId, playit, params){
	if(artistId != '' && artistId != undefined){
    var random  = Math.round((Math.random()*32767)+1);
		if(playit == "tagFav"){
			if(playlistEditMode == true){
        document.getElementById("mainContent").src = "content/" + pageName + ".php?u=" + user.guid + "&id=" + artistId + "&action=tagFav&cpid=" + currentPlaylistId + params + "&rand=" + random;
			}else{
				document.getElementById("mainContent").src = "content/" + pageName + ".php?u=" + user.guid + "&id=" + artistId + "&action=tagFav" + params + "&rand=" + random;
			}
		}else{
			if(playlistEditMode == true){
        document.getElementById("mainContent").src = "content/" + pageName + ".php?u=" + user.guid + "&id=" + artistId + "&cpid=" + currentPlaylistId + "&rand=" + random;
			}else{
				if(params != undefined){
					document.getElementById("mainContent").src = "content/" + pageName + ".php?u=" + user.guid + "&id=" + artistId + params + "&rand=" + random;
				}else{
					document.getElementById("mainContent").src = "content/" + pageName + ".php?u=" + user.guid + "&id=" + artistId + "&rand=" + random;
				}
			}
		}
	}
}

function gotoAlbum(albumId, params){
	if(albumId != '' && albumId != undefined){
		var random  = Math.round((Math.random()*32767)+1);
		var docURL  = '';
		docURL += "content/album.php?u=" + user.guid + "&id=" + albumId + "&ir=" + user.isReg;
		if(playlistEditMode == true){
			docURL += "&cpid=" + currentPlaylistId;
		}
		docURL += "&rand=" + random;
		if(params != undefined){
			docURL += params;
		}
		document.getElementById("mainContent").src = docURL;
	}
}

function gotoOtherUsers(userId){
	if(userId != '' && userId != undefined){
		var random  = Math.round((Math.random()*32767)+1);
	
		//if(guid != user.guid){
			document.getElementById("mainContent").src = "content/userProfile.php?u=" + user.guid + "&id=" + userId + "&rand=" + random;

		//}else{
		//	gotoUserPage(guid);
		//}
	}
}

function gotoPlaylistPage(pid, params){
    var random  = Math.round((Math.random()*32767)+1);
	if(playlistEditMode){
		if(params == undefined){
			params = '';
		}
		setContentFrame('content/playlistInfo.php?u=' + user.guid + '&pid=' + pid + '&userpid=' + currentPlaylistId + '&rn=' + random + params);
	}else{
		if(params == undefined){
			params = '';
		}
    setContentFrame('content/playlistInfo.php?u=' + user.guid + '&pid=' + pid + '&rn=' + random + params);
	}
}

function gotoPlaylistInst(){
	var random  = Math.round((Math.random()*32767)+1);
	setContentFrame('content/playlistInstructions.php?u=' + user.guid + '&rand=' + random);
}
///*****///

//**Wiki Links**//
function artist_link(artistId){
	gotoArtist(artistId);
}



///*****///
function closeBuilderBox(){
	document.getElementById("playlistContent").src = "content/blank.php";
	boxOpen = "";
	
	showTipBox();
}

var boxOpen  = "";
var tipsOpen = "";
var tipBoxType  = "";

function showBuilderBox(pid){
	if(tipsOpen == "true"){
		hideTipBox();	
	}
	
	var random  = Math.round((Math.random()*32767)+1);
	document.getElementById("playlistContent").src = "content/builder.php?u=" + user.guid + "&pid=" + pid + "&rand=" + random;
	boxOpen = "true";
}

function showTipBox(tipType){
	
	if(!boxOpen){
		if(boxOpen == "true"){
			closeBuilderBox();
		}
		
		/**** Comment out 1/5/07***/
		if(document.getElementById("playlistContent").src.search(/tipBox.php/) > -1){
		}else{	
			//document.getElementById("playlistContent").src = "content/tipBox.php";
		}
		
		
		if (tipBoxType != tipType){
			tipBoxType = tipType;
					
			tipsOpen = "true";
		}
	}
}

var shoutTries = 0;
function retryShoutBox(){
	try{
		playlistContent.showShoutBox();
	}catch(E){
		shoutTries++;
		if(shoutTries < 4){
			setTimeout("retryShoutBox();", 500);
		}
	}
}

function hideTipBox(){
	document.getElementById("playlistContent").src = "content/blank.php";
	tipsOpen = "";
	shoutTries = 0;
}

function gotoReg(params){
	if(params == 'hp'){
		document.getElementById("mainContent").src = "content/register.php?u=" + user.guid;
	}else{
		document.getElementById("mainContent").src = "content/reg_catch.php?u=" + user.guid;
	}
}

var showFlashAlert = false;
function showFlashPlayerAlert(){
	showFlashAlert = true;
}


/*wiki link*/
function offsite_link(linkurl){
	window.open(linkurl, "ftOffsite");
}

//*******************//
//**User Management**//
//*******************//

var currIconPath = "";

function setUserInfo(userName, userGuid, userIcon, userId){
	//alert("setUserInfo :: " + userName + ", " + userGuid + ", " + userIcon);
	user.guid      = userGuid;
	user.username  = userName;
	user.userid    = userId;
	user.isReg     = 'Y';
	var headerHTML = '';
	var iconPath   = '';
	if(userIcon == '' || userIcon == undefined){
		iconPath = '';
	}else{
		iconPath = 'http://img.finetune.com' + newImageStructure(userIcon);
	}
	
	headerHTML += '<table cellpadding="0" cellspacing="0" width="100%" style="background-image:url(http://cdn.finetune.com/images/profile-box-bkg.gif); background-repeat: repeat-x; padding: 5px;">';
	headerHTML += '<tr>';
	headerHTML += '<td width="60" rowspan="2">';
	headerHTML += '<div id="userIconDiv"><a href="#" onClick="gotoUserPage(\'' + user.userid + '\'); return false;" title="' + userName + '"><img src="' + iconPath + '" id="persistIcon" alt="' + userName + '" height="55" width="55" class="albOrgBorder" onError="this.src=\'http://cdn.finetune.com/images/no_user_45.png\';" /></a></div>';
	headerHTML += '</td>';
	headerHTML += '<td style="padding: 0px 0px 0px 2px; border-bottom: 1px solid #666;" height="30">';
	headerHTML += '<div id="userNameDiv" style="margin-left: 2px;"><a href="#" onClick="gotoUserPage(\'' + user.userid + '\'); return false;">' + userName + '</div>';
	headerHTML += '<div><a href="#" onClick="gotoUserPage(\'' + user.userid + '\'); return false;"><img src="http://cdn.finetune.com/images/profile/view-prof.gif" alt="View Profile" title="View Profile" onMouseOver="this.src=\'http://cdn.finetune.com/images/profile/view-prof-over.gif\';" onMouseOut="this.src=\'http://cdn.finetune.com/images/profile/view-prof.gif\';" /></a><a href="#" onClick="userLogOut(); return false;"><img src="http://cdn.finetune.com/images/profile/log-out.gif" alt="Log-Out" title="Log-Out" onMouseOver="this.src=\'http://cdn.finetune.com/images/profile/log-out-over.gif\';" onMouseOut="this.src=\'http://cdn.finetune.com/images/profile/log-out.gif\';" /></a></div>';
	headerHTML += '</td>';
						
	headerHTML += '</tr>';
	headerHTML += '<tr>';
	headerHTML += '<td><div class="profileMsg">WELCOME</div></td>';
	headerHTML += '</tr>';
	headerHTML += '</table>';
	//alert(document.getElementById("profileLayout").innerHTML);
	document.getElementById("profileLayout").innerHTML = headerHTML;
	
	writeCookie("nxrGuid", user.guid, getExpDate(30, 0, 0), "/", ".finetune.com");
	setNewFlashGuid(user.guid);
}

function updateUserName(userStr){
	document.getElementById("userNameDiv").innerHTML = '<a href="#" class="cursorRollover" onClick="gotoUserPage(\'' + user.userid + '\'); return false;">' + userStr + '</a></div>';
}

function setUserIcon(path){
	var iconHTML = '';
	iconHTML += '<a href="#" onClick="gotoUserPage(\'' + user.userid + '\'); return false;" title="' + user.username + '">';
	iconHTML += '<img src="http://img.finetune.com' + path + '" id="persistIcon" alt="' + user.username + '" height="45" width="45" class="albOrgBorder" onError="this.src=\'http://cdn.finetune.com/images/no_user_45.png\';" />';
	iconHTML += '</a>';
	iconHTML += '</div>';
	
	document.getElementById("userIconDiv").innerHTML = iconHTML;
}

function rmUserIcon(){	
	document.getElementById("userIconDiv").innerHTML = '';
}

function updateUserIcon(path){
	currIconPath = path;
	document.getElementById("persistIcon").src = path;
}

function userLogOut(){
	user.guid     = '';
	user.token    = '';
	user.username = '';
	user.isReg    = 'N';
	
	deleteCookie("nxrGuid", "/", ".finetune.com");
	deleteCookie("anonGuid", "/", ".finetune.com");
	
	playlistEditMode  = false;
	currentPlaylistId = 0;
	
	getAnonGuid();
}

function getAnonGuid(){
	var random  = Math.round((Math.random()*32767)+1);
						
	if (window.XMLHttpRequest){ ///Mozilla, Safari
		anonHTTP = new XMLHttpRequest();
	}else if(window.ActiveXObject){
		try{
			anonHTTP = new ActiveXObject("Msxml2.XMLHTTP");
		} catch(e){
			try{
				anonHTTP = new ActiveXObject("Microsoft.XMLHTTP");
			} catch(e){}
		}
	}

	anonHTTP.onreadystatechange = getAnonGuidHandler;
	anonHTTP.open("GET", "/api/getAnonGuid.php" + "?rn=" + random, true);
	anonHTTP.send(null);
}

function getAnonGuidHandler(){
	if(anonHTTP.readyState == 4){
		if(anonHTTP.status == 200){
			newUserGuid = anonHTTP.responseText;
			
			user.guid = newUserGuid;
			
			/* User Log Out */
			/* Change from profile view to register view in header */
			var headerHTML = '';
			headerHTML += '<table cellpadding="0" cellspacing="0" width="100%" style="background-image:url(http://cdn.finetune.com/images/profile-box-bkg.gif); background-repeat: repeat-x; padding: 5px;">';		
			headerHTML += '<tr>';
			headerHTML += '<td style="vertical-align: bottom;" height="30">';
			headerHTML += '<div style="text-align:center; border-bottom: 1px solid #666; margin: 0px 30px 0px 30px; padding-bottom: 5px;"><a href="#" onClick="parent.gotoReg(\'hp\'); return false;"><img src="http://cdn.finetune.com/images/profile/register.gif" alt="Register" title="Register" onMouseOver="this.src=\'http://cdn.finetune.com/images/profile/register-over.gif\';" onMouseOut="this.src=\'http://cdn.finetune.com/images/profile/register.gif\';" /></a><a href="#" onClick="parent.setContentFrame(\'content/signin.php?u=\' + user.guid); return false;"><img src="http://cdn.finetune.com/images/profile/log-in.gif" alt="Log-In" title="Log-In" onMouseOver="this.src=\'http://cdn.finetune.com/images/profile/log-in-over.gif\';" onMouseOut="this.src=\'http://cdn.finetune.com/images/profile/log-in.gif\';" /></a></div>';
			headerHTML += '</tr>';
			headerHTML += '<tr>';
			headerHTML += '</td>';
			headerHTML += '<td><div class="profileMsg">WELCOME</div></td>';
			headerHTML += '</tr>';
			headerHTML += '</table>';
			document.getElementById("profileLayout").innerHTML = headerHTML;
	
			//rmUserIcon();
			//updateUserName(user.username);
	
			document.getElementById('mainContent').src = "content/home.php";
			
			hideBuilder("norefresh");
			
			writeCookie("anonGuid", user.guid, getExpDate(30, 0, 0), "/", ".finetune.com");
		}
	}
}

function resetUserInfo(){
	var random  = Math.round((Math.random()*32767)+1);
	playlistArr       = new Array();
	playlistEditMode  = false;
	currentPlaylistId = 0;
	//clearPlaylistDetailsView();
	document.getElementById("playlistContent").src = "";
	document.getElementById("playlistContent").src = "content/builder.php?u=" + user.guid + "&rand=" + random;

	if(user.username != '' && user.username != undefined){
		//document.getElementById('signin').innerHTML = '<a href="#" class="menuLinks" onClick="gotoUserPage();" style="color: #FFF;">' + user.username + '</a> ';
		//document.getElementById('reg').innerHTML    = ' [<a href="#" onClick="userLogOut();" style="font-size: 8pt;">Logout</a>]';
	}
}

function checkUserSession(flashGuid){
	if(flashGuid != ''){
		user.flashGuid = flashGuid;
	}
	
	if(flashGuid == user.guid){
		//pass
	}else{
			//if guids not equal
		if(user.guid != ''){
			functionExists = flashplayer.setListener;
			if(functionExists != '' && functionExists != undefined){
				setTimeout("setNewFlashGuid('" + user.guid + "');", 1000);
			}
		}
	}
}

function setNewFlashGuid(userguid){
	if(user.isReg == 'Y'){
		flashplayer.setListener(userguid);
		if(user.flashGuid != 'xxplayerguidxx' && user.flashGuid != '' && user.flashGuid != undefined){
			if(guidInfoHTTPResult != ''){
				if(guidInfoHTTPResult == 'reg'){
					//flash guid reg, do not link
				}else{
					linkGuids(userguid, user.flashGuid);
				}
				guidInfoHTTPResult = '';
			}else{
				state = getGuidInfo(user.flashGuid);
			}	
		}
	}else{
		if(user.flashGuid == 'xxplayerguidxx' || user.flashGuid == '' || user.flashGuid == undefined){
			flashplayer.setListener(userguid);
		}else if(guidInfoHTTPResult != ''){
			if(guidInfoHTTPResult == 'reg'){
				//then flash guid is registered.  do not overwrite
			}else{
				//flash guid anon, overwrite
				flashplayer.setListener(userguid);
				if(user.flashGuid != 'xxplayerguidxx' && user.flashGuid != ''){
					linkGuids(userguid, user.flashGuid);
				}
			}
			guidInfoHTTPResult = '';
		}else{
			state = getGuidInfo(user.flashGuid);
			//get flash guid state
			//if app state == reg, then push
			//else if flash state == anon, then push
		}
	}
}


var guidInfoHTTP = '';
var guidInfoHTTPResult = '';

function getGuidInfo(flashGuid){
	if(flashGuid != '' && flashGuid != undefined && flashGuid != 'xxplayerguidxx'){
		var random  = Math.round((Math.random()*32767)+1);
						
		if (window.XMLHttpRequest){ ///Mozilla, Safari
			guidInfoHTTP = new XMLHttpRequest();
		}else if(window.ActiveXObject){
			try{
				guidInfoHTTP = new ActiveXObject("Msxml2.XMLHTTP");
			} catch(e){
				try{
					guidInfoHTTP = new ActiveXObject("Microsoft.XMLHTTP");
				} catch(e){}
			}
		}

		guidInfoHTTP.onreadystatechange = getGuidInfoHandler;
		guidInfoHTTP.open("GET", "/api/getGuidInfo.php?fg=" + flashGuid + "&rn=" + random, true);
		guidInfoHTTP.send(null);
	}
}

function getGuidInfoHandler(){
	if(guidInfoHTTP.readyState == 4){
		if(guidInfoHTTP.status == 200){
			userObj = eval("(" + guidInfoHTTP.responseText + ")");
			guidInfoHTTPResult = userObj.userState;
			setNewFlashGuid(user.guid)
		}
	}
}

var linkGuidHTTP = '';

function linkGuids(primaryGuid, linkGuid){
	if(primaryGuid != '' && primaryGuid != undefined && primaryGuid != 'xxplayerguidxx'){
		if(linkGuid != '' && linkGuid != undefined && linkGuid != 'xxplayerguidxx'){
			var random  = Math.round((Math.random()*32767)+1);
						
			if (window.XMLHttpRequest){ ///Mozilla, Safari
				linkGuidHTTP = new XMLHttpRequest();
			}else if(window.ActiveXObject){
				try{
					linkGuidHTTP = new ActiveXObject("Msxml2.XMLHTTP");
				} catch(e){
					try{
						linkGuidHTTP = new ActiveXObject("Microsoft.XMLHTTP");
					} catch(e){}
				}
			}

			linkGuidHTTP.open("GET", "/api/linkGuids.php?pg=" + primaryGuid + "&ag=" + linkGuid + "&rn=" + random, true);
			linkGuidHTTP.send(null);
		}
	}
}

function newImageStructure(relPath){
	var reFile = new RegExp('\/.*\.(gif|jpg|png|bmp|tiff)', "i");
	var reAlphaNum = new RegExp('[A-Za-z0-9]');
	var middle = relPath.replace('/userImgs/', '').replace(reFile, '');
	
	//alert(middle);
	var split_middle = '';
	var max_reached = false;
	var i = 0;
	//Comment this out Later//
	//relPath = relPath.replace('/userImgs/', '/userImgsNew/');
	//////////////////////////
	
	for( i = 0; i < middle.length; i++ ){
		//alert(middle);
		if( middle.charAt(i).match(reAlphaNum))
			split_middle += middle.charAt(i).toLowerCase() + '/';
		else
			split_middle += 'sy/';
			
		if( i == 5 ){ //Max reached			
			max_reached = true;
			newPath = relPath.replace(middle, split_middle + middle);
			return newPath;
		}
	}
	if( !max_reached ){
		while( i < 6 ){
			split_middle += 'nu/';
			i++;
		}
		newPath = relPath.replace(middle, split_middle + middle);
		return newPath;
	}
}