var clock = new Date();
var milisegundos = 0;
var yoxviewPath = $.KumbiaPHP.publicPath+"javascript/yoxview/";

function CTRequest(sURL, sMethod, sVars, sDataType, fnDone){jQuery.ajax({url: $.KumbiaPHP.publicPath+sURL,type: sMethod,async: true,data: sVars,dataType: sDataType,success: fnDone,error: fnDone});}

jQuery(document).ready(function(){
	//$("#logo").ifixpng();
	jQuery(document).everyTime(30000, "announcement", ChangeAnnouncements);
	jQuery(".ann_playpause").css({background: "url('"+$.KumbiaPHP.publicPath+"img/ann_pause.png')"});
	jQuery(".comments").prettyComments();
	jQuery(".scrollable").scrollable({keyboard: false});
	jQuery(".yoxview").yoxview({lang: "es", playDelay: 5000});
	/*var options = {
		time: jQuery("#time").html(),
		utc: true,
		utcOffset: -5 
	}
	/*jQuery("#playlist").dataTable({
		"bLengthChange": false,
		"iDisplayLength": 10,
		"oLanguage": {
			"sUrl": "lib/dataTables/language/es_ES.txt"
		},
		"aaSorting": [[ 0, "desc" ]],
		"aoColumns":[
			{"bSortable": true, "bVisible": false},
			null,
			null,
			null
		]
	});
	jQuery("#nick").keypress(
		function(e){
			var isEnter = window.event == null ? e.keyCode == 13 : window.event.keyCode == 13;
			if(isEnter)
				jQuery("#pass").focus();
	});
	jQuery("#pass").keypress(
		function(e){
			var isEnter = window.event == null ? e.keyCode == 13 : window.event.keyCode == 13;
			if(isEnter)
				jQuery("#btnLogon").click();
	});*/
	/*jQuery("#BannerSuperior").ekko({
		minTimeout: 20000,
		method: "post",
		multiplier: 2,
		sendData: null,
		type: "json",
		url: $.KumbiaPHP.publicPath+"banners/actualizar"
	},
	function(data){
		jQuery.each(data, function(i, item){
			file = "";
			if(item.file.match(".swf")){
				file = "<object type='application/x-shockwave-flash' data='"+$.KumbiaPHP.publicPath+"img/upload/banners/"+item.file+"' width="+item.width+"' height='"+item.height+"'><param name='movie' value='"+$.KumbiaPHP.publicPath+"img/upload/banners/"+item.file+"' /><param name='wmode' value='transparent' /></object>";
			}else{
				file = "<img src='"+$.KumbiaPHP.publicPath+"img/upload/banners/"+item.file+"' width='"+item.width+"' height='"+item.height+"' alt='"+item.title+"' title='"+item.file+"' />";
				if(item.url != "")
					file = "<a href='"+item.url+"' target='_blank'>"+file+"</a>";
			}
			if(item.type == "1"){
				if(item.pos == "U")
					jQuery("#BannerSuperior").html(file);
				else
					jQuery("#BannerMedio").html(file);
			}
			if(item.type == "3"){
				if(item.pos == "L")
					jQuery("#BannerLeft").html(file);
				else
					jQuery("#BannerRight").html(file);
			}
		})
	});*/
	jQuery("#messages").ekko({
		minTimeout: 20000,
		method: "post",
		multiplier: 2,
		sendData: null,
		type: "html",
		url: $.KumbiaPHP.publicPath+"mensajes/actualizar"
	},
	function(data){
		jQuery("#messages").html(data);
	});
	jQuery("#clock").ekko({
		minTimeout: 60000,
		method: "post",
		multiplier: 1,
		sendData: null,
		type: "text",
		url: $.KumbiaPHP.publicPath+"actualizaciones/reloj"
	},
	function(data){
		jQuery("#clock").html(data);
	});
});

/* one playlist item
lst[n] = {
	author:"",
	description:"",
	duration:"",
	file:"",
	link:"",
	image:"",
	start:"",
	title:"",
	type:""
}
*/

var arrayPlaylist = new Array();
var backcolor = "";
var contPlaylist = 0;
var currentItem = -1;
var currentItemID = 0;
var currentItemType = "";
var currentPosition = 0;
var currentState = "";
var player = null;
var playlistLoaded = false;
var playlistNews = 0;
var playlistOn = false;
var previousItem = -1;
var previousItemID = 0;
var previousState = "";
var songListened = false;
var tabSelected = "Artists";

