var gridMode = 'playlist';
var searchKeywords;
var list_type = 'song';
var list_id = 1;
var contentFlow = null;
var flowInited;
var lastH;
var firstLoad = true;
var firstLoadGrid = true;
var flowScript;
function displayHover(id) { 
	$("#"+id).trigger("click");
	console.log('Trigger: #'+id);
}
var loader = {
	show: function() {
		$('#loadCircle').show();
	},
	hide: function() {
		$('#loadCircle').delay(1000).fadeOut(500);
	}
};

var display = {
	delay: 5,
	content: [],
	idle:true,
	load: function() {
		text = $("#title").html();
		display.content = text.split(",");
		msg = "Hello there, " + display.content[1] + "! Welcome!";
		display.content[2] = "Your permanent link is: <a href='./"+display.content[1]+ "' title='Permanent Link'>"+base_url+display.content[1]+"</a>";
		display.content[1] = msg;
	},
	start: function() {
		if(display.idle){
			$("#title")
			.html(display.content[0])
			.animate({opacity:'1'},1000)
			.delay(2000)
			.animate({opacity:'0'},1000)
			if(display.idle){
			$('#title').queue(function() {
				$(this).dequeue();
				$('#title')
				.html(display.content[1])
				.animate({opacity:'1'},1000)
				.delay(1000)
				if(display.idle){
				$(this).queue(function() {
					$(this).dequeue();
					$('#artist')
					.animate({opacity:'0'},100)
					.html(display.content[2])
					.animate({opacity:'1'},1000)
					.delay(display.delay * 1000)
					if(display.idle){
					$('#artist').queue(function() {
						$(this).dequeue();
						$('#title').animate({opacity:'0'},500)
						$('#artist').animate({opacity:'0'},500)
						if(display.idle){
						$(this).queue(function() {
								$(this).dequeue();
								display.start();
						})}
					})}
				})}
			})}
		}
		$("span.img").css({ 
			position: "relative",
			margin: "-1px auto 0 auto" ,
			zIndex: "910",
			border: "1px solid #bbb",
			display: "block",
			width: "31px",
			height: "31px",
			overflow: "hidden",
			background: "url(./avatars/13992.gif) no-repeat"
			});
		$("span.img").css("-moz-border-radius","5px");
		$("span.img").css("-webkit-border-radius","5px");
		
	},
	stop: function() {
		display.idle=false;
		$("#loadCircle").css("top","-24px");
		$('#title').stop();
		$('#title').dequeue();
		$('#artist').stop();
		$('#artist').dequeue();
		$('#info span').css("margin-top","2px");
		$('#title')
		.animate({opacity:'1'},800)
		$('#artist')
		.animate({opacity:'1'},800)
		$('#center')
		.animate({opacity:'1'},800)
		$('#center *').animate({opacity:'1'},800)
	}
};

var video = {
		working: false,
		state: -1,
		timer: 0,
		hidden:false,
		show:function(){
				if(video.state==-1 && !video.working){
					$('#jwplay1').css("top",170);
					//$('#yWrapper').height(189);
					video.timer = setInterval(function(){
						if(parseInt($('#jwplay1').css("top"))>20) {
								$('#jwplay1').css("top",parseInt($('#jwplay1').css("top"))-10);
								$('#now_playin').css("top",parseInt($('#jwplay1').css("top"))-20);
								$('#yWrapper').css("height",parseInt($('#yWrapper').height())+12);
								video.working = true;
							}
						else{
							clearInterval(video.timer);
							$('#jwplay1').css("top",18);
							video.working=false;
							video.state=1;
							$('#yWrapper').height(189);
							updateSize();
						}
					},10);
					$('#toggle').css("background-position","0px 0px");
				}
		},
		hide:function(){
				if(video.state==1 && !video.working){
					video.timer = setInterval(function(){
						if(parseInt($('#jwplay1').css("top"))<170) {
								$('#jwplay1').css("top",parseInt($('#jwplay1').css("top"))+10);
								$('#now_playin').css("top",parseInt($('#jwplay1').css("top"))+20);
								$('#yWrapper').css("height",parseInt($('#yWrapper').height())-15);
								video.working = true;
							}
						else{
							clearInterval(video.timer);
							$('#jwplay1').css("top",170);
							$('#yWrapper').height(0);
							video.working=false;
							video.state=-1;
							updateSize();
						}
					},10);
					$('#toggle').css("background-position", "0px -24px");
			
				}
		}
	};
	
