/***********************************************
* Dynamic Ajax Content- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/

var bustcachevar=1 //bust potential caching of external pages after initial request? (1=yes, 0=no)
var loadedobjects=""
var rootdomain="http://"+window.location.hostname
var bustcacheparameter=""
var modo = "GET";
function ajaxpage(url, containerid,rmode,rdata){	
var page_request = false
if (rmode=="POST") modo = "POST"; else modo = "GET";
if (rdata) datos = rdata; else datos = null;
if (window.XMLHttpRequest) // if Mozilla, Safari etc
page_request = new XMLHttpRequest()
else if (window.ActiveXObject){ // if IE
try {
page_request = new ActiveXObject("Msxml2.XMLHTTP")
} 
catch (e){
try{
page_request = new ActiveXObject("Microsoft.XMLHTTP")
}
catch (e){}
}
}
else
return false
page_request.onreadystatechange=function(){
loadpage(page_request, containerid)
}

if (bustcachevar) //if bust caching of external page
bustcacheparameter=(url.indexOf("?")!=-1)? "&cc="+new Date().getTime() : "?cc="+new Date().getTime()
page_request.open(modo, url+bustcacheparameter, true)
page_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=ISO-8859-1');
page_request.send(datos)

}
var sortear = false;
var mostrarGrupo = false;
var loadCanal = false;
var logeado = false;
function loadpage(page_request, containerid){
if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1)) {
document.getElementById(containerid).innerHTML=page_request.responseText
if (accion == "login") {
  if (page_request.responseText.substr(4,7) == "logeado") {
	  accion = "";
	  logeado = true;
  }
} 
if (accion == "importarVideos") {
	  accion = "";
	  hideCargandoTOP();
	  sortear = true;
}

if (editarVideos) {
	  editarVideos = false;
	  hideCargandoTOP();
	  sortear = true;
}
if (loadCanal) {
	document.getElementById('cargando_rapido').style.display='none';
	loadCanal= false;
}
if (sortear) {
	 Position.includeScrollOffsets = true;
   sortear = false;
   if (modoCanales == 1) {
     document.getElementById("cargando_rapido").style.display = "none";
     Sortable.create("resultados_busqueda_rapida",{handle:'handle',constraint:false,ghosting:false,scroll:document.getElementById('resultados')}); 
   } else {
   	 document.getElementById("cargando").style.display = "none";
     Sortable.create("resultados_busqueda",
     {dropOnEmpty:true,containment:["resultados_busqueda","videosCanal"],constraint:false});
     Sortable.create("videosCanal",
     {dropOnEmpty:true,handle:'handle',containment:["resultados_busqueda","videosCanal"],constraint:false});
	  hideCargandoTOP();
   }
}
if (mostrarGrupo) {
	mostrarFlash ('playlist.xml.php?canal=m'+page_request.responseText,'mediaspace');
	mostrarGrupo = false;
}
}
}

function mostrarFlash (playlist,divLayer) {
	canalVolver();
		/*var so = new SWFObject('/mediaplayer.swf','player','472','571','8');
		so.addParam("allowfullscreen","true");
		so.addParam("allowscriptaccess","always");
		so.addParam("wmode","opaque");
		so.addVariable("width","472");
		so.addVariable("height","571");
		so.addVariable('javascriptid','player');
		so.addVariable('enablejs','true');
		so.addVariable('file',playlist);
		so.addVariable('linkfromdisplay','true');
		so.addVariable('displaywidth','450');
		so.addVariable('displayheight','340');
		so.addVariable('thumbsinplaylist','true');
		so.addVariable('autoscroll','true');
		so.addVariable('autostart','true');
		so.addVariable('repeat','list');
		so.addVariable('shuffle','false');
		so.write(divLayer);*/
		flashvars="width=472&height=571&javascriptid=player&enablejs=true&file="+playlist+"&linkfromdisplay=true&displaywidth=450&displayheight=340&thumbsinplaylist=true&autoscroll=true&autostart=true&repeat=list&shuffle=false";
		swfDivName = divLayer;
		cargaPlayer('/mediaplayer.swf', '472', '571', '#ffffff',flashvars,'window');

}

function mostrarCargando(divLayer) {
		/*var so = new SWFObject('/cargando.swf','cargandoSwf','462','100','8');
		so.addParam("wmode","transparent");
		so.addVariable("width","462");
		so.addVariable("height","100");
		so.write(divLayer);*/

		swfDivName = divLayer;
		cargaPlayer('/cargando.swf', '100', '100', '#3F3F3F','','transparent');
}

