/*Creado con Ardora - www.webardora.net
bajo licencia Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0)
para otros usos contacte con el autor
*/
$(document).ready(function() {aObjectsOld[0]="init";iniArrayObjects();cargaElementos();
$("#fontName").change(function() {$("#texto").css("font-family",$(this).find("option:selected").text());});
$("#tamano").change(function() {if ($("#tamano").val()<6){$("#tamano").val("6")}; if ($("#tamano").val()>99){$("#tamano").val("99")}; var tam=$("#tamano").val().toString()+"px";$("#texto").css("font-size",tam);});
$("#negrilla").change(function() { if ($("#negrilla").is(':checked')){var cssObj = {"font-weight" : "bold"};$("#texto").css(cssObj);}else{var cssObj = {"font-weight" : "normal"};$("#texto").css(cssObj);}});
$("#italica").change(function() {if ($("#italica").is(':checked')){var cssObj = {"font-style" : "italic"};$("#texto").css(cssObj);}else{var cssObj = {"font-style" : "normal"};$("#texto").css(cssObj);}});
$("#colorLetra").change(function() {$("#texto").css("color",$(this).val());});	 
$("#fontAli").change(function() {$("#texto").css("text-align",$(this).find("option:selected").text());});
$("#sombraTexto").change(function() {if ($("#sombraTexto").is(':checked')){$("#texto").css("text-shadow","3px 3px 2px rgba(150,150,150,0.9)");}else{$("#texto").css("text-shadow","none");}});
$("#xiro").change(function() {if ($("#xiro").val()<-179){$("#xiro").val("-180")}if ($("#xiro").val()>180){$("#xiro").val("180")}});
$("#transparencia").change(function() {if ($("#transparencia").val()<0){$("#transparencia").val("0")}if ($("#transparencia").val()>1){$("#transparencia").val("1")}});
$("#borde").change(function() {if ($("#borde").val()>49){$("#borde").val("49")}});
$("#corFondo").change(function() {$("#texto").css(" backgroundColor",$(this).val());});	
$("#transparente").change(function() {if ($("#transparente").is(":checked")){var cssObj = {"background-color" : "#ffffff"};} else{ var cssObj = {"background-color" : "#"+$("#corFondo").val()};} $("#texto").css(cssObj);});

	 $("#xiroImg").change(function() {
	 	if ($("#xiroImg").val()<-179){$("#xiroImg").val("-180")}
		if ($("#xiroImg").val()>180){$("#xiroImg").val("180")}
	 });
	 
	 $("#transparenciaImg").change(function() {
	 	if ($("#transparenciaImg").val()<0){$("#transparenciaImg").val("0")}
		if ($("#transparenciaImg").val()>1){$("#transparenciaImg").val("1")}
	 });

	 $("#bordeImg").change(function() {
	 	if ($("#bordeImg").val()>49){$("#bordeImg").val("49")}
	 });
	 $("#anchoOriginal").change(function() {
			if ($("#anchoOriginal").val()<50){$("#anchoOriginal").val("50")}
			if ($("#anchoOriginal").val()>2000){$("#anchoOriginal").val("2000")}
	 });
	 $("#anchoThumb").change(function() {
			if ($("#anchoThumb").val()<25){$("#anchoThumb").val("25")}
			if ($("#anchoThumb").val()>2000){$("#anchoThumb").val("2000")}
	 });
	  $( "#sliderPoly" ).slider({min: 3, max: 29, value: 3, orientation: "vertical", slide: function( event, ui ) {drawPoly=ui.value;$( "#sliderPoly .ui-slider-handle").text(drawPoly);}});
	  $( "#sliderCanvas" ).slider({min: 1,max: 29,value: 1,orientation: "vertical",slide: function( event, ui ) {$( "#amount" ).val( ui.value );pizarra_canvas = document.getElementById("canvas01");pizarra_context = pizarra_canvas.getContext("2d");pizarra_context.lineWidth = $( "#amount" ).val();$( "#sliderCanvas .ui-slider-handle").text($( "#amount" ).val());}});
	  $( "#amount" ).val( $( "#sliderCanvas" ).slider( "value" ) );
$("#bNewText").click(function() {crearNuevoTexto();});
$("#bProperties").click(function() {editProperties();});
$("#bNewBackGround").click(function() {crearNuevoBack();});
$("#bNewImage").click(function() {crearNuevaImagen();});
$("#bNewSound").click(function() {crearNuevoAudio();});
$("#bNewMovie").click(function() {crearNuevoVideo();});
$("#bNewEmbed").click(function() {crearNuevoEmbed();});
$("#bNewCanvas").click(function() {crearNuevoCanvas();});

}); 	 