/* moved in document.ready */
//window.onbeforeunload = saveVideoState;

 function saveVideoState()  
 {
	if ($.cookie("videoState")) {
		$.cookie("videoState", null);
	}
	$.cookie("videoState", video.state, { expires: 31 });
 } 
function gridView(){
	$("#view2_tab").css("margin-left",0);
	var iW = $(".gridHolder").eq(0).width(); //width of a single image
	var cW = $("#view2_tab").width(); //width of the container where images will be held
	var rLn = Math.floor(cW / iW); //how many images will be able to show on 1 row
	var rW = rLn * iW; //number of images per row multiplied by image width
	var gridC = $("#view2_tab").get(0);
	if(gridC.clientHeight < gridC.scrollHeight )
		cW-=16;
	
	var newM = Math.floor((cW - rW)/(rLn));
	$(".gridHolder").css("margin-left",newM);

	var nrW = rW+rLn*newM;
	var diff = cW - nrW;
	
	var eqM = (diff-newM)/2;
	$("#view2_tab").css("margin-left",eqM);
}

var content_height;
function updateSize(){
	//var top = 230;
	//var bottom = 100;
	//var box_height = $(window).height() - 115;
	//if(box_height < 100){box_height=100;}
	content_height=(($(window).height() - 96)>200)? $(window).height() - 113:200;
	$('#scrollable').height(content_height-$('#yWrapper').height()-12);
	$('#sidebar').height(content_height);
	//$('#transparentOverlay').height(content_height+81);
	if($("#view3_tab").css("visibility")=="hidden") {
		$('.bDiv').height(content_height-11-31);
	} else {
		$('.bDiv').height(content_height-11-223-31);
	}
	if($("#view2_tab").css("visibility")=="visible"){
		$("#view2_tab").css("height",content_height);
		gridView();
	}
	$('#footer').width($('#container').width());
	$('#fill').width($('#container').width());
	$('#trackinfo').width($(window).width()-627);
	$('#progress').width($(window).width()-725);
	$('#center').width($('#progress').width()+62);
	if($("#title").attr('title')!='') $("#title").html($("#title").attr('title'));
	if(!$.browser.msie) $("#title").textTruncate($("#title").width()-40);
	if(activeIE){
		$("#trackinfo").backgroundCanvasPaint(paintTrack,7,theme._other);
	}
	if(firstLoad){
		$('#wrapper').animate({opacity:'1'},1000);
		$('#fullPageLoader').show();
		firstLoad = false;
	}
}

function loadTabs() {
	if (!checkTabs()) {
		loader.show();
		var gate = base_url + 'ajax.php?do=load_tabs';
		$.getJSON(gate, function(data) {
			if (data.success) {
				$('#content').html(data.content);
			}
		});
		loader.hide();
	}
}

function checkTabs() {
	if ($('.flexigrid').get(0)) {
		return true
	} else {
		return false;
	}
}

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 = 'auto';
            }
            
			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';
			$('#play img').attr('src', './images/pause.png');
			$('#play img').css('margin-left', '10px');
			
			//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;
  } 
}*/

//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;
}


/*
 * (ivan) I can't find anything related to it;
 */
/*addEvent(window, "load", editbox_init);*/


