$(document).ready(function() {
						   
	$("#playlist .album").editable("update.php", { 
		tooltip	: "Doubleclick to edit...",
		event	: "dblclick",
		style	: "inherit"
	});
	$("#playlist .artist").editable("update.php", { 
		tooltip	: "Doubleclick to edit...",
		event	: "dblclick",
		style	: "inherit"
	});

	$("#playlist .name .titling").editable('update.php', {
		event		: "edit",
		style		: "inherit"
	});

	//$('marquee').marquee();
	
	$('marquee').marquee('pointer').mouseover(function () {
	  $(this).trigger('stop');
	}).mouseout(function () {
	  $(this).trigger('start');
	}).mousemove(function (event) {
	  if ($(this).data('drag') == true) {
		this.scrollLeft = $(this).data('scrollX') + ($(this).data('x') - event.clientX);
	  }
	}).mousedown(function (event) {
	  $(this).data('drag', true).data('x', event.clientX).data('scrollX', this.scrollLeft);
	}).mouseup(function () {
	  $(this).data('drag', false);
	});
		
	updateSize();
	$(window).resize(function(){
		updateSize();
	});

	/*$("div.submenu").bind('click', function(){
		$(this).fadeIn("slow");
		console.log('ACTIVATE');
	},function () {
		$(this).fadeOut("slow");
		//$("#"+id).unbind('click');
		console.log('DEACTIVATE');
	});
*/
});


function displayHover(id) { 
	$("#"+id).trigger("click");
	console.log('Trigger: #'+id);
}



function updateSize(){
	var top = 230;
	var bottom = 100;
	var box_height = $(window).height() - top - bottom;
	if(box_height < 55){box_height=55;}
	$('#scrollable').height(box_height);
	$('#scroll_down').css('top',50+box_height);
}


function editTitle(id,close) { 
	console.log('Edit Name:'+id);
	$(id+' .titling').trigger("edit");
	$(id).data("disabled", "yes");
	var cnt = $(id+" a").contents()
	$(id+" a").replaceWith(cnt);

	//$(close).css('visibility','hidden');
	
}

function updateField(tothis) {
    if (tothis.value == '') {
        tothis.value = tothis.defaultValue;
    } else if (tothis.value == tothis.defaultValue) {
		tothis.value = '';
    }
}

function clearField(tothis) {
    if (tothis.value == tothis.defaultValue) {
        tothis.value = '';
    }
}

function loadPage() {
	loader = document.getElementById('loading');
	wrapper = document.getElementById('uploader');
	wrapper.style.display = 'none';
	loader.style.display = 'block';
}
/*
function TextScroll(scrollname, div_name, up_name, down_name)
{
    this.div_name = div_name;
    this.name = scrollname;
    this.scrollCursor = 0;
    this.speed = 5;
    this.timeoutID = 0;
    this.div_obj = null;
    this.up_name = up_name;
    this.dn_name = down_name;


	{
        if (document.getElementById)
		{
			div_obj = document.getElementById(this.div_name);
            
			if (div_obj) {
                this.div_obj = div_obj;
                this.div_obj.style.overflow = 'hidden';
            }
            
			div_up_obj = document.getElementById(this.up_name);
            div_dn_obj = document.getElementById(this.dn_name);
            
			if (div_up_obj && div_dn_obj) {
                div_up_obj.onmouseover = function (TextScrollObj) { return function () { TextScrollObj.scrollUp(); }} (this);
				div_up_obj.onmouseout = function (TextScrollObj) { return function () { TextScrollObj.stopScroll(); }} (this); 
				div_dn_obj.onmouseover = function (TextScrollObj) { return function () { TextScrollObj.scrollDown(); }} (this); 
				div_dn_obj.onmouseout = function (TextScrollObj) { return function () { TextScrollObj.stopScroll(); }} (this);
            }
			
        }
    }

	this.stopScroll = function() {
        clearTimeout(this.timeoutID);
    }

	this.scrollUp = function() {
        if (this.div_obj) {
            this.scrollCursor = (this.scrollCursor - this.speed) < 0 ? 0 : this.scrollCursor - this.speed;
            this.div_obj.scrollTop = this.scrollCursor;
            this.timeoutID = setTimeout(this.name + ".scrollUp()", 60);
        }
    }

	this.scrollDown = function() {
        if (this.div_obj) {
            this.scrollCursor += this.speed;
            this.div_obj.scrollTop = this.scrollCursor;
            this.timeoutID = setTimeout(this.name + ".scrollDown()", 60);
        }
    }

	this.resetScroll = function() {
        if (this.div_obj) {
            this.div_obj.scrollTop = 0;
            this.scrollCursor = 0;
        }
    }

}
*/