function AddFavorite(Titulo, URL) {
	if (navigator.appName == "Netscape") {
		window.sidebar.addPanel(Titulo, URL, ""); 
	}
	
	if (navigator.appName == "Microsoft Internet Explorer"){
		window.external.AddFavorite(URL, Titulo);
	}
}

function AddListeners(){
	if (player){
		player.addControllerListener("ITEM", "ItemListener");
		player.addModelListener("STATE", "StateListener");
		player.addModelListener("TIME", "PositionListener");
	}else{
		setTimeout("AddListeners()", 100);
	}
}

function ChangeAnnouncements(op){
	op = op || 1;
	var ann_curr = parseInt(jQuery("#ann_curr").html());
	var ann_total = parseInt(jQuery("#ann_total").html());
	if(op == 1){
		jQuery("#announcement"+ann_curr).hide();
		if(ann_curr >= ann_total){
			ann_curr = 1;
		}else{
			ann_curr++;
		}
		jQuery("#announcement"+ann_curr).show();
	}else{
		jQuery("#announcement"+ann_curr).hide();
		if(ann_curr <= 1)
			ann_curr = ann_total;
		else
			ann_curr--;
		jQuery("#announcement"+ann_curr).show();
	}
	jQuery("#ann_curr").html(ann_curr);
	jQuery(document).everyTime(30000, "announcement", ChangeAnnouncements);
}

function ChangeColorWeb(themes_id, bcolor, fcolor){
	backcolor = bcolor;
	jQuery(".ColorWeb").css({background: "url('"+$.KumbiaPHP.publicPath+"img/page_bg.png') "+bcolor});
	jQuery(".FontWeb").css({color: fcolor});
	//jQuery(".ColorWeb font").css({color: "#"+color});
	CTRequest("colores/cambiar/"+themes_id, "POST", null, "html", null);
}

function ChangeImageNews(op){
	var img = parseInt(jQuery("#noticias_actual").val());
	var num_images = parseInt(jQuery("#noticias_total").val());
	if(op == 1){
		jQuery("#news_image"+img).hide("slow");
		if(img >= num_images){
			img = 1;
		}else{
			img++;
		}
		jQuery("#news_image"+img).show("slow");
	}else{
		jQuery("#news_image"+img).hide("slow");
		if(img <= 1)
			img = num_images;
		else
			img--;
		jQuery("#news_image"+img).show("slow");
	}
	jQuery("#noticias_actual").val(img);
}

function ConfirmAddToMyPlaylist(cType, iID, sAuthor, sTitle){
	if(cType == "S")
		msg = "Deseas agregar esta canci\u00F3n a tus favoritas";
	else
		msg = "Deseas agregar este video a tus favoritos";
	var op = confirm("\u00BF"+msg+"\u003F");
	if(op){
		var existe = false;
		for(var itm in arrayPlaylist){
			if(arrayPlaylist[itm].description == cType+":"+iID)
				existe = true;
		}
		if(existe){
			alert("Este archivo ya está en tus favoritos.");
		}else{
			jQuery("#PlaylistMSG").css({background: "url('img/spinner.gif') center no-repeat"});
			jQuery("#PlaylistMSG").show();
			//arrayPlaylist[contPlaylist] = type+""+id;
			if(cType == "S"){
				//img = "<img src='img/music.gif' alt='' height='16' title='Canci\u00F3n' width='16' />";
				img = "<img src='img/music_delete.gif' alt='' height='16' title='Eliminar de tus favoritos' width='16' onclick=\"DeleteFromMyPlaylist('"+contPlaylist+"');\" />";
				action = "music";
				type_str = "sound";
			}else{
				//img = "<img src='img/video.gif' alt='' height='16' title='Video' width='16' />";
				img = "<img src='img/video_delete.gif' alt='' height='16' title='Eliminar de tus favoritos' width='16' onclick=\"DeleteFromMyPlaylist('"+contPlaylist+"');\" />";
				action = "video";
				type_str = "video";
			}
			CTRequest("modules/public.php", "POST", "op=GetFile&type="+cType+"&id="+iID+"&playlist=S", "json",
			function(data){
				arrayPlaylist[contPlaylist] = {
					author: sAuthor,
					description: cType+":"+iID,
					//duration: "",
					file: stripslashes(data.file),
					/*file_type: cType,
					id: iID,*/
					image: stripslashes(data.image),
					link: stripslashes(data.url),
					//start: true,
					title: sTitle,
					type: type_str
				}
				contPlaylist++;
				jQuery("#MyPlaylist").append("<li class='new'>"+img+" "+stripslashes(sAuthor)+" - "+stripslashes(sTitle)+"</li>");
				//player.sendEvent("LOAD", arrayPlaylist);
				playlistNews++;
				jQuery("#SaveFavorites").show();
				jQuery("#PlaylistMSG").css({background: ""});
				jQuery("#PlaylistMSG").hide();
			});
		}
	}
}