// ##### ADDITIONS #####
function load_song (song_id)
{
	loader.show();
	$('#perma-link').empty();
	$.getJSON('/load/song/' + song_id, function(data)
	{
		if (data.status == 'working') {
			player.songId = song_id;
			player.handle.sendEvent('LOAD', data.url);
			$('#perma-link').html('<a href="' + data.url + '" target="_blank">Link to Video Source</a>');
		} else if (data.status == 'broken') {
			$('#row' + song_id).addClass('brokenSong');
			player.nextSong();
		}
		var tmpContainer = $('#row' + song_id + ' .cell_8 div');
		var tmpText = parseInt($(tmpContainer).text()) + 1;
		$(tmpContainer).text(tmpText);
		if (data.thumb) {
			$('#grid' + song_id + ' img').attr('src', data.thumb);
//			$('#flow' + song_id + ' img').attr('src', data.thumb);
		}
	});
	loader.hide();
}

function rate_song (id, value)
{
	loader.show();
	$.getJSON(base_url + 'ajax.php?do=rateSong&id=' + id + '&value=' + value, function(o) {
		if (o.success) {

		} else {
			alert(o.message);
		}
	});
	loader.hide();
}

function reportBrokenVideo(song_id) {
	loader.show();
	$.getJSON('./ajax.php?do=reportbroken&id=' + song_id, function(data)
	{
		if (data.success) {
			$('#row' + song_id).addClass('brokenSong');
			$('#row' + song_id + ' .playstatus').attr('checked', false).change();
		}
	});
	loader.hide();
}

function loadItemsIntoViews(gridMode, list_type, list_id, params) {
	loader.show();
	if (gridMode == 'playlist') {
		$('.fplaylist').flexToggleCol(4, true);
		$('.fplaylist').flexToggleCol(5, true);
		$('.fplaylist').flexToggleCol(6, false);
		var gate = base_url + 'ajax.php?do=' + list_type + '&id=' + list_id + '&format=gridview';
	} else {
		$('.fplaylist').flexToggleCol(4, false);
		$('.fplaylist').flexToggleCol(5, false);
		$('.fplaylist').flexToggleCol(6, true);
		var gate = base_url + 'ajax.php?do=' + list_type + '&keywords=' + list_id + '&format=gridview';
	}
	$.post(
		gate,
		params,
		function(data)
		{
			var cflow = ContentFlowGlobal.Flows[0];
			var contentFlow = $('#contentFlow .flow');
			var hiddenFlow = $('#hiddenFlowContainer');
			var viewTab = $('#view2_tab');
			if (flowInited) {
				var cflowLength = cflow.items.length;
				for (i = 0; i < cflowLength; i++) {
					cflow.rmItem(0);
				}
			} else {
				contentFlow.empty();
			}
			hiddenFlow.empty();
			viewTab.empty();
			for (key = 0; key < data.rows.length; key++) {
				var val = data.rows[key];
				var id = val.id;
				val.thumb = (val.thumb != '') ? val.thumb : base_url + 'themes/default/images/noCover.png';
				viewTab.append("<div class='gridHolder' id='grid" + val.id + "'><div class='gridFrame'><div class='artCrop'><img src='" + val.thumb + "' height='120' /><span></span></div></div><div class='gridTitle' title='" + val.title + "'>" + val.title + "</div><div>" + val.duration + "</div></div>\n");
				if (flowInited) {
					hiddenFlow.append("<div class='item' id='flow" + val.id + "'><img class='content' src='" + val.thumb + "' /><div class='caption'>" + val.title + "</div></div>\n");
					var elementId = document.getElementById("flow" + val.id);
					cflow.addItem(elementId, 'last');
				} else {
					contentFlow.append("<div class='item' id='flow" + val.id + "'><img class='content' src='" + val.thumb + "' /><div class='caption'>" + val.title + "</div></div>\n");
				}
			}
			if (flowInited) {
				cflow.moveTo(0);
			}

			$('.gridTitle').each(function() {
				$(this).css( {
					whiteSpace:"nowrap",
					overflow:"hidden",
					textAlign:"center"
				});
				$(this).next('div').css( {
					whiteSpace:"nowrap",
					overflow:"hidden",
					textAlign:"center"
				});
				if(this.clientWidth < this.scrollWidth)
						$(this).text($(this).text().substr(0,12)+"...")
			});
			$('.artCrop').children('img').each(function() {
				if($(this).width()>120)
					$(this).css('margin-left',(120-$(this).width())/2)
			});
			
			$('.artCrop span').hide();
			$('.gridHolder').hover(function() {
					$(this).find('span').show();
				}, function() {
					$(this).find('span').hide();
				});
			updateSize();
			updateSize();

			//if (firstLoadGrid) {
				//$('#views a.view3').click();
				//firstLoadGrid = false;
			//}
			$('.fplaylist tr:eq(0)').mousedown();
		},
		'json'
	);
	loader.hide();
}