function iniArrayObjects(){
	$.ajaxSetup({async:false});
	$.get("giveXMLBack.php",{folderG:folderGroup,folderG:folderGroup,typeObj:"list"},function(data){
		aObjects=data.listId.split("|");
		aDate=data.listDt.split("|");
		aType=data.listType.split("|");
   }, "json");	
   $.ajaxSetup({async:true});
}
function doRefresh(){
	if (isRefresh){
recharge=window.setInterval("reFresh()",10000);
		$("#bRefresh").removeClass("ui-priority-secondary");
		$("#bRefresh").addClass("ui-priority-primary");
		isRefresh=false;
	}
	else{
		window.clearInterval(recharge);
		$("#bRefresh").removeClass("ui-priority-primary");
		$("#bRefresh").addClass("ui-priority-secondary");
		isRefresh=true;
	}
}
function reFresh(){
	$("#bRefresh").addClass("ui-state-hover");
	cargaElementos();
	$("#bRefresh").removeClass("ui-state-hover");
}
function GoBack(){ if (selected==null){ window.location.href = "../index.php";}}
function cargaElementos(){
	if (aObjectsOld[0]=="init"){
		$.get("giveXMLBack.php",{folderG:folderGroup,folderG:folderGroup,typeObj:"back"},function(data){
			aplyStyle("pizarra",data.cssStyle);								 
   		}, "json");
		$.get("giveXMLBack.php",{folderG:folderGroup,folderG:folderGroup,typeObj:"objects"},function(data){
			var vecId=data.listId.split("~");
			var vecType=data.listType.split("~");
			var vecAlt=data.listAlt.split("~");
			var vecCom=data.listComent.split("~");
			var vecIH=data.listInnerHtml.split("~");
			var vecLink=data.listLink.split("~");
			var vecCss=data.listCss.split("~");
			for (var i = 0; i < data.num; i++) {
				if (vecType[i]=="Text"){
					nT=newText(vecIH[i],false);
					var pre=String(vecId[i]);
					while (pre.length<3){pre="0"+pre;}
					$(nT).attr("id",pre+"_Text");
					$(nT).attr("title",vecLink[i]);
					aplyStyle(pre+"_Text",vecCss[i]);
				}
				if (vecType[i]=="Image"){
					nT=createImage(vecId[i],vecAlt[i],vecCom[i],vecIH[i],vecLink[i],vecCss[i]);
				}
				if (vecType[i]=="Audio"){
					nT=createMedia(vecId[i],vecIH[i],vecCss[i],"Audio");
				}
				if (vecType[i]=="Video"){
					nT=createMedia(vecId[i],vecIH[i],vecCss[i],"Video");
				}
				if (vecType[i]=="Embed"){
					nT=createEmbed(vecId[i],recodificaIH(vecIH[i]),vecCss[i]);
				}
			}
   		}, "json");
		aObjectsOld=aObjects.slice(0);
		aDateOld=aDate.slice(0);
		aTypeOld=aType.slice(0);
	}
	else{
		aObjectsOld=aObjects.slice(0);
		aDateOld=aDate.slice(0);
		aTypeOld=aType.slice(0);
		iniArrayObjects();
		if (aDateOld[0]!=aDate[0]){
			$.get("giveXMLBack.php",{folderG:folderGroup,folderG:folderGroup,typeObj:"back"},function(data){
				aplyStyle("pizarra",data.cssStyle);								 
   			}, "json");
		}
		for (var i = 1; i < aObjects.length; i++) {
			var exists=false;
			for (var z = 1; z < aObjectsOld.length; z++) {
				if (aObjectsOld[z]==aObjects[i]){
					exists=true;
					if (aDateOld[z]!=aDate[i]){
						if (aType[i]=="Text"){
							 nId=parseInt(aObjectsOld[z],10);
							 var nameObject=String(aObjectsOld[z]);
							 while (nameObject.length<3){nameObject="0"+nameObject;}
							 nameObject=nameObject+"_Text";
							  $.ajaxSetup({async:false});
							$.get("giveXMLBack.php",{folderG:folderGroup,typeObj:"getParaText", numId:nId},function(data){
								document.getElementById(nameObject).innerHTML=data.IH;
								$("#"+nameObject).attr("title",data.linkValue);
								aplyStyle(nameObject,data.cssStyle);								 
							}, "json");
							$.ajaxSetup({async:true});
						}
						if (aType[i]=="Image"){
							nId=parseInt(aObjectsOld[z],10);
							 var nameObject=String(aObjectsOld[z]);
							 while (nameObject.length<3){nameObject="0"+nameObject;}
							 nameObject=nameObject+"_Image";
							  $.ajaxSetup({async:false});
							$.get("giveXMLBack.php",{folderG:folderGroup,typeObj:"getParaText", numId:nId},function(data){
								var ele= document.getElementById(nameObject)
								var imaSel=ele.getElementsByTagName("img");
								$(imaSel).attr("src",data.IH);
								$(imaSel).attr("alt",data.altValue);
								$(imaSel).attr("longdesc",data.comentValue);
								$("#"+nameObject).attr("title",data.linkValue);
								aplyStyle(nameObject,data.cssStyle);								 
							}, "json");
							$.ajaxSetup({async:true});
						}
						if (aType[i]=="Audio"){
							nId=parseInt(aObjectsOld[z],10);
							 var nameObject=String(aObjectsOld[z]);
							 while (nameObject.length<3){nameObject="0"+nameObject;}
							 nameObject=nameObject+"_Audio";
							  $.ajaxSetup({async:false});
							$.get("giveXMLBack.php",{folderG:folderGroup,typeObj:"getParaText", numId:nId},function(data){
								aplyStyle(nameObject,data.cssStyle);								 
							}, "json");
							$.ajaxSetup({async:true});
						}
						if (aType[i]=="Video"){
							nId=parseInt(aObjectsOld[z],10);
							 var nameObject=String(aObjectsOld[z]);
							 while (nameObject.length<3){nameObject="0"+nameObject;}
							 nameObject=nameObject+"_Video";
							  $.ajaxSetup({async:false});
							$.get("giveXMLBack.php",{folderG:folderGroup,typeObj:"getParaText", numId:nId},function(data){
								aplyStyle(nameObject,data.cssStyle);								 
							}, "json");
							$.ajaxSetup({async:true});
						}
						if (aType[i]=="Embed"){
							nId=parseInt(aObjectsOld[z],10);
							 var nameObject=String(aObjectsOld[z]);
							 while (nameObject.length<3){nameObject="0"+nameObject;}
							 nameObject=nameObject+"_Embed";
							  $.ajaxSetup({async:false});
							$.get("giveXMLBack.php",{folderG:folderGroup,typeObj:"getParaText", numId:nId},function(data){
								aplyStyle(nameObject,data.cssStyle);								 
							}, "json");
							$.ajaxSetup({async:true});
						}
						aDateOld[z]=aDate[i];	
					}
				}
			}
			if (!exists){
				nId=parseInt(aObjects[i],10);
				var pre=String(nId);
				while (pre.length<3){pre="0"+pre;}				
				if (aType[i]=="Text"){
						if (document.getElementById(pre+"_Text")==null){						
							$.get("giveXMLBack.php",{folderG:folderGroup,typeObj:"getParaText", numId:nId},function(data){
								nT=newText(data.IH,false);
								$(nT).attr("id",pre+"_Text");
								$(nT).attr("title",data.linkValue);
								aplyStyle(pre+"_Text",data.cssStyle);	
							}, "json");
						}
				}
				if (aType[i]=="Image"){
					if (document.getElementById(pre+"_Image")==null){
						$.get("giveXMLBack.php",{folderG:folderGroup,typeObj:"getParaText", numId:nId},function(data){
								nT=createImage(pre,data.altValue,data.comentValue,data.IH,data.linkValue,data.cssStyle);	
						}, "json");
					}
				}
				if (aType[i]=="Audio"){
					if (document.getElementById(pre+"_Audio")==null){
						$.get("giveXMLBack.php",{folderG:folderGroup,typeObj:"getParaText", numId:nId},function(data){
								nT=createMedia(pre,data.IH,data.cssStyle,"Audio");	
						}, "json");
					}
				}
				if (aType[i]=="Video"){ 
					if (document.getElementById(pre+"_Video")==null){
						$.get("giveXMLBack.php",{folderG:folderGroup,typeObj:"getParaText", numId:nId},function(data){
								nT=createMedia(pre,data.IH,data.cssStyle,"Video");	
						}, "json");
					}
				}
				if (aType[i]=="Embed"){ 
					if (document.getElementById(pre+"_Embed")==null){
						$.get("giveXMLBack.php",{folderG:folderGroup,typeObj:"getParaText", numId:nId},function(data){
								nT=createEmbed(pre,recodificaIH(data.IH),data.cssStyle);	
						}, "json");
					}
				}
			}
		}
		for (var z = 1; z < aObjectsOld.length; z++) {
			exists=false;
			for (var i = 1; i < aObjects.length; i++) {
				if (aObjectsOld[z]==aObjects[i]){
					exists=true;
				}
			}
			if (!exists){
				nId=parseInt(aObjectsOld[z],10);
				var pre=String(nId);
				while (pre.length<3){pre="0"+pre;}
				if (aTypeOld[z]=="Text"){
					nObj=document.getElementById(pre+"_Text");
					if (nObj!=null){nObj.parentNode.removeChild(nObj);}
				}
				if (aTypeOld[z]=="Image"){
					nObj=document.getElementById(pre+"_Image");
					if (nObj!=null){nObj.parentNode.removeChild(nObj);}
				}
				if (aTypeOld[z]=="Audio"){
					nObj=document.getElementById(pre+"_Audio");
					if (nObj!=null){nObj.parentNode.removeChild(nObj);}
				}
				if (aTypeOld[z]=="Video"){
					nObj=document.getElementById(pre+"_Video");
					if (nObj!=null){nObj.parentNode.removeChild(nObj);}
				}
				if (aTypeOld[z]=="Embed"){
					nObj=document.getElementById(pre+"_Embed");
					if (nObj!=null){nObj.parentNode.removeChild(nObj);}
				}
			}
		}
	}
}
function aplyStyle(object,cssStyle){
	var element=document.getElementById(object);
	var type=0;
	var vec=cssStyle.split("|");
	for(i=0;i<(vec.length-1);i++){
		var eleStyle=vec[i].split(":");
		if (eleStyle.length==2){
			$(element).css(eleStyle[0],eleStyle[1]);
		}
		else{
			$(element).css(eleStyle[0],eleStyle[1]+":"+eleStyle[2]);
		}
	}
	if(element.id!="pizarra"){
		$(element).css("position", "absolute");
	}
}
function recodificaIH(codigo){
	do {
    	codigo = codigo.replace("*;","<");
	} while(codigo.indexOf("*;") >= 0);
	do {
    	codigo = codigo.replace(";*",">");
	} while(codigo.indexOf(";*") >= 0);
	
	do {
    	codigo = codigo.replace("||",'"');
	} while(codigo.indexOf("||") >= 0);
	return codigo;
}
function editProperties(){
	var thumb="";
	var tit="";
	var fXML="";
	if (selected==null){
		$.ajaxSetup({async:false}); 
		$.get("giveXMLShow.php",{folderG:folderGroup,typeObj:"giveMeProperties"},function(data){
			thumb=data.th;
			tit=data.tit;
			fXML=data.fol;
		}, "json");
		$.ajaxSetup({async:true});
		$("#comentaProper").val(tit);
		if ($.trim(thumb).length==0){
			$("#ImgProperties").attr("src",fXML+"/thumb_posterShow.png");
		}
		else{
			$("#ImgProperties").attr("src",thumb);
		}
		
		abreDialog("#editProperties");
	}
}