// NEW function
function TextScroll(scrollname, div_name, up_name, down_name)
{
    this.div_name = div_name;
    this.name = scrollname;
    this.scrollCursor = 0;
    this.speed = 5;
    this.timeoutID = 0;
    this.div_obj = null;
    this.up_name = up_name;
    this.dn_name = down_name;

	this.stopScroll = function() {
        clearTimeout(this.timeoutID);
    };

	this.scrollUp = function() {
        if (this.div_obj) {
            this.scrollCursor = (this.scrollCursor - this.speed) < 0 ? 0 : this.scrollCursor - this.speed;
            this.div_obj.scrollTop = this.scrollCursor;
            this.timeoutID = setTimeout(this.name + ".scrollUp()", 60);
        }
    };

	this.scrollDown = function() {
        if (this.div_obj) {
            this.scrollCursor += this.speed;
            this.div_obj.scrollTop = this.scrollCursor;
            this.timeoutID = setTimeout(this.name + ".scrollDown()", 60);
        }
    };

	this.resetScroll = function() {
        if (this.div_obj) {
            this.div_obj.scrollTop = 0;
            this.scrollCursor = 0;
        }
    };

	
        if (document.getElementById)
		{
			div_obj = document.getElementById(this.div_name);
            
			if (div_obj) {
                this.div_obj = div_obj;
                this.div_obj.style.overflow = 'hidden';
            }
            
			div_up_obj = document.getElementById(this.up_name);
            div_dn_obj = document.getElementById(this.dn_name);
            
			if (div_up_obj && div_dn_obj) {
                div_up_obj.onmouseover = function (TextScrollObj) { return function () { TextScrollObj.scrollUp();};} (this);
				div_up_obj.onmouseout = function (TextScrollObj) { return function () { TextScrollObj.stopScroll();};} (this);
				div_dn_obj.onmouseover = function (TextScrollObj) { return function () { TextScrollObj.scrollDown();};} (this);
				div_dn_obj.onmouseout = function (TextScrollObj) { return function () { TextScrollObj.stopScroll();};} (this);
            }
			
        }
    
}


function displayNow(id) {
	$('#' + id).toggle();
}	
function keepactive(id) {
	document.getElementById(id).style.visibility = 'visible';
}
function songAddForm(title,time,url,uid) {
	document.getElementById('addnewsong').style.visibility='visible';
	url = "/add-song.php?title="+encodeURI(title)+"&time="+time+"&url="+encodeURI(url)+"&uid="+uid;
	$("#smessage").load(url);
}
function playlistAdd(userid,songid,playlistid) {
	$("#message").load("/loading.html");	
	$("#message").load("/add-playlist.php?sid="+songid+"&uid="+userid+"&plid="+playlistid);
}
function libraryAdd(userid,songid) {
	$("#message").load("/loading.html");	
	$("#message").load("/add-playlist.php?sid="+songid+"&uid="+userid+"&plid=library");
}
function playlistNew(userid,title) {
	$("#errormessage").load("/loading.html");
	$("#errormessage").load("/add-new.php?title="+encodeURI(title)+"&uid="+userid);
}
function dropDownTimeout(id) {
	setTimeout(document.getElementById(id).style.visibility = 'hidden',6000);
}		
function deletePlaylist(id) {
	var answer = confirm("Delete this playlist?");
	if (answer){
		$.get("/update.php?delete=yes&playlist="+id, function(data){
			if (data == 'deleted') {
				//window.location="http://moof.com/";		
				$("#p"+id).fadeOut("slow");
			} else {
				alert("Error upon delete, try again");
			}
		});		
	}
}
function deleteSong(songid,sid) {
	$.get("/update.php?delete=yes&songid="+songid+"&id="+sid, function(data){
		if (data == 'deleted') {
			//window.location="http://moof.com/";		
			$("#"+sid).fadeOut("slow");
		} else {
			alert("Error upon delete, try again");
		}
	});
}

function searchLoadYt(keywords,id,userid) {
	if($('#'+id).data("disabled") == 'yes'){
		$.get('/load-song.php?userid=' + userid + '&keywords=' + keywords + '&id='+id, function(data){
			video = data.split('?')[1].split('&')[0].split('v=')[1];
			document.getElementById('yplayer').loadVideoById(video);
			document.getElementById('tracktitle').innerHTML = keywords;
			document.title = keywords + ' on moof.com';
			document.getElementById('play').style.backgroundImage='url(./images/button-pause.gif)';
			//console.log("Play State: Loading from searchLoadYt");
		});	
	}
}
function loadByUrl(url){
	video = url.split('?')[1].split('&')[0].split('v=')[1];
	document.getElementById('yplayer').loadVideoById(video);	
}
function loadPlaylist(userid,playlistid) {
	$("#playlist").load("/load-playlist.php?uid="+userid+"&plid="+playlistid);
}