function DeleteFromMyPlaylist(num){
	arrayPlaylist[num] = {
		author: "",
		description: "",
		file: "",
		/*file_type: "",
		id: "",*/
		image: "",
		link: "",
		title: "",
		type: ""
	}
	//PrintPlaylist(-1);
	playlistNews--;
	if(playlistNews > 0)
		jQuery("#SaveFavorites").show();
	else
		jQuery("#SaveFavorites").hide();
	player.sendEvent("LOAD", arrayPlaylist);
	arrayPlaylist = player.getPlaylist();
	currentLength = arrayPlaylist.length;
	alert("currentItem: "+currentItem+", currentLength: "+currentLength);
	if(playlistOn){
		if(currentItem == currentLength - 1)
			player.sendEvent("NEXT");
		else
			player.sendEvent("PLAY");
	}
	PrintPlaylistPlayer();
}

function FixPNG(){
	jQuery(document).ready(function(){
		jQuery("img[src$=.png]").ifixpng();
	});
}

function InitPlayer(bgcolor) {
	backcolor = bgcolor || "CCCCCC";
	
	var flashvars = {
		//file: "./nstramusik/chattagena.mp3",
		//image: "./img/logo.png",
		backcolor: backcolor,
		skin: "./lib/overlay.swf",
		controlbar: "over"
	}
	var params = {
		allowfullscreen: "true", 
		allowscriptaccess: "always",
		wmode: "transparent"
	}
	var attributes = {
		id: "player",  
		name: "player"
	}
	swfobject.embedSWF("lib/mediaplayer.swf", "player", "300", "292", "8", false, flashvars, params, attributes);
}

function IsAlphaNum(str){
	// Return immediately if an invalid value was passed in
	if (str+"" == "undefined" || str+"" == "null" || str+"" == "")	
		return false;
	
	var isValid = true;
	
	// convert to a string for performing string comparisons.
   	str += "";	
   	
	// Loop through length of string and test for any alpha numeric 
	// characters
   	for (i = 0; i < str.length; i++){
		// Alphanumeric must be between "0"-"9", "A"-"Z", or "a"-"z"
      	if (!(((str.charAt(i) >= "0") && (str.charAt(i) <= "9")) || 
      		((str.charAt(i) >= "a") && (str.charAt(i) <= "z")) ||
      		((str.charAt(i) >= "A") && (str.charAt(i) <= "Z")) ||
      		(str.charAt(i) == "@"))){
				isValid = false;
				break;
			}
   	} // END for
   
   	return isValid;
}// end IsAlphaNum

function IsEmailAddress(s){
	//var s = theElement.value;
	var filter=/^[A-Za-z][A-Za-z0-9_]*@[A-Za-z0-9_]+\.[A-Za-z0-9_.]+[A-za-z]$/;
	if (s.length == 0 ) return true;
	if (filter.test(s))
		return true;
	//else
		//alert("Ingrese una direccion de correo válida");
	//theElement.focus();
	return false;
}

function LoadFile(cType, iID, bAutostart){
	jQuery("#PlaylistMSG").css({background: "url('img/spinner.gif') center no-repeat"});
	jQuery("#PlaylistMSG").show();
	//previousItemID = currentItemID;
	currentItemID = iID;
	currentItemType = cType;
	songListened = false;
	CTRequest("modules/public.php", "POST", "op=GetFile&type="+cType+"&id="+iID, "json",
	function(data){
		LoadPlayer(data.file, data.image, data.url, bAutostart);
		jQuery("#PlaylistMSG").css({background: ""});
		jQuery("#PlaylistMSG").hide();
	});
}