function setPlaylistTotals() {
	loader.show();
	$.getJSON(base_url + 'ajax.php?do=' + list_type + '&id=' + list_id + '&format=totals', function(data)
	{
		$('#playlist-info').text(data.totalSongs + ' song(s), ' + data.totalDuration + ' hours');
	});
	loader.hide();
}

function triggerContentFlow() {
/*
	ContentFlowGlobal.init();
	ContentFlowGlobal.onloadInit();
	cflow = new ContentFlow('flow');
// 	cflow.Flow = $('#contentFlow').get(0);
// 	cflow.items = [];
	$.each($('#hiddenFlowContainer .item'), function(key, val) {
		cflow.addItem($(val).get(0), 'last');
	});
*/
}

function load_url (source, url)
{
	loader.show();
	$.getJSON('/load/url/' + source + '/' + url, function(data)
	{
		if (player.handle != undefined) {
			player.handle.sendEvent('LOAD', data.url);
		}
	});
	loader.hide();
}

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)
{
	if (playlist_name == '') {
		playlist_name = $('#playlist_add_new_name').attr('value');
		if (playlist_name == '') {
			$('#osx-modal-data input[name=playlist]').attr('value');
		}
	}
	$('#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');
}
$(window)
	.unbind('beforeunload')
	.bind('beforeunload', function(e) {
		saveVideoState();
		if (player.state == 'BUFFERING' || player.state == 'PLAYING') {
			  return "Refrain.com will stop playback ...";
		} else {
			$(window).unbind('beforeunload');
		}
	});