//XMLHttpRequest class function
function datosServidor() {
};
datosServidor.prototype.iniciar = function() {
	try {
		// Mozilla / Safari
		this._xh = new XMLHttpRequest();
	} catch (e) {
		// Explorer
		var _ieModelos = new Array(
		'MSXML2.XMLHTTP.5.0',
		'MSXML2.XMLHTTP.4.0',
		'MSXML2.XMLHTTP.3.0',
		'MSXML2.XMLHTTP',
		'Microsoft.XMLHTTP'
		);
		var success = false;
		for (var i=0;i < _ieModelos.length && !success; i++) {
			try {
				this._xh = new ActiveXObject(_ieModelos[i]);
				success = true;
			} catch (e) {
			}
		}
		if ( !success ) {
			return false;
		}
		return true;
	}
}

datosServidor.prototype.ocupado = function() {
	estadoActual = this._xh.readyState;
	return (estadoActual && (estadoActual < 4));
}

datosServidor.prototype.procesa = function() {
	if (this._xh.readyState == 4 && this._xh.status == 200) {
		this.procesado = true;
	}
}

datosServidor.prototype.enviar = function(urlget,datos) {
	if (!this._xh) {
		this.iniciar();
	}
	if (!this.ocupado()) {
		this._xh.open("GET",urlget,false);
		this._xh.send(datos);
		if (this._xh.readyState == 4 && this._xh.status == 200) {
			return this._xh.responseText;
		}
		
	}
	return false;
}


var urlBase = "update.php";
var formVars = "";
var changing = false;


function fieldEnter(campo,evt,idfld) {
	evt = (evt) ? evt : window.event;
	if (evt.keyCode == 13 && campo.value!="") {
		elem = document.getElementById( idfld );
		remotos = new datosServidor;
		nt = remotos.enviar(urlBase + "?fieldname=" +encodeURI(elem.id)+ "&content="+encodeURI(campo.value)+"&"+formVars,"");
		//remove glow
		noLight(elem);
		elem.innerHTML = nt;
		changing = false;
		return false;
	} else {
		return true;
	}


}

function fieldBdlur(campo,idfld) {
	if (campo.value!="") {
		elem = document.getElementById( idfld );
		remotos = new datosServidor;
		nt = remotos.enviar(urlBase + "?fieldname=" +escape(elem.id)+ "&content="+escape(campo.value)+"&"+formVars,"");
		elem.innerHTML = nt;
		changing = false;
		return false;
	}
}

//edit field created
function editBox(actual) {
	//alert(actual.nodeName+' '+changing);
	if(!changing){
		width = widthEl(actual.id) + 20;
		height =heightEl(actual.id) + 2;

		if(height < 40){
			if(width < 100)	width = 150;
			actual.innerHTML = "<input id=\""+ actual.id +"_field\" style=\"width: "+width+"px; height: "+height+"px;\" maxlength=\"254\" type=\"text\" value=\"" + actual.innerHTML + "\" onkeypress=\"return fieldEnter(this,event,'" + actual.id + "')\" onfocus=\"highLight(this);\" onblur=\"noLight(this); return fieldBlur(this,'" + actual.id + "');\" />";
		}else{
			if(width < 70) width = 90;
			if(height < 50) height = 50;
			actual.innerHTML = "<textarea name=\"textarea\" id=\""+ actual.id +"_field\" style=\"width: "+width+"px; height: "+height+"px;\" onfocus=\"highLight(this);\" onblur=\"noLight(this); return fieldBlur(this,'" + actual.id + "');\">" + actual.innerHTML + "</textarea>";
		}
		changing = true;
	}

		actual.firstChild.focus();
}



//find all span tags with class editText and id as fieldname parsed to update script. add onclick function
function editbox_init(){
	if (!document.getElementsByTagName){ return; }
	var spans = document.getElementsByTagName("span");

	// loop through all span tags
	for (var i=0; i<spans.length; i++){
		var spn = spans[i];

        	if (((' '+spn.className+' ').indexOf("editText") != -1) && (spn.id)) {
			spn.onclick = function () { editBox(this); }
			spn.style.cursor = "pointer";
			spn.title = "Double click to edit!";
       		}

	}


}