function crearNuevoBack(){
  if (selected==null){
	$.ajaxSetup({async:false}); 
	$.get("giveXMLBack.php",{folderG:folderGroup,typeObj:"isOpenBack"},function(data){
		if (data.isOpen=="N"){
			adiante=true;
		}
		else{
			editOnTime(data.dtOpen);
			if (seguir){
document.getElementById("errorOpen").innerHTML=" Cambio non permitido -> "+data.usrOpen+" estÃ¡ editando o obxecto.";
				$("#errorOpen").css("visibility","visible");
				InitializeTimer();
				adiante=false;
			}
			else{
				adiante=true;			
			}
		}
    }, "json");
	$.ajaxSetup({async:true});
	if (adiante){
		$.post("openEditXML.php",{folderG:folderGroup,typeObj:"0"},function(data){},"json");
		if ($("#pizarra").css("background-image")!="none"){$("#haiImaxenBack").attr("checked","checked");}
		else{$("#haiImaxenBack").removeAttr("checked");}
		if ($("#pizarra").css("background-color")!=null){
			var valor=colorToHex($("#pizarra").css("background-color"));
			valor=valor.substring(1,8);
		}
		else{
			var valor="FFFFFF";
		}
		$("#colorBack").val(valor);
		if ($("#pizarra").css("background-position")=="50% 100%"){$("#positionBack").val("bottom")};
		if ($("#pizarra").css("background-position")=="50% 50%"){$("#positionBack").val("center")};
		if ($("#pizarra").css("background-position")=="0% 0%"){$("#positionBack").val("inherit")};
		if ($("#pizarra").css("background-position")=="0% 50%"){$("#positionBack").val("left")};
		if ($("#pizarra").css("background-position")=="100% 50%"){$("#positionBack").val("right")};
		if ($("#pizarra").css("background-position")=="50% 0%"){$("#positionBack").val("top")};
		if ($("#pizarra").css("background-position")=="undefined"){$("#positionBack").val("center")};		
		$("#repeatBack").val($("#pizarra").css("background-repeat"));
		abreDialog("#backGroundDialog");
	}
  }
}
function crearNuevoEmbed(){
	if (selected==null){
		abreDialog("#embedNew");
	}
}
function crearNuevoVideo(){
	if (selected==null){
		$("#errorFileNA").css("visibility","hidden");
		$("#isAudio").removeAttr("checked");
		abreDialog("#mediaNew");
	}
}
function crearNuevoAudio(){
	if (selected==null){
		$("#errorFileNA").css("visibility","hidden");
		$("#isAudio").attr("checked","checked");
		abreDialog("#mediaNew");
	}
}
function crearNuevaImagen(){
	if (selected==null){
		$("#errorFileNAImg").css("visibility","hidden");
		document.getElementById("aImaxen").style.visibility="visible";
		$("#newImg").attr("checked","checked"); 		 
		$("#comentaImaxen").val("");
		$("#altImaxen").val("");
		$("#urlImaxen").val("http://");
		abreDialog("#imageNew");
	}
}
function crearNuevoTexto(){
	if (selected==null){
	   document.editarTexto.texto.value="";	
	   $("#texto").css("font-family","Verdana, Geneva, sans-serif");
	   $("#texto").css("font-size","12px");
	   $("#texto").css("font-weight","400");
	   $("#texto").css("font-style","normal");
	   $("#texto").css("color","#000000");
	   $("#texto").css("text-align","justify");
	   $("#texto").css("background","transparent");
	   $("#textoAncho").val("200");
	   $("#textoAlto").val("25");
	   $("#fontName").val("Verdana,Geneva,sans-serif");
	   $("#tamano").val("12");
	   $("#negrilla").removeAttr("checked");
	   $("#italica").removeAttr("checked");
	   $("#colorLetra").val("#000000");		
	   $("#xiro").val("0");
	   $("#fontAli").val("justify");
	   $("#transparencia").val("1");
	   $("#borde").val("0");
	   $("#corFondo").val("#ffffff");
	   $("#url").val("http://");
	   $("#newItem").attr("checked","checked");
	   abreDialog('#editarDialog');
	}
}
function abreDialog(ide){
	   var dialogA = $(ide).dialog();
	   zIndexMax=parseInt(giveZindex(),10);
	   var zIndex = dialogA.dialog( "option", "zIndex" );
	   if (zIndex=="auto"){zIndex=0}
	   
	   if (zIndex<zIndexMax){
		    zIndexMax=zIndexMax+1;
			$(".ui-dialog").css("zIndex",zIndexMax);
			dialogA.dialog( "option", "zIndex", zIndexMax );
	   }
	   if (navigator.appName == 'Microsoft Internet Explorer'){
 		  var sizeH=dialogA.height()+350;
	   	  dialogA.dialog({height:sizeH});
	   }
	   dialogA.dialog("open");
	    if ($(".ui-widget-overlay")[0]){var ovDiv=$(".ui-widget-overlay")[0];if ($(ovDiv).hasClass('ui-front')){$(ovDiv).remove();}}
	   
}
function editOnTime(time){
	$.get("ardoraPosterFunctions.php",{typeFunc:"giveMeDate"},function(data){
		
		if (time.substr(0,10)!=data.servDate.substr(0,10)){
			seguir=false;
		}
		else{
			var hourOpen=parseInt(time.substr(11,2),10)*3600+parseInt(time.substr(14,2),10)*60+parseInt(time.substr(17,2),10);
			var hourServer=parseInt(data.servDate.substr(11,2),10)*3600+parseInt(data.servDate.substr(14,2),10)*60+parseInt(data.servDate.substr(17,2),10);
			if (hourServer-hourOpen>maxTmpEdit){
				seguir=false;
			}
			else{
				seguir=true;
			}
		}
    }, "json");
}
function giveZindex(){
	var valueZindex=0;
	capas=$("*[id]");
	for (i=0;i<capas.length;i++){
		if (parseInt($(capas[i]).css("z-index"),10)>valueZindex){
				if ($(capas[i]).attr("id").substring(3,4)=="_"){ 
					valueZindex=parseInt($(capas[i]).css("z-index"),10);
				}
		}
	}
	return valueZindex;
}
function colorToHex(color) {
    if (color.substr(0, 1) === '#') {
        return color;
    }
    var digits = /(.*?)rgb\((\d+), (\d+), (\d+)\)/.exec(color);   
    var red = parseInt(digits[2],10);
    var green = parseInt(digits[3],10);
    var blue = parseInt(digits[4],10);
    var rgb = blue | (green << 8) | (red << 16);
    return digits[1] + '#' + rgb.toString(16);
};
function InitializeTimer(){ secs = 10; StartTheTimer();}
function StopTheClock(){
   if(timerRunning)
      clearTimeout(timerID); timerRunning = false;
}
function StartTheTimer(){
   if (secs==0){
      StopTheClock();
      $("#errorOpen").css("visibility","hidden");
	  $("#errorFileNABack").css("visibility","hidden");
	  $("#errorFileNAImg").css("visibility","hidden");
	  $("#errorFileNA").css("visibility","hidden");
	  $("#errorFileNAPro").css("visibility","hidden");
   }
   else{
      self.status = secs; secs = secs - 1; timerRunning = true; timerID = self.setTimeout("StartTheTimer()", 1000);
   }
}
function permite(elEvento, permitidos) {
  var numeros = "0123456789";
  var numerosN = "-0123456789";
  var numerosD = ".0123456789";
  var caracteres = " abcdefghijklmnñopqrstuvwxyzçABCDEFGHIJKLMNÑOPQRSTUVWXYZÇ";
  var numeros_caracteres = numeros + caracteres;
  var teclas_especiales = [8, 37, 39, 46];
  switch(permitidos) {
    case 'num':
      permitidos = numeros;
      break;
	case 'numN':
      permitidos = numerosN;
      break;
	case 'numD':
      permitidos = numerosD;
      break;
    case 'car':
      permitidos = caracteres;
      break;
    case 'num_car':
      permitidos = numeros_caracteres;
      break;
  }
  var evento = elEvento || window.event;
  var codigoCaracter = evento.charCode || evento.keyCode;
  var caracter = String.fromCharCode(codigoCaracter);
  var tecla_especial = false;
  for(var i in teclas_especiales) {
    if(codigoCaracter == teclas_especiales[i]) {
      tecla_especial = true;
      break;
    }
  }
  return permitidos.indexOf(caracter) != -1 || tecla_especial;  
}