function mostrarCargando100(divLayer) {
		/*var so = new SWFObject('/cargando.swf','cargandoSwf','100','100','8');
		so.addParam("wmode","transparent");
		so.addVariable("width","462");
		so.addVariable("height","100");
		so.write(divLayer);*/

		swfDivName = divLayer;
		cargaPlayer('/cargando.swf', '100', '100', '#3F3F3F','','transparent');
}
 
 
// APIS

		function HideContent(d) {
		if(d.length < 1) { return; }
		objeto = document.getElementById(d);
		objeto.style.display = "none";
		objeto.innerHTML = "";
		}
		function ShowContent(d) {
		if(d.length < 1) { return; }
		document.getElementById(d).style.display = "block";
		}
		function ReverseContentDisplay(d) {
		if(d.length < 1) { return; }
		if(document.getElementById(d).style.display == "none") { document.getElementById(d).style.display = "block"; }
		else { document.getElementById(d).style.display = "none"; }
		}
		function showCargando() {
		  cargando = document.getElementById("cargando");
		  cargando.style.display = "block";
		}
		function hideCargando() {
		  cargando = document.getElementById("cargando");
		  cargando.style.display = "none";
		}
		function showCargandoTOP() {
			document.getElementById("mediaspace").style.display = "none";
      document.getElementById("cargandoTOP").style.display = "block";		
      mostrarCargando('topLayerForm');
      document.getElementById("topLayerForm").style.display = "block";		
      setBackHeight();
    }
    function setBackHeight() {
	    var height = document.body.offsetHeight;
	    if (height < 400) height = 1000;
	    document.getElementById("cargandoTOP").style.height = height + "px";
    }
		function hideCargandoTOP() {
		  if (modoCanales == 1) document.getElementById("mediaspace").style.display = "";
      document.getElementById("cargandoTOP").style.display = "none";
		   document.getElementById("topLayerForm").style.display = "none";	
		}
		function loginForm(returnVal) {
			if (!returnVal) returnVal="";
		  showCargandoTOP();
		  document.getElementById("cargandoTOP").innerHTML = "";
		  ajaxpage('index.php?modo=login&return='+returnVal,'topLayerForm');
		}
		function comentarioForm(idCanal) {
			showCargandoTOP();
		  document.getElementById("cargandoTOP").innerHTML = "";
		  ajaxpage('index.php?modo=comentario&ch='+idCanal+'&return=comentario','topLayerForm');
		}

		function showWait(check) {
		  setTimeout("mostrarCargando ('int_formulario')",500);
		  return true;
		}

		function showWait1() {
			 if (document.getElementById("urlOcupada").style.display == "block") { 
			   alert(document.getElementById("errMsg").innerHTML);
			   return false;
			 }
		  setTimeout("mostrarCargando ('int_formulario')",500);
		  return true;
	 }
	editarVideos = false;	
		function editarCanal(idCanal) {
		 showCargandoTOP();
		 //document.getElementById("cargandoTOP").innerHTML = "";
		 canalAvanzado();
		 document.getElementById('storedId').innerHTML = "E"+idCanal;
		 accion == "editarVideos";
		 editarVideos = true;
     ajaxpage('index.php', 'canales','POST','videoModo=E&ch='+idCanal);
		 
		 //ajaxpage('index.php?modo=editar&canal='+idCanal,'topLayerForm');
		}
		function eliminarCanal(idCanal){
			if (confirm("¿Quieres eliminar este canal?")){
		    showCargandoTOP();
		    document.getElementById("cargandoTOP").innerHTML = "";
		    ajaxpage('index.php?modo=eliminar&id='+idCanal ,'topLayerForm');
		  }
		}
		
		function savedOK() {
		  showCargandoTOP();
		  document.getElementById("cargandoTOP").innerHTML = "";
		  alert("Tu canal se ha grabado con éxito");
		  window.location="http://www.dalealplay.tv";
		  //ajaxpage('index.php?modo=savedOK','topLayerForm');
		}
		function savedERR() {
		  showCargandoTOP();
		  document.getElementById("cargandoTOP").innerHTML = "";
		  alert("Se ha producido un ERROR, por favor intentelo más tarde.");
		  window.location="http://www.dalealplay.tv";
		}
		function importForm() {
		  showCargandoTOP();
		  document.getElementById("cargandoTOP").innerHTML = "";
		  ajaxpage('index.php?modo=import','topLayerForm');
		}
		accion = "";
		function apiLogin() {
		    accion = "login";
		    sendData = "user="+document.getElementById("usr").value + "&pass="+document.getElementById("pss").value;
		    if (document.getElementById("return"))
		      sendData = sendData + "&return="+document.getElementById("return").value;
		    if (document.getElementById("ch"))
		      sendData = sendData + "&ch="+document.getElementById("ch").value;
		    //mostrarCargando ('topLayerForm');
		    //if (document.getElementById("usr").value =="" or document.getElementById("pss").value=="") 
				   ajaxpage('index.php','topLayerForm','POST',sendData);
			}
		
		function getOrder() {
		  var orderList = '';
		  orderedNodes = document.getElementById("resultados_busqueda").getElementsByTagName("li");
		  for (var i=0;i < orderedNodes.length;i++) {
			orderList += orderedNodes[i].getAttribute('vidId') + ',';
			}
		  return orderList;
		}
		function reproducirLista() {
		 mostrarGrupo = true;
		 ajaxpage('index.php?crear='+getOrder(),'storedId');
		}
		function getOrderRapida() {
		  var orderList = '';
		  orderedNodes = document.getElementById("resultados_busqueda_rapida").getElementsByTagName("li");
		  for (var i=0;i < orderedNodes.length;i++) {
			orderList += orderedNodes[i].getAttribute('vidId') + ',';
			}
		  return orderList;
		}
		
		function reproducirListaRapida() {
		 mostrarGrupo = true;
		 ajaxpage('index.php?crear='+getOrderRapida(),'storedId');
		}
		
		var modoCanales = 1; // ver video
		var FirstTimeCanales = false;
		function canalAvanzado() {
		 //sendEvent('player','playpause');
		 document.getElementById('mediaspace').style.display = "none";
		 document.getElementById('avanzado').style.display="block";
		 document.getElementById('ver_canales').style.display='none';
		 document.getElementById('crear_canales').style.display='block';
		 modoCanales = 0; // modo avanzado de editar canal
		 
		 if (FirstTimeCanales && (document.getElementById("resultados_busqueda") != null)) {
		   Sortable.create("resultados_busqueda",{dropOnEmpty:true,containment:["resultados_busqueda","videosCanal"],constraint:false});
       Sortable.create("videosCanal",{dropOnEmpty:true,handle:'handle',containment:["resultados_busqueda","videosCanal"],constraint:false});
		 } else FirstTimeCanales = true;
		}
    
    function vovlerEditar() {
		document.getElementById('volverEnEditar').style.display="none";
		document.getElementById('moverTodosLosVideos').style.display="block";
		canalAvanzado()
		}
		
    function canalSimple() {
		 document.getElementById('mediaspace').style.display = "block";
		 document.getElementById('avanzado').style.display="none";
		 document.getElementById('ver_canales').style.display='block';
		 document.getElementById('crear_canales').style.display='none';
		 modoCanales = 1; // modo simple de editar canal
		}
	  
	  
	  function getOrderCanal() {
		  var orderList = '';
		  orderedNodes = document.getElementById("videosCanal").getElementsByTagName("li");
		  for (var i=0;i < orderedNodes.length;i++) {
			orderList += orderedNodes[i].getAttribute('vidId') + ',';
			}
		  return orderList;
		}
		function canalVolver() {
		 document.getElementById('mediaspace').style.display = "block";
		 document.getElementById('avanzado').style.display="none";
		 modoCanales = 1; // modo ver vídeo
		}
		function canalBorrar() {
      document.getElementById("avanzado").innerHTML = canalOrigin;
	   Sortable.create("resultados_busqueda",
     {dropOnEmpty:true,containment:["resultados_busqueda","videosCanal"],constraint:false});
     Sortable.create("videosCanal",
     {dropOnEmpty:true,handle:'handle',containment:["resultados_busqueda","videosCanal"],constraint:false});
		}
		
		function getListaCanales() {
		  document.getElementById('cargando_rapido').style.display='block';
		  loadCanal = true;
		  document.getElementById('cab_resultados_reproducir').style.display='none';
		  document.getElementById('cab_resultados').style.display='block';
		  document.getElementById('resultados_canales').style.display='block';
		  document.getElementById('resultados_canales_buscar').style.display='none';
		  ajaxpage('index.php?modo=todosloscanales','resultados_canales');
		}
		function misCanales() {
		  document.getElementById('cargando_rapido').style.display='block';
		  loadCanal = true;
		  document.getElementById('cab_resultados_reproducir').style.display='none';
		  document.getElementById('cab_resultados').style.display='block';
		  document.getElementById('resultados_canales').style.display='block';
		  document.getElementById('resultados_canales_buscar').style.display='none';
		  ajaxpage('index.php','resultados_canales','POST','modo=miscanales');
		}
		
		function canalesUsuario(NickUser) {
		  document.getElementById('cargando_rapido').style.display='block';
		  loadCanal = true;
		  document.getElementById('cab_resultados_reproducir').style.display='none';
		  document.getElementById('cab_resultados').style.display='block';
		  document.getElementById('resultados_canales').style.display='block';
		  document.getElementById('resultados_canales_buscar').style.display='none';
		  ajaxpage('index.php?modo=canalesusuario&nick='+NickUser,'resultados_canales');
		}
		
		function buscarRapido() {
		  sortear=true;
		  document.getElementById('cab_resultados_reproducir').style.display='block';
		  document.getElementById('cab_resultados').style.display='none';
		  document.getElementById('cargando_rapido').style.display='block';
		  document.getElementById('resultados_canales').style.display='none';
		  document.getElementById('resultados_canales_buscar').style.display='block';
		  ajaxpage('index.php?qr='+document.getElementById('q').value, 'resultados_canales_buscar');
		  return false;
	  }
		function canalVistaPrevia() {
		 if ((document.getElementById("videosCanal").getElementsByTagName("li").length > 1)) {
		 mostrarGrupo = true;
		 document.getElementById('volverEnEditar').style.display="block";
		 document.getElementById('moverTodosLosVideos').style.display="none";
		 canalVolver();
		 ajaxpage('index.php?crear='+getOrderCanal(),'storedId');
		} else {
		  alert("Debes arrastrar por lo menos un video en la zona 'Parilla de programación'");
		}
		}		
		function canalSave() {
		 if ((document.getElementById("videosCanal").getElementsByTagName("li").length > 1)) {
		 showCargandoTOP();
		 //document.getElementById("cargandoTOP").innerHTML = "";
		chid = document.getElementById('storedId').innerHTML;
		if (chid.substr(0,1) == "E") {
		chid=chid.substr(1,100);	
		ajaxpage('index.php?modo=editar&canal='+chid,'topLayerForm');
		ajaxpage('index.php?canal='+chid+'&actualizar='+getOrderCanal(),'storedId');
		} else {			
		 ajaxpage('index.php?modo=grabar','topLayerForm');
		 ajaxpage('index.php?crear='+getOrderCanal(),'storedId');
		}
		} else {
		  alert("Debes arrastrar por lo menos un video en la zona 'Parilla de programación'");
		}
		}
		function canalInfo(canalid) {
		 showCargandoTOP();
		 ajaxpage('index.php?modo=editar&canal='+canalid,'topLayerForm');
		}
		function grabarCanal() {
				accion = "grabarCanal";
		    sendData = "nombre="+document.getElementById("nombreCanal").value + "&avatar="+document.getElementById("avatarURL").value + "&tags="+document.getElementById("tagsCanal").value + "&descripcion="+document.getElementById("descripcionCanal").value + "&tempId="+document.getElementById("storedId").innerHTML;
		    if (document.getElementById("return"))
		      sendData = sendData + "&return="+document.getElementById("return").value;
		    mostrarCargando ('topLayerForm');
				ajaxpage('index.php','topLayerForm','POST',sendData);
		
		}
		function grabarComentario(idCanal) {
				accion = "grabarComentario";
		    sendData = "modo=grabaComentario&ch="+idCanal+"&texto="+document.getElementById("textoComentario").value;
		    mostrarCargando ('topLayerForm');
				ajaxpage('index.php','topLayerForm','POST',sendData);
        return false;

		}
		function apiImportar() {
				accion = "importarVideos";
		     chosen = ""
		      len = document.loginForm.importar.length;
		       for (i = 0; i <len; i++) {
               if (document.loginForm.importar[i].checked) {
                   chosen = document.loginForm.importar[i].value
              }
           }

           if (chosen == "") {
            alert("Hay que elegir el fuente de importacion");
            return(false);
           }
		      
		    sendData = "videoModo="+chosen;
		    if (document.getElementById("grupo"))
		      sendData = sendData + "&grupoId="+document.getElementById("grupo").value;
		    showCargandoTOP();
		    //document.getElementById('cargando').style.display='block';
				ajaxpage('index.php','resultados','POST',sendData);
				//alert(sendData);
		    
		}
		
		
		