function LoadPlayer(sFile, sImage, sURL, bAutostart){
	backcolor = backcolor || "FFFFFF";
	bAutostart = bAutostart || false;
	//sBgcolor = (typeof sBgcolor == 'undefined') ? "0066FF" : sBgcolor;
	sFile = stripslashes(sFile);
	sImage = stripslashes(sImage);
	sURL = stripslashes(sURL);
	
	var flashvars = {
		autostart: bAutostart,
		backcolor: backcolor,
		controlbar: "over",
		file: sFile,
		image: sImage,
		link: sURL,
		skin: "./lib/overlay.swf"
	}
	var params = {
		allowfullscreen: "true", 
		allowscriptaccess: "always",
		wmode: "transparent"
	}
	var attributes = {
		id: "player",  
		name: "player"
	}
	swfobject.embedSWF("lib/mediaplayer.swf", "player", "300", "292", "8", false, flashvars, params, attributes);
	if(playlistOn){
		player.sendEvent("STOP");
		PlayerStopped();
		playlistLoaded = false;
	}
}

function LoadScript(module){
	CTRequest("js/modules/"+module+".min.js", "POST", "", "script", null);
}

function LoadScriptAdmin(module){
	CTRequest("js/admin/"+module+".min.js", "POST", "", "script", null);
}

function LogonUser(){
	nick = jQuery("#nick").val();
	pass = jQuery("#pass").val();
	remember = "N";
	if(nick == "" && pass == ""){
		alert("Debe ingresar el nick y la clave.");
		jQuery("#nick").focus();
	}else{
		if(nick == ""){
			alert("Debe ingresar el nick.");
			jQuery("#nick").focus();
		}else{
			if(pass == ""){
				alert("Debe ingresar la clave.");
				jQuery("#pass").focus();
			}else{
				if($("#remember").attr("checked") == true){
					remember = "S";
				}
				jQuery("#btnLogon").attr("disabled", "disabled");
				jQuery("#LogonUserMSG").css({background: "url('img/spinner.gif') center no-repeat"});
				jQuery("#LogonUserMSG").show();
				CTRequest("modules/users.php", "POST", "op=LogonUser&nick="+nick+"&pass="+pass+"&remember="+remember, "json", LogonUserFN);
			}
		}
	}
}

function LogonUserFN(data){
	if(data.msg == "ok"){
		alert("Hola "+data.nick+", Bienvenid@ a Chattagena -  Tu Ciudad en Internet.");
		jQuery(".ColorWeb").css({background: "url('img/page_bg.png') #"+data.bgcolor});
		jQuery("#UserNick").html(data.nick);
		jQuery("#nick").val("");
		jQuery("#pass").val("");
		jQuery("#LogonOption").hide();
		jQuery("#LogoffOption").show();
		jQuery("#form_login").hide();
		//jQuery("#btnNewPublicMessage").show();
		//LoadBlockUsers();
		//LoadStatusBar();
		//ViewSection("news", "Main");
	}else{
		if(data.msg == "user_banned"){
			alert("Este usuario ha sido banneado.");
		}else{
			alert("Datos incorrectos.");
		}
	}
	jQuery("#btnLogon").attr("disabled", "");
	jQuery("#LogonUserMSG").css({background: ""});
	jQuery("#LogonUserMSG").hide();
}

function LogoffUser(){
	//jQuery("#btnLogout").attr("disabled", "disabled");
	//jQuery("#UserInfoMSG").html("<img src='img/spinner.gif' alt='' />&nbsp;Desconectando...");
	CTRequest("modules/users.php", "POST", "op=LogoffUser&secure=S", "json", LogoffUserFN);
}

function LogoffUserFN(data){
	if(data.msg != "ok"){
		//jQuery("#btnLogout").attr("disabled", "");
		//jQuery("#UserInfoMSG").html("");
		alert("Error al Desconectar.");
	}else{
		alert(data.nick + " vuelve pronto a Chattagena - Tu Ciudad en Internet.");
		jQuery("#UserNick").html("Turista");
		jQuery("#LogonOption").show();
		jQuery("#LogoffOption").hide();
		//jQuery("#btnNewPublicMessage").hide();
		//LoadBlockUsers();
		//LoadStatusBar();
		//jQuery("#DivMenuAdmin").hide("slow");
		//jQuery("#DivMenuUser").hide("slow");
		//ViewSection("news", "Main");
	}
}