//crossbrowser load function
function addEvent(elm, evType, fn, useCapture)
{
  if (elm.addEventListener){
    elm.addEventListener(evType, fn, useCapture);
    return true;
  } else if (elm.attachEvent){
    var r = elm.attachEvent("on"+evType, fn);
    return r;
  } else {
    alert("Please upgrade your browser to use full functionality on this page");
  }
}

//get width of text element
function widthEl(span){

	if (document.layers){
	  w=document.layers[span].clip.width;
	} else if (document.all && !document.getElementById){
	  w=document.all[span].offsetWidth;
	} else if(document.getElementById){
	  w=document.getElementById(span).offsetWidth;
	}
return w;
}

//get height of text element
function heightEl(span){

	if (document.layers){
	  h=document.layers[span].clip.height;
	} else if (document.all && !document.getElementById){
	  h=document.all[span].offsetHeight;
	} else if(document.getElementById){
	  h=document.getElementById(span).offsetHeight;
	}
return h;
}

function highLight(span){
            //span.parentNode.style.border = "2px solid #D1FDCD";
            //span.parentNode.style.padding = "0";
            span.style.border = "1px solid #54CE43";
}

function noLight(span){
        //span.parentNode.style.border = "0px";
        //span.parentNode.style.padding = "2px";
        span.style.border = "0px"; 
}

//sets post/get vars for update
function setVarsForm(vars){
	formVars  = vars;
}

addEvent(window, "load", editbox_init);
// #### TEST #####
// ##### ADDITIONS #####
function load_song (song_id)
{
	playing_song_id = song_id;
	$.getJSON('/load/song/' + song_id, function(data)
	{
		$('#yplayer').loadVideoById(data.youtube);
		$('#tracktitle').html (data.keywords);
		$(document).attr('title', data.keywords + ' on moof.com');
		$('#play').css('backgroundImage', 'url(./images/button-pause.gif)');
	});
}

function delete_song (song_id)
{
	$('#delete_song').children('input').attr('disabled', 'true');
	$.getJSON('./delete/song/' + song_id, function (data)
	{
		if (data.success == 'true')
		{
			$('#song_' + song_id).slideUp('slow', function () { $(this).remove(); });
			$('#delete_song').hide();
		}
		else
		{
			$('#delete_song').slideUp();
			alert(data.message);
		}
		$('#delete_song').children('input').attr ('disabled', '');
	});
}

function delete_playlist (playlist_id)
{
	$('#delete_playlist').children('input').attr('disabled', 'true');
	$.getJSON('./delete/playlist/' + playlist_id, function (data)
	{
		if (data.success == 'true')
		{
			$("#add_playlist_playlist").children("option").each(function(item)
			{
				if ($(this).val() == playlist_id)
				{
					$(this).remove();
				}
			});
			$('#playlist_' + playlist_id).slideUp().remove();
		}
		else
		{
			alert(data.message);
		}
		$('#delete_playlist').slideUp();
		$('#delete_playlist').children('input').attr ('disabled', '');
	});
}

function add_playlist (playlist_name)
{
	$('#playlist_add_new').children('input').attr('disabled', 'true');
	$.post('./add/playlist', {playlist : playlist_name}, function (data)
	{
		if (data.success == 'true')
		{
			$('#my_playlists').append(data.code);
			$('#add_playlist_playlist').append(data.option);
		}
		else
		{
			alert(data.message);
		}
		$('#playlist_add_new').slideUp();
		$('#playlist_add_new').children('input').attr('disabled', '');
	}, 'json');
}

function add_song (option_song_id, option_playlist_id)
{
	$('#add_playlist').children('input').attr('disabled', 'true');
	$.post('./add/song', {playlist_id : option_playlist_id, song_id : option_song_id}, function (data)
	{
		alert(data.message);
		$('#add_playlist').slideUp();
		$('#add_playlist').children('input').attr('disabled', '');
	}, 'json');
}

function update_song (option_song_id, option_title, option_artist, option_album)
{
	$('#update_song').children('input').attr('disabled', 'true');
	$.post('./update/song', {song_id : option_song_id, title : option_title, artist : option_artist, album : option_album}, function (data)
	{
		if (data.success == 'true')
		{
			$('#song_' + option_song_id + '_title').html (option_title);
			$('#song_' + option_song_id + '_artist').html (option_artist);
			$('#song_' + option_song_id + '_album').html (option_album);
		}
		else
		{
			alert(data.message);
		}
		$('#update_song').slideUp();
		$('#update_song').children('input').attr('disabled', '');
	}, 'json');
}