$(document).ready(function(){
	if($("#contentFlow").css("height")) {
		$("#contentFlow").css("height",'213px');
		$("#contentFlow").css("padding-top",'10px');
	}
	$('#view1_tab').css("opacity",'0');
	$('#title').css("opacity",'0');
	$('#artist').css("opacity",'0');
	$('#center ').css("opacity",'0');
	$('#center *').css("opacity",'0');
	
	$('#title').css("margin-top","4px");//4px
	$('#artist').css("margin-top","7px");//7px
	$('#info span').css("height","11px");
	$(window).resize(function(){
		updateSize();
		updateSize();
		if($(window).height()<400){
			if(!video.hidden){
				video.hide();
			}
		video.hidden = true;
		}
		else{
			if(video.hidden){
				video.show();
				video.hidden=false;
			}
		}
	});
	
	
	// ##### LOAD SONGS #####
	load_results();

	$('a').click (function()
	{
		if ($(this).attr('href') == '#')
		{
			return false;
		}
	});

	$('html, body').animate({scrollTop:0}, 'slow');
	$(window).scroll(function()
	{
		if ($(window).scrollTop() > $(document).height() - $(window).height() - 400)
		{
			load_results ();
		}
	});


	$("#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"
	});


	/*
	bottom controls
	*/
	 $('#toggle').click(function(){
		if(!video.hidden){
			(video.state==-1)?video.show():video.hide();
		}
	});
	
	/* FLEXIGRID */
	if (gridMode == 'playlist') {
		var gate = base_url + 'ajax.php?do=' + list_type + '&id=' + list_id + '&format=flexigrid';
		$('.fplaylist')
			.flexigrid(
			{
				dataMode: gridMode,
				height: 500, //default height
				width: 'auto', //auto width
				striped: false, //apply odd even stripes
				novstripe: false,
				minwidth: 30, //min width of columns
				minheight: 80, //min height of columns
				resizable: false, //resizable table
				url: gate, //ajax url
				method: 'POST', // data sending method
				dataType: 'json', // type of data loaded
				errormsg: 'Connection Error',
				usepager: true, //
				nowrap: true, //
				page: 1, //current page
				total: 0, //total pages
				useRp: true, //use the results per page select box
				rp: 50, // results per page
				rpOptions: [10,25,50,100],
				title: false,
				pagestat: 'Displaying {from} to {to} of {total} items',
				procmsg: 'Processing, please wait ...',
				nomsg: 'No items',
				minColToggle: 1, //minimum allowed column to be hidden
				showToggleBtn: true, //show or hide column toggle popup
				hideOnSubmit: false,
				singleSelect: true,
				autoload: true,
				blockOpacity: 0,
				onSuccess: function() {
					var params = {
						page: this.page,
						rp: this.rp,
						sortname: this.sortname,
						sortorder: this.sortorder
					};
					loadItemsIntoViews(gridMode, list_type, list_id, params);
					setPlaylistTotals();
				},
				onSubmit: false, // using a custom populate function
				cookies: true,
				tableId: '.fplaylist',
				colMove: true,

				sortname: 'id',
				sortorder: 'asc',
				query: '',
				qtype: '',

				colModel : [
					{display: 'Play', name : 'play', width : 32, sortable: false, align: 'center'},
					{display: '0...9', name : 'id', width : 32, sortable: true, align: 'left'},
					{display: 'Name', name : 'name', width : 320, sortable: true, align: 'left'},
					{display: 'Time', name : 'time', width : 48, sortable: true, align: 'left'},
					{display: 'Artist', name : 'artist', width : 240, sortable: true, align: 'left'},
					{display: 'Album', name : 'album', width : 240, sortable: true, align: 'left'},
					{display: 'Description', name : 'description', width : 240, sortable: true, align: 'left', hide:true},
					{display: 'Rating', name : 'rating', width : 76, sortable: true, align: 'left'},
					{display: 'Counter', name : 'counter', width : 52, sortable: true, align: 'center'},
					{display: 'Actions',  width : 60, sortable: false, align: 'center'}
				]
			}
		);
	} else {
		var gate = base_url + 'ajax.php?do=search&keywords=' + searchKeywords;
		$('.fplaylist')
			.flexigrid(
			{
				dataMode: 'search',
				height: 500, //default height
				striped: false, //apply odd even stripes
				resizable: false, //resizable table
				url: gate, //ajax url
				method: 'POST', // data sending method
				dataType: 'json', // type of data loaded
				showToggleBtn: false, //show or hide column toggle popup
				hideOnSubmit: false,
				singleSelect: true,
				sortname: 'id',
				sortorder: 'asc',
				cookies: true,
				tableId: '.fplaylist',
				colMove: true,

				colModel : [
					{display: 'Name', name : 'name', width : 320, align: 'left'},
					{display: 'Time', name : 'time', width : 48, align: 'left'},
					{display: 'Source', name : 'source', width : 1, align: 'left'},
					{display: 'URL', name : 'url', width : 1, align: 'center'},
					{display: 'Actions',  width : 60, align: 'center'}
				]
			}
		);
	}

	/*
	 * SLIDER
	 */
	$('.slider_time_bar')
		.slider({
		  handle: '.slider_time_handle',
		  animate: false,
		  min: {x:0, y:0},
		  max: {x:100, y:100}
		});
	$('.slider_vol_bar').slider({
		  handle: '.slider_vol_handle',
		  animate: false,
		  min: {x:0, y:0},
		  max: {x:100, y:100}
		});

	var attributes = {};
	var params = {};
	var flashvars = {};

	/* JW PLAYER INIT */
	attributes = {
			id:"jwplay1",
			name:"jwplay1"
	}
	params = {
			allowfullscreen:"true",
			allowscriptaccess:"always",
			wmode:"transparent"
	}
	flashvars = {
			autostart: "true",
			controlbar: "none",
//			volume: "70",
//			mute: "false",
			playerready: "playerReadyCallback",
			image: base_url + "player/preview.jpg"
	}
	if ($('#jwplayer').attr('id')) {
		swfobject.embedSWF(base_url + "player/player.swf", "jwplayer", "223", "171", "9.0.115", false, flashvars, params, attributes);
	}

	/* VISUALIZER INIT */
/*
	attributes = {
			id:"jwplay2",
			name:"jwplay2"
	}
	params = {
			allowfullscreen:"true",
			allowscriptaccess:"always",
			wmode:"transparent"
	}
	flashvars = {
			autostart: "true",
			controlbar: "none",
			volume: "70",
			plugins: base_url + "player/plugins/revolt/revolt.swf",
			file: "http://keepvid.com/?url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dc2UZ2EfXCac%26feature%3Dgrec"
	}
	if ($('#jwvisualization').attr('id')) {
		swfobject.embedSWF(base_url + "player/player.swf", "jwvisualization", "470", "320", "9.0.115", false, flashvars, params, attributes);
	}
*/
	/*
	 * BUTTONS
     */
	$('#play')
		.unbind('click')
		.bind('click', function(e) {
			e.preventDefault();
			if ($('.dblClicked').length == 0) {
				player.nextSong();
				return false;
			}
			if (player.state == 'BUFFERING' || player.state == 'PLAYING') {
				player.sendEvent('PLAY', false);
			} else {
				player.sendEvent('PLAY', true);
			}
			return false;
		});

	$('#contentFlow .flow .active')
		.live('click', function(e) {
			e.preventDefault();
			var id = $(this).attr('id').replace('flow', '');
			player.playId(id);
			return false;
		});

	$('.next')
		.unbind('click')
		.bind('click', function(e) {
			e.preventDefault();
			player.nextSong();
			return false;
		});
	$('.previous')
		.unbind('click')
		.bind('click', function(e) {
			e.preventDefault();
			player.prevSong();
			return false;
		});
	$('#volume-mute')
		.unbind('click')
		.bind('click', function(e) {
			e.preventDefault();
			player.sendEvent('VOLUME', 1);
			$('.slider_vol_bar').slider('moveTo', 1);
			return false;
		});
	$('#volume-loud')
		.unbind('click')
		.bind('click', function(e) {
			e.preventDefault();
			player.sendEvent('VOLUME', 100);
			$('.slider_vol_bar').slider('moveTo', 100);
			return false;
		});

	if (player.repeat) {
		$('#repeat_p').css("background-position","0px 0px");
	}
	if (player.shuffle) {
		$('#shuffle_p').css("background-position","0px 0px");
	}
	$('#repeat_p')
		.unbind('click')
		.bind('click', function(e) {
			e.preventDefault();
			if (player.repeat) {
				$(this).css("background-position", "0px -24px");
				player.repeat = false;
			} else {
				$(this).css("background-position","0px 0px");
				player.repeat = true;
			}
			return false;
		});
	$('#shuffle_p')
		.unbind('click')
		.bind('click', function(e) {
			e.preventDefault();
			if (player.shuffle) {
				$(this).css("background-position", "0px -24px");
				player.shuffle = false;
			} else {
				$(this).css("background-position","0px 0px");
				player.shuffle = true;
			}
			return false;
		});

	$('.flexigrid .playstatus')
		.live('change' , function(e) {
			if (gridMode == 'playlist') {
				loader.show();
				checked = $(this).attr('checked');
				id = $(this).attr('value');
				$.getJSON('./ajax.php?do=statuschange&type=' + list_type + '&status=' + checked + '&id=' + id + '&playlist_id=' + list_id, function(o) {
					if (o.success) {

					} else {
						alert('Problem while marking the item.');
					}
				});
				loader.hide();
			}
		});

	$('.removeSong')
		.live('click', function(e) {
			e.preventDefault();
			loader.show();
			var id = $(this).attr('id').replace('remove_', '');
			$.getJSON(base_url + 'ajax.php?do=delete&type=song&id=' + id, function(o) {
				if (o.success) {
					if ($('#row' + id).hasClass('dblClicked') == true) {
						player.nextSong();
					}
					$('#row' + id).remove();
					$('#flow' + id).remove();
					$('#grid' + id).remove();
					setPlaylistTotals();
				} else {
					alert(o.message);
				}
			});
			loader.hide();
			return false;
		});

	$('.addSong')
		.live('click', function(e) {
			e.preventDefault();
			loader.show();
			var parents = $(this).parent().parent().parent();
			var gate = base_url + 'ajax.php?do=loadPlaylists';
			$.getJSON(gate, function(o) {
				if (o.success) {
					osx_create(o.content);
					$('#add_song_to').submit(function() {
						var title = $('.cell_2', parents).text();
						var duration = $('.cell_3', parents).text();
						var songUrl = $('.songUrl', parents).text();
						var songSource = $('.songSource', parents).text();
						var playlist_id = $('#add_song_to select[name=playlist_id]').val();
						var gate = base_url + 'ajax.php?do=loadPlaylists';
						if (songUrl != '') {
							var params = {title: title, duration: duration, url: songUrl, source: songSource, playlist_id: playlist_id};
						} else {
							var songId = $('.playstatus', parents).attr('value');
							var params = {song_id: songId, playlist_id: playlist_id};
						}
						$.post(
							gate,
							params,
							function(o) {
								if (o.success) {
									$('.simplemodal-close').click();
								} else {
									$('#add_song_to').html('<p>' + o.message + '</p>');
								}
							},
							'json'
						);
						return false;
					});
				} else {

				}
			});
			loader.hide();
			return false;
		});

	$('.mf a')
		.live('click', function(e) {
			e.preventDefault();
			loader.show();
			if (!checkTabs()) {
				window.location = $(this).attr('href');
				return false;
			}
			var matches = $(this).attr('href').match(/([^/]+)\/(\d+)/g);
			var matches = matches[0].split('/');
			gridMode = 'playlist';
			list_type = 'playlist';
			switch (matches[0]) {
				case 'top_songs':
					list_id = matches[0];
				break;
				case 'user':
					list_type = 'songs';
				default:
					list_id = matches[1];
			}
			var gate = base_url + 'ajax.php?do=' + list_type + '&id=' + list_id + '&format=flexigrid';
			$('.fplaylist').flexOptions({url: gate, dataMode: gridMode}).flexReload();
			loader.hide();
			return false;
		});

	$('.gridHolder')
		.live('click', function(e) {
			var id = $(this).attr('id').replace('grid', '');
			player.playId(id);
			if(lastH) lastH.css("background","none");
			$(this).children('.gridFrame').css("background","url(../images/grid_frame.png) no-repeat scroll 3px 2px transparent");
			lastH = $(this).children('.gridFrame');
			$(this).children('.gridFrame').children().children('img').css('visibility','visible');
		});

	$('#search form')
		.submit(function() {
			loader.show();
			if (!checkTabs()) {
				alert("You're not in a play mode and will be redirected to one.");
				window.location = base_url;
				return false;
			}
			list_type = 'search';
			list_id = $('input[name|=keywords]', this).attr('value');
			var gate = base_url + 'ajax.php?do=' + list_type + '&keywords=' + list_id + '&format=flexigrid';
			if (list_id.length >= 3) {
				gridMode = 'search';
				$('.fplaylist').flexOptions({url: gate, dataMode: gridMode}).flexReload();
			}
			loader.hide();
			return false;
		});

	updateSize();
	loader.hide();
});