function NeedLogin(){
	alert("Chattagena.com te invita a iniciar sesión para poder hacer uso de esta opción.");
}

function NstroChat(){
	window.open("nstrochat/","NstroChat","width=800,height=650,toolbar=no,location=no,status=no,menubar=no,resizable=no,scrollbars=no")
}

function NstraMusik(){
	window.open("http://canciones.chattagena.com","NstraMusik","width=500,height=220,toolbar=no,location=no,status=no,menubar=no,resizable=no,scrollbars=no")
}

function NstrosVideos(){
	window.open("http://videos.chattagena.com","NstrosVideos","width=600,height=300,toolbar=no,location=no,status=no,menubar=no,resizable=no,scrollbars=no")
}

function PlayerPlaying(){
	playlistOn = true;
	jQuery("#PlayFavorites").hide();
	jQuery("#StopFavorites").show();
}

function playerReady(thePlayer) {
	player = document.getElementById(thePlayer.id);
	AddListeners();
}

function PlayerStopped(){
	playlistOn = false;
	jQuery("#PlayFavorites").show();
	jQuery("#StopFavorites").hide();
}

function PlayFavorites(){
	if(!playlistLoaded)
		playlistLoaded = true;
	if(playlistOn){
		PlayerStopped();
		player.sendEvent("STOP");
	}else{
		player.sendEvent("LOAD", arrayPlaylist);
		player.sendEvent("PLAY");
		jQuery("#SaveFavorites").hide();
		PrintPlaylistPlayer();
	}
}

function PlayStopChangeAnnouncements(){
	img = jQuery(".ann_playpause").css("background");
	if(img.match("pause")){
		jQuery(document).stopTime("announcement");
		jQuery(".ann_playpause").css({background: "url('img/ann_play.png')"});
	}else{
		jQuery(document).everyTime(30000, "announcement", ChangeAnnouncements);
		jQuery(".ann_playpause").css({background: "url('img/ann_pause.png')"});
	}
}

function PositionListener(obj) { 
	currentPosition = obj.position;
}

function PrintPlaylist(iIndex){
	jQuery("#MyPlaylist").html("");
	for(var itm in arrayPlaylist){
		if(arrayPlaylist[itm].author != "" && arrayPlaylist[itm].title != ""){
			if(arrayPlaylist[itm].type == "sound")
				img = "<img src='img/music_delete.gif' alt='' height='16' title='Eliminar de tus favoritos' width='16' onclick=\"DeleteFromMyPlaylist('"+itm+"');\" />";
			else
				img = "<img src='img/video_delete.gif' alt='' height='16' title='Eliminar de tus favoritos' width='16' onclick=\"DeleteFromMyPlaylist('"+itm+"');\" />";
			if(itm == iIndex)
				jQuery("#MyPlaylist").append("<li class='listen'>"+img+" "+arrayPlaylist[itm].author+" - "+arrayPlaylist[itm].title+"</li>");
			else
				jQuery("#MyPlaylist").append("<li>"+img+" "+arrayPlaylist[itm].author+" - "+arrayPlaylist[itm].title+"</li>");
		}
	}
}

function PrintPlaylistPlayer(iIndex){
	var plst = null;
	plst = player.getPlaylist();
	if (plst) {
		var txt = '';
		jQuery("#MyPlaylist").html("");
		for(var itm in plst){
			if(plst[itm].type == "sound")
				img = "<img src='img/music_delete.gif' alt='' height='16' title='Eliminar de tus favoritos' width='16' onclick=\"DeleteFromMyPlaylist('"+itm+"');\" />";
			else
				img = "<img src='img/video_delete.gif' alt='' height='16' title='Eliminar de tus favoritos' width='16' onclick=\"DeleteFromMyPlaylist('"+itm+"');\" />";
			if(itm == iIndex)
				jQuery("#MyPlaylist").append("<li class='listen'>"+img+" "+plst[itm].author+" - "+plst[itm].title+"</li>");
			else
				jQuery("#MyPlaylist").append("<li>"+img+" "+plst[itm].author+" - "+plst[itm].title+"</li>");
		}
		//jQuery("#MyPlaylist").html("<li id='Playlist"+contPlaylist+"' onclick=\"javascript:LoadFile('"+type+"', '"+id+"', 'true');\">"+img+" "+stripslashes(author)+" - "+stripslashes(title)+"</li>");
	}	
}