var PositionOBJ = (function() {
	// Resolve a string identifier to an object
	// ========================================
	function resolveObject(s) {
		if (document.getElementById && document.getElementById(s)!=null) {
			return document.getElementById(s);
		}
		else if (document.all && document.all[s]!=null) {
			return document.all[s];
		}
		else if (document.anchors && document.anchors.length && document.anchors.length>0 && document.anchors[0].x) {
			for (var i=0; i<document.anchors.length; i++) {
				if (document.anchors[i].name==s) { 
					return document.anchors[i]
				}
			}
		}
	}
	
	var pos = {};
	pos.$VERSION = 1.0;
	
	// Set the position of an object
	// =============================
	pos.set = function(o,left,top) {
		if (typeof(o)=="string") {
			o = resolveObject(o);
		}
		if (o==null || !o.style) {
			return false;
		}
		
		// If the second parameter is an object, it is assumed to be the result of getPosition()
		if (typeof(left)=="object") {
			var pos = left;
			left = pos.left;
			top = pos.top;
		}
		
		o.style.left = left + "px";
		o.style.top = top + "px";
		return true;
	};
	
	// Retrieve the position and size of an object
	// ===========================================
	pos.get = function(o) {
		var fixBrowserQuirks = true;
			// If a string is passed in instead of an object ref, resolve it
		if (typeof(o)=="string") {
			o = resolveObject(o);
		}
		
		if (o==null) {
			return null;
		}
		
		var left = 0;
		var top = 0;
		var width = 0;
		var height = 0;
		var parentNode = null;
		var offsetParent = null;
	
		
		offsetParent = o.offsetParent;
		var originalObject = o;
		var el = o; // "el" will be nodes as we walk up, "o" will be saved for offsetParent references
		while (el.parentNode!=null) {
			el = el.parentNode;
			if (el.offsetParent==null) {
			}
			else {
				var considerScroll = true;
				/*
				In Opera, if parentNode of the first object is scrollable, then offsetLeft/offsetTop already 
				take its scroll position into account. If elements further up the chain are scrollable, their 
				scroll offsets still need to be added in. And for some reason, TR nodes have a scrolltop value
				which must be ignored.
				*/
				if (fixBrowserQuirks && window.opera) {
					if (el==originalObject.parentNode || el.nodeName=="TR") {
						considerScroll = false;
					}
				}
				if (considerScroll) {
					if (el.scrollTop && el.scrollTop>0) {
						top -= el.scrollTop;
					}
					if (el.scrollLeft && el.scrollLeft>0) {
						left -= el.scrollLeft;
					}
				}
			}
			// If this node is also the offsetParent, add on the offsets and reset to the new offsetParent
			if (el == offsetParent) {
				left += o.offsetLeft;
				if (el.clientLeft && el.nodeName!="TABLE") { 
					left += el.clientLeft;
				}
				top += o.offsetTop;
				if (el.clientTop && el.nodeName!="TABLE") {
					top += el.clientTop;
				}
				o = el;
				if (o.offsetParent==null) {
					if (o.offsetLeft) {
						left += o.offsetLeft;
					}
					if (o.offsetTop) {
						top += o.offsetTop;
					}
				}
				offsetParent = o.offsetParent;
			}
		}
		
	
		if (originalObject.offsetWidth) {
			width = originalObject.offsetWidth;
		}
		if (originalObject.offsetHeight) {
			height = originalObject.offsetHeight;
		}
		
		return {'left':left, 'top':top, 'width':width, 'height':height
				};
	};
	
	// Retrieve the position of an object's center point
	// =================================================
	pos.getCenter = function(o) {
		var c = this.get(o);
		if (c==null) { return null; }
		c.left = c.left + (c.width/2);
		c.top = c.top + (c.height/2);
		return c;
	};
	
	return pos;
})();


// Comprobacion URL unica


function OnChangedUsername()
{
if(document.getElementById('urlCanal').value != "")
{
 OnCheckAvailability();
}
}

function OnCheckAvailability()
{
if(window.XMLHttpRequest)
{
oReq = new XMLHttpRequest();
}
else if(window.ActiveXObject)
{
oReq = new ActiveXObject("Microsoft.XMLHTTP");
}

oReq.open("POST", "index.php", true);
oReq.onreadystatechange = UpdateCheckAvailability;
oReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
oReq.send("url=" + document.getElementById('urlCanal').value);
}

function UpdateCheckAvailability()
{
if(oReq.readyState == 4)
{ 
if(oReq.status == 200)
{
	if (oReq.responseText.indexOf("#OK#") > 0 ) {
    document.getElementById("urlDisponible").style.display="block";
    document.getElementById("urlOcupada").style.display="none";
  } else {
    document.getElementById("urlOcupada").style.display="block";
    document.getElementById("urlDisponible").style.display="none";
  }
} else{
	alert("SIN SERVICIO");
//document.getElementById("Available").innerHTML = "Servicio no disponible";
}
}
}