//**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  = '';
var flashbuilder = '';

var trackmenu = '';	
var menuTimer = '';


function copyToClipboard(inElement) {
  if (parent.window.frames['mainContent'].document.getElementById(inElement).createTextRange) {
    var range = parent.window.frames['mainContent'].document.getElementById(inElement).createTextRange();
    if (range && BodyLoaded==1)
      range.execCommand('Copy');
  }else{
	var flashcopier = 'flashcopier';
    if(!document.getElementById(flashcopier)) {
      var divholder = document.createElement('div');
      divholder.id = flashcopier;
      document.body.appendChild(divholder);
    }
    document.getElementById(flashcopier).innerHTML = '';
    var divinfo = '<embed src="_clipboard.swf" FlashVars="clipboard='+encodeURIComponent(parent.window.frames['mainContent'].document.getElementById(inElement).innerHTML)+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
    document.getElementById(flashcopier).innerHTML = divinfo;
  }
  alert('Copied to Clipboard');
}


function hideTrackMenu(obj, event){
	if (!obj.contains(event.relatedTarget || event.toElement)) {
		menuTimer = setTimeout("doHideTrackMenu();", 600);
	}else{
		clearTimeout(menuTimer);
	}
}
	
function doHideTrackMenu(){
	trackmenu.style.display = 'none';
}

function refreshContent(){
	pagesrc = document.getElementById("mainContent").src;
	if( pagesrc.indexOf('?') == -1 )
		document.getElementById("mainContent").src = pagesrc + '?r=' + (Math.random() * 9999);
	else
		document.getElementById("mainContent").src = pagesrc + '&r=' + (Math.random() * 9999);
}
//

//*************************//
//**Loading Content Pages**//
//*************************//


function gotoRecs(guid, id){
	r = Math.random() * 99999;
	document.getElementById("mainContent").src = 'content/recommend.php?u=' + guid + '&id=' + id + '&r=' + r;
}

function setContentFrame(page){
	document.getElementById("mainContent").src = page;
}

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_artists.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"){
		
			document.getElementById("mainContent").src = "content/artist.php?u=" + user.guid + "&id=" + artistId + "&play=true&rand=" + random;
			
		}else if(playit == "tracks"){
			
			document.getElementById("mainContent").src = "content/artist.php?u=" + user.guid + "&id=" + artistId + "&rand=" + random;
			
		}else if(playit == "tagFav"){
			
			document.getElementById("mainContent").src = "content/artist.php?u=" + user.guid + "&id=" + artistId + "&action=tagFav" + params + "&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"){
			document.getElementById("mainContent").src = "content/" + pageName + ".php?u=" + user.guid + "&id=" + artistId + "&action=tagFav" + params + "&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;
		
		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);
		document.getElementById("mainContent").src = "content/userProfile.php?u=" + user.guid + "&id=" + userId + "&rand=" + random;
	}
}

function gotoPlaylistPage(pid, params){
    var random  = Math.round((Math.random()*32767)+1);
	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 = "";
	document.getElementById('coolStuff').style.display = 'inline';
	//showTipBox();
}

var boxOpen  = "";
var tipsOpen = "";
var tipBoxType  = "";

function showBuilderBox(pid){
	if(tipsOpen == "true"){
		hideTipBox();	
	}
	hideCoolStuff();
	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, guid){
	if( guid )
		user.guid = guid;
	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;
	}
}

function regCatch(){
	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, hasRecs, hasCart, hasDownloads){
	
	user.guid      = userGuid;
	user.username  = userName;
	user.userid    = userId;
	user.isReg     = 'Y';
	
	//flashbuilder.setGuid( userGuid );
	
	var headerHTML = '';
	var iconPath   = '';
				
	writeCookie("nxrGuid", user.guid, getExpDate(30, 0, 0), "/", "finetune.com");
	setNewFlashGuid(user.guid);
	
	subheader = parent.subheader;
	subheader.setUserInfo(userId, userGuid, userName);
	subheader.changeState('userLoggedIn');
	
	subheader.onStateChangeComplete = function(){
		if( hasRecs =='Y') {
			subheader.showNewForYou();
			subheader.showFavArtists();
		}
		if( hasCart == 'Y' ) {
			subheader.showCart();
		}
		if( hasDownloads == 'Y')  {
			subheader.showDownloads();
		}
	}
	
/*	dhtmlHistory.add( "profile", { 'guid':user.guid,
								'userId':user.userid,
								'state':'userLoggedIn',
								'hasRecs': hasRecs ? true : false,
								'hasCart': hasCart ? true : false,
								'hasDownloads': hasDownloads ? true : false } );
*/	
}

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){
   try {	
	currIconPath = path;
	document.getElementById("persistIcon").src = path;
   } catch (e) {}
}

function userLogOut(){
	user.guid     = '';
	user.token    = '';
	user.username = '';
	user.isReg    = 'N';
	uId = '';
	uGuid = '';
	deleteCookie("nxrGuid", "/", "");	
	deleteCookie("nxrGuid", "/", "finetune.com");
	deleteCookie("nxrGuid", "/", ".finetune.com");
	deleteCookie("nxrGuid", "/", "www.finetune.com");
	deleteCookie("anonGuid", "/", "finetune.com");

	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;
			
			//flashbuilder.hideBuilder();
			
			//flashbuilder.setGuid( user.guid );
			
			writeCookie("anonGuid", user.guid, getExpDate(30, 0, 0), "/", "finetune.com");
			
			parent.subheader.changeState('userLoggedOut');
			
			parent.setContentFrame('content/home.php');
		}
	}
}

function resetUserInfo(){
	var random  = Math.round((Math.random()*32767)+1);
	playlistArr       = new Array();

	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;
	}
}


function getClientHeight() {
	return f_filterResults (	
		window.frames['mainContent'].window.innerHeight ? window.frames['mainContent'].window.innerHeight : 0,
		window.frames['mainContent'].document.documentElement ? window.frames['mainContent'].document.documentElement.clientHeight : 0,
		window.frames['mainContent'].document.body ? window.frames['mainContent'].document.body.clientHeight : 0
	);
}

function getScrollTop() {
	return f_filterResults (
		window.frames['mainContent'].window.pageYOffset ? window.frames['mainContent'].window.pageYOffset : 0,
		window.frames['mainContent'].document.documentElement ? window.frames['mainContent'].document.documentElement.scrollTop : 0,
		window.frames['mainContent'].document.body ? window.frames['mainContent'].document.body.scrollTop : 0
	);
}
function f_filterResults(n_win, n_docel, n_body) {
	var n_result = n_win ? n_win : 0;
	if (n_docel && (!n_result || (n_result > n_docel)))
		n_result = n_docel;
	return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}