function SaveFavorites(){
	jQuery("#SaveFavorites").hide();
	player.sendEvent("LOAD", arrayPlaylist);
	playlistNews = 0;
	playlistLoaded = true;
	/*player.sendEvent("ITEM", currentItem);
	player.sendEvent("SEEK", currentPosition);*/
	/*player.sendEvent("PLAY");
	if(!playlistOn){
		playlistOn = true;
	}
	PlayerPlaying();*/
	PrintPlaylistPlayer();
	songListened = false;
}

function ScrollToMain(){jQuery.scrollTo("#main", 800);}

function SendPass(){
	email = $("#email").val();
	if(email == ""){
		alert("Debe ingresar el email.");
		jQuery("#email").focus();
	}else{
		if(!email.match("@")){
			alert("Ingrese un email v\u00E1lido.");
			jQuery("#email").focus();
		}else{
			jQuery("#btnForgotPass").attr("disabled", "disabled");
			jQuery("#ForgotPassMSG").css({background: "url('img/spinner.gif') center no-repeat"});
			jQuery("#ForgotPassMSG").show();
			CTRequest("modules/users.php", "POST", "op=SendPass&email="+email, "html", SendPassFN);
		}
	}
}

function SendPassFN(res){
	jQuery("#btnForgotPass").attr("disabled", "");
	jQuery("#ForgotPassMSG").css({background: ""});
	jQuery("#ForgotPassMSG").hide();
}

function ItemListener(obj){
	/*if(obj.index != currentItem){
 		previousItem = currentItem;
		currentItem = obj.index;
		if(playlistLoaded)
			PrintPlaylistPlayer(currentItem);
		else
			PrintPlaylist(-1);
		if(currentState == "PLAYING"){
			if(playlistLoaded){
				PlayerPlaying();
				var plst = null;
				plst = player.getPlaylist();
				desc = plst[currentItem].description;
				temp = desc.split(":");
				currentItemType = temp[0];
				currentItemID = parseInt(temp[1]);
				alert("playlistLoaded, currentItemID: "+currentItemID+", currentItemType: "+currentItemType);
				if(currentItemID > 0 && currentItemType != ""){
					songListened = true;
					op = "SongListened";
					if(currentItemType == "V")
						op = "VideoViewed";
					CTRequest("modules/public.php", "POST", "op="+op+"&id="+currentItemID, null);
				}
			}else{
				alert("!playlistLoaded currentItemID: "+currentItemID+", currentItemType: "+currentItemType);
				if(currentItemID > 0 && currentItemType != ""){
					songListened = true;
					op = "SongListened";
					if(currentItemType == "V")
						op = "VideoViewed";
					CTRequest("modules/public.php", "POST", "op="+op+"&id="+currentItemID, null);
				}
			}
		}
	}else
		alert("obj.index == currentItem");*/
	if(currentState == "PLAYING"){
		if(playlistLoaded){
			PlayerPlaying();
			if(obj.index != currentItem){
				previousItem = currentItem;
				currentItem = obj.index;
				PrintPlaylistPlayer(currentItem);
				var plst = null;
				plst = player.getPlaylist();
				desc = plst[currentItem].description;
				temp = desc.split(":");
				currentItemType = temp[0];
				currentItemID = parseInt(temp[1]);
				//alert("playlistLoaded, currentItemID: "+currentItemID+", currentItemType: "+currentItemType);
				if(currentItemID > 0 && currentItemType != ""){
					songListened = true;
					op = "SongListened";
					if(currentItemType == "V")
						op = "VideoViewed";
					CTRequest("modules/public.php", "POST", "op="+op+"&id="+currentItemID, null);
				}
			}
		}else{
			//alert("!playlistLoaded currentItemID: "+currentItemID+", currentItemType: "+currentItemType);
			if(currentItemID > 0 && currentItemType != ""){
				songListened = true;
				op = "SongListened";
				if(currentItemType == "V")
					op = "VideoViewed";
				CTRequest("modules/public.php", "POST", "op="+op+"&id="+currentItemID, null);
			}
		}
	}
}

function StateListener(obj){ //IDLE, BUFFERING, PLAYING, PAUSED, COMPLETED
	//alert("StateListener");
	currentState = obj.newstate;
	previousState = obj.oldstate;
	
	if((currentState == "COMPLETED") && (previousState == "PLAYING")){
		currentItem = obj.index;
		currentLength = player.getPlaylist().length;
		songListened = false;
		if(currentItem < currentLength - 1 || playlistOn){
			player.sendEvent("LOAD", arrayPlaylist);
			player.sendEvent("NEXT");
			jQuery("#SaveFavorites").hide();
		}
	}
}

function stripslashes(html){
	html = html.replace(/\\/g, "");
	
	return html;
}

function ToggleDiv(div){
	jQuery("#"+div).toggle();
}

function TogglePlaylist(){
	jQuery("#PlaylistContent").slideToggle();
}

function ToggleOptions(opt){
	var div = "";
	var focus = "";
	if(opt == 1){
		div = "form_login";
		focus = "nick_nav";
		jQuery("#form_forgot_pass").hide();
	}else if(opt == 2){
		div = "form_forgot_pass";
		focus = "email_nav";
		jQuery("#form_login").hide();
	}
	jQuery("#"+div).toggle();
	jQuery("#options_text").toggle();
	jQuery("#"+focus).focus();
}

function Trim(str){
	var resultStr = "";
	resultStr = TrimLeft(str);
	resultStr = TrimRight(resultStr);
	
	return resultStr;
}

function TrimLeft(str){
	var resultStr = "";
	var i = len = 0;
	if (str+"" == "undefined" || str == null)
		return "";
	str += "";
	
	if (str.length == 0)
		resultStr = "";
	else{
		len = str.length;
		while ((i <= len) && (str.charAt(i) == " "))
			i++;
		resultStr = str.substring(i, len);
	}
	
	return resultStr;
}

function TrimRight(str){
	var resultStr = "";
	var i = 0;
	if (str+"" == "undefined" || str == null)
		return "";
	str += "";
	if (str.length == 0)
		resultStr = "";
	else{
		i = str.length - 1;
		while ((i >= 0) && (str.charAt(i) == " "))
			i--;
		resultStr = str.substring(0, i + 1);
	}
	
	return resultStr;
}

function ValidarRegistro(){
	if(!IsAlphaNum(Trim($("#usuario_nick").val()))){
		alert("El nick solo puede tener números y letras, no se aceptan caracteres especiales ni tildes");
		jQuery("#usuario_nick").focus();
		return false;
	}
	if(!IsEmailAddress(Trim($("#usuario_email").val()))){
		alert("Ingrese un E-Mail válido");
		jQuery("#usuario_email").focus();
		return false;
	}
	return true;
}

function ViewSection(module, op){
	jQuery("#DivLoading").show();
	//jQuery("#Main").html("<img src='img/spinner.gif' alt='' />&nbsp;Cargando la Secci&oacute;n...");
	CTRequest("modules/"+module+".php", "POST", "op="+op, "html", ViewSectionFN);
	LoadScript(module);
}

function ViewSectionFN(res){
	if(res != ""){
		jQuery("#Main").html(res);
	}else{
		//jQuery("#Main").html("");
		Boxy.ask("<font class='error'>Tenemos un Error, intenta de nuevo.</font>", null, null, {title: "<img src='img/error.png' alt='' />&nbsp;Error", closeable: true, closeText: "[Cerrar]"});
	}
	FixPNG();
	jQuery("#DivLoading").hide();
}

function ViewSectionAdmin(module, op){
	jQuery("#DivLoading").show();
	//jQuery("#Main").html("<img src='img/spinner.gif' alt='' />&nbsp;Cargando la Secci&oacute;n...");
	CTRequest("admin/"+module+".php", "POST", "op="+op, "html", ViewSectionAdminFN);
	LoadScriptAdmin(module);
}

function ViewSectionAdminFN(res){
	if(res != ""){
		jQuery("#Main").html(res);
	}else{
		//jQuery("#Main").html("");
		Boxy.ask("<font class='error'>Tenemos un Error, intenta de nuevo.</font>", null, null, {title: "<img src='img/error.png' alt='' />&nbsp;Error", closeable: true, closeText: "[Cerrar]"});
	}
	FixPNG();
	jQuery("#DivLoading").hide();
}

function ViewTab(div){
	jQuery("#"+tabSelected+"Updates").slideUp("slow");
	jQuery("#"+div+"Updates").slideDown("slow");
	jQuery("#Tab"+div).css({background: "#CCC"});
	jQuery("#Tab"+tabSelected).css({background: ""});
	tabSelected = div;
}
