/*ardoraPoster, created by ARDORA www.webardora.net

Copyright (C) <2011>  <José Manuel Bouzán M.>

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
counter = 0; valueZ=10; var selected=null; father= new Array(); var openButtonTopBar=true;
var maxTmpEdit=300;
var isOpenCanvas=false; var seguir=true; var adiante=false;
var isRefresh=true;
var recharge;
aObjects= new Array(); aDate= new Array(); aType= new Array(); aObjectsOld= new Array(); aDateOld= new Array(); aTypeOld= new Array(); 
folderGroup=""; var drawSide="L"; var drawTool="Pen"; var drawCanvasColor="#000"; var drawPoly=3;
$(document).ready(function(){
   folderGroup=document.getElementById("path").innerHTML;
   $.get("giveXMLShow.php",{folderG:folderGroup,typeObj:"giveMeProperties"},function(data){
			thumb=data.th; tit=data.tit; fXML=data.fol;
			document.getElementById("jobTitle").innerHTML=tit;
	}, "json");
doRefresh();
   $(".newTextDrag").draggable({
      helper:"clone",
      containment: "pizarra",
      stop:function(ev, ui) {
         var pos=$(ui.helper).offset();
         objName = "#cloneNewText"+counter
         $(objName).css({"left":pos.left,"top":pos.top});
         $(objName).removeClass("newTextDrag");
         $(objName).draggable({
            containment: "parent",
            stop:function(ev, ui) {
               var pos=$(ui.helper).offset();
            }
         });
      }
   });
   $(".newEmbedDrag").draggable({
      helper:"clone",
      containment: "pizarra",
      stop:function(ev, ui) {
         var pos=$(ui.helper).offset();
         objName = "#cloneNewEmbed"+counter
         $(objName).css({"left":pos.left,"top":pos.top});
         $(objName).removeClass("newEmbedDrag");
         $(objName).draggable({
            containment: "parent",
            stop:function(ev, ui) {
               var pos=$(ui.helper).offset();
            }
         });
      }
	});
   $(".newImageDrag").draggable({
      helper:"clone",
      containment: "pizarra",
      stop:function(ev, ui) {
         var pos=$(ui.helper).offset();
         objName = "#cloneNewImage"+counter
         $(objName).css({"left":pos.left,"top":pos.top});
         $(objName).removeClass("newImageDrag");
         $(objName).draggable({
            containment: "parent",
            stop:function(ev, ui) {
               var pos=$(ui.helper).offset();
            }
         });
      }
	}); 
     $(".newMediaDrag").draggable({
      helper:"clone",
      containment: "pizarra",
      stop:function(ev, ui) {
         var pos=$(ui.helper).offset();
         objName = "#cloneNewMedia"+counter
         $(objName).css({"left":pos.left,"top":pos.top});
         $(objName).removeClass("newMediaDrag");
         $(objName).draggable({
            containment: "parent",
            stop:function(ev, ui) {
               var pos=$(ui.helper).offset();
            }
         });
      }
	});
	 
    $("#buttonTopBar").mouseenter(function(e){
		if (!openButtonTopBar){
			$( "#buttonTopBar" ).animate({
					height: "20px"
				  }, 500, function() {
						$("#bNewBackGround").css({"visibility" : "visible"});
						$("#bNewText").css({"visibility" : "visible"});
						$("#bNewImage").css({"visibility" : "visible"});
						$("#bNewSound").css({"visibility" : "visible"});
						$("#bNewMovie").css({"visibility" : "visible"});
						$("#bNewEmbed").css({"visibility" : "visible"});
						$("#buserDataText").css({"visibility" : "visible"});
						$("#bCloseButtonTopBar").css({"visibility" : "visible"});
						
			})
			openButtonTopBar=true;	
		}
	});
	$("#edita").mousedown(function(e){						   
	   if ($(selected).attr("id").substr(4,4)=="Text"){ 
		   document.editarTexto.texto.value=$(selected).html();	
		   $("#newItem").removeAttr("checked");
		   $("#texto").css("font-family",$(selected).css("font-family"));
		   $("#texto").css("font-size",$(selected).css("font-size"));
		   $("#texto").css("font-weight",$(selected).css("font-weight"));
		   $("#texto").css("font-style",$(selected).css("font-style"));
		   $("#texto").css("color",$(selected).css("color"));
		   $("#texto").css("text-align",$(selected).css("text-align"));
		   
		   $("#texto").css("background",$(selected).css("background-color"));
		   $("#textoAncho").val($(selected).css("width").replace("px",""));
		   $("#textoAlto").val($(selected).css("height").replace("px",""));
		   if (navigator.appName != 'Microsoft Internet Explorer'){ 
				$("#texto").css("text-shadow",$(selected).css("text-shadow"));		
			   if ($(selected).css("text-shadow")!="none"){
					$("#sombraTexto").attr("checked","checked");
			   }
			   else{
				   $("#sombraTexto").removeAttr("checked");
			   }
			   if ($(selected).css("box-shadow")!="none"){
					$("#sombraBorde").attr("checked","checked");
			   }
			   else{
				   $("#sombraBorde").removeAttr("checked");
			   }
		   }
		   var tama=$(selected).css("font-size").substring(0,$(selected).css("font-size").length-2);
		   $("#fontName").val($(selected).css("font-family"));
		   $("#tamano").val(tama);
		   if ($(selected).css("font-weight")=="700"){
				$("#negrilla").attr("checked","checked");     
		   }
		   else{
				$("#negrilla").removeAttr("checked");
		   }
		   if ($(selected).css("font-style")=="italic"){
				$("#italica").attr("checked","checked");     
		   }
		   else{
				$("#italica").removeAttr("checked");
		   }
		   if ($(selected).css("color")!=null){
			var valor=colorToHex($(selected).css("color"));
			valor=valor.substring(1,8);
		   }
		   else{
				var valor="000000";
		   }
			$("#colorLetra").val(colorToHex($(selected).css("color")));
			$("#fontAli").val($(selected).css("text-align"));
			var trans=$(selected).css("opacity");
			trans=parseFloat(trans).toString();
			$("#transparencia").val(trans);
			var bor=$(selected).css("border-bottom-width").substring(0,$(selected).css("border-bottom-width").length-2);;
			$("#borde").val(bor);
			if (($(selected).css("background-color")!="transparent") &&($(selected).css("background-color").substring(0,4)!="rgba")){
				if ($(selected).css("background-color")!=null){
					var valor2=colorToHex($(selected).css("background-color")); 			
					valor2=valor2.substring(1,8);
				} else{var valor2="ffffff";}}else{var valor2="ffffff";	}
			valor2="#"+valor2;$("#corFondo").val(valor2);$("#url").val($(selected).attr("title"));
		   abreDialog('#editarDialog');
	   }
	   if ($(selected).attr("id").substr(4,5)=="Image"){//editar imaxen
			document.getElementById("aImaxen").style.visibility="hidden";
			$("#newImg").removeAttr("checked");
	 		var imaSel=selected.getElementsByTagName("img");
	 		$("#comentaImaxen").val($(imaSel).attr("longdesc"));
	 		$("#altImaxen").val($(imaSel).attr("alt"));
			$("#fontAliImg").val($(selected).css("text-align"));
			var trans=$(selected).css("opacity");
			trans=parseFloat(trans).toString();
			$("#transparenciaImg").val(trans);
			var bor=$(selected).css("border-bottom-width").substring(0,$(selected).css("border-bottom-width").length-2);;
			$("#bordeImg").val(bor);
			if ($(selected).css("color")!=null){var valor=colorToHex($(selected).css("color"));valor=valor.substring(1,8);}
		   	else{var valor="000000";}
			while (valor.length<6){
				valor="0"+valor;
			}
			$("#corBordeImg").val(valor);
			$("#corBordeImg").css("color", "#" + valor);
			if (($(selected).css("background-color")!="transparent") &&($(selected).css("background-color").substring(0,4)!="rgba")){
				if ($(selected).css("background-color")!=null){
					var valor2=colorToHex($(selected).css("background-color")); 			
					valor2=valor2.substring(1,8);
				}
				else{ var valor2="ffffff";}
			}
			else{var valor2="ffffff";}
			$("#corFondoImg").val(valor2);
			$("#corFondoImg").css("color", "#" + valor2);
			if ($(selected).css("background-color")=="transparent"){$("#transparenteImg").attr("checked","checked");}
			else{$("#transparenteImg").removeAttr("checked");}
			if (navigator.appName != 'Microsoft Internet Explorer'){
			   if ($(selected).css("box-shadow")!="none"){$("#sombraBordeImg").attr("checked","checked");}
			   else{$("#sombraBordeImg").removeAttr("checked");}
		    }
			$("#urlImaxen").val($(selected).attr("title"));
			abreDialog("#imageNew");
	   }
	   
	});
	$("#grava").mousedown(function(e){
		var el = selected;
		var st = window.getComputedStyle(el, null);
		var tr = st.getPropertyValue("-webkit-transform") ||
				 st.getPropertyValue("-moz-transform") ||
				 st.getPropertyValue("-ms-transform") ||
				 st.getPropertyValue("-o-transform") ||
				 st.getPropertyValue("transform") ||
				 "fail...";
		// With rotate(30deg)...
		// matrix(0.866025, 0.5, -0.5, 0.866025, 0px, 0px)
		//alert('Matrix: ' + tr);
		// rotation matrix - http://en.wikipedia.org/wiki/Rotation_matrix
		var values = tr.split('(')[1].split(')')[0].split(',');
		var a = values[0];
		var b = values[1];
		var c = values[2];
		var d = values[3];
		var scale = Math.sqrt(a*a + b*b);		
		// arc sin, convert from radians to degrees, round
		// DO NOT USE: see update below
		var sin = b/scale;
		//var angle = Math.round(Math.asin(sin) * (180/Math.PI));
		var angle = Math.round(Math.atan2(b, a) * (180/Math.PI));
		// works!
		//alert('Rotate: ' + angle + 'deg');
	   var nameSel=$(selected).attr("id").substring(0,3);	
	   nId=parseInt(nameSel,10); //indicamos base 10      
	   var cssObj = {
		    "position" : "absolute",
			"color" :       $(selected).css("color"),
			"left" :        $(selected).css("left"),
			"top" :         $(selected).css("top"),
			"font-size" :   $(selected).css("font-size"),
			"font-weight" : $(selected).css("font-weight"),
			"font-style" :  $(selected).css("font-style"),
			"font-family" : $(selected).css("font-family"),
			"text-align" :  $(selected).css("text-align"),
			"border-style" : "solid",
			"border-width" : $(selected).css("border-bottom-width"),
			"padding" : 	 $(selected).css("padding"),
			"z-index" : 	$(selected).css("z-index"),
			"width" :		$(selected).css("width"),
			"height" :		$(selected).css("height"),
			"transform" :	"rotate("+angle+"deg)",
			"-ms-transform" : "rotate("+angle+"deg)",
			"-webkit-transform" : "rotate("+angle+"deg)",
			"-moz-transform" : "rotate("+angle+"deg)",
			"-o-transform" : "rotate("+angle+"deg)",
			"backgroundColor": $(selected).css("backgroundColor"),
			"text-shadow" : $(selected).css("text-shadow"),
			"-moz-box-shadow" : $(selected).css("text-shadow"),
			"-webkit-box-shadow" : $(selected).css("-webkit-box-shadow"),
			"box-shadow" : $(selected).css("box-shadow"),
			"-ms-filter progid"  : $(selected).css("-ms-filter progid"),
			"filter"  : $(selected).css("filter"),
			"opacity"  : $(selected).css("opacity")
   	   };
	   

		var cssSend="";
	   for (name in cssObj){
			cssSend=cssSend+name + ":" + cssObj[name]+"|";
	   }
	   
	   if ($(selected).attr("id").substr(4,5)=="Image"){
		   	var imaSel=selected.getElementsByTagName("img");
	   		var co=$(imaSel).attr("longdesc");
	   		var al=$(imaSel).attr("alt");
			var contido=$(imaSel).attr("src");
	   }
	   if ($(selected).attr("id").substr(4,4)=="Text"){
	   		var co="-";
			var al="-";
			var contido=selected.innerHTML;
	   }
	   if ($(selected).attr("id").substr(4,5)=="Audio"){
	   		var audioSel=selected.getElementsByTagName("h6");
	   	    var co="-";
			var al="-";
			var contido=audioSel[0].innerHTML;
	   }
	   if ($(selected).attr("id").substr(4,5)=="Video"){ 
	   		var audioSel=selected.getElementsByTagName("h6");
	   	    var co="-";
			var al="-";
			var contido=audioSel[0].innerHTML;
	   }
	   if ($(selected).attr("id").substr(4,5)!="Embed"){
		   $.post("saveXMLBack.php",{
				  folderG:folderGroup,
				  typeSave:"actNewText",
				  css:cssSend,
				  url:$(selected).attr("title"),
				  txt:contido,
				  numId:nId,
				  comen:co, 
				  alter:al
		   },function(data){},"json");
	   }
	   else{
	   		$.post("saveXMLBack.php",{
				   folderG:folderGroup,
				  typeSave:"actNewEmbed",
				  numId:nId,
				  css:cssSend
		   },function(data){},"json");
	   }

	   hideButtons();
	   selected=null;
	});
	$("#cancela").mousedown(function(e){
	   nId=$(selected).attr("id");
	   $.ajaxSetup({async:false});
	   $.get("giveXMLBack.php",{folderG:folderGroup,typeObj:"getParaText", numId:nId},function(data){
			aplyStyle(nId,data.cssStyle);
	   }, "json");
	   $.post("saveXMLBack.php",{folderG:folderGroup,typeSave:"escActNewText",numId:nId},function(data){},"json");
	   $.ajaxSetup({async:true});
	   hideButtons();
	   selected=null;								 
	});
	$("#borrar").mousedown(function(e){
	   abreDialog('#borrarDialog');
	});

	$("#text_l").mousedown(function(e){
		  var cssObj = {"text-align" : "left"};
		  $(selected).css(cssObj);
	});
	$("#text_r").mousedown(function(e){
		  var cssObj = {"text-align" : "right"};
		  $(selected).css(cssObj);
	});
	$("#text_c").mousedown(function(e){
		  var cssObj = {"text-align" : "center"};
		  $(selected).css(cssObj);
	});
	$("#text_j").mousedown(function(e){
		  var cssObj = {"text-align" : "justify"};
		  $(selected).css(cssObj);
	});
	$("#opaMais").mousedown(function(e){
	   var opa=$(selected).css("opacity");
	   opa=parseFloat(opa)+parseFloat(0.1);
	   if (opa<=1){
		  var cssObj = {
			 "-ms-filter progid" : "DXImageTransform.Microsoft.Alpha(Opacity="+opa*100+")",
			 "filter" : "alpha(opacity="+opa*100+")",
			 "opacity" : opa
		  };
		  $(selected).css(cssObj);
	   }
	});
	$("#opaMenos").mousedown(function(e){
	   var opa=$(selected).css("opacity");
	   opa=parseFloat(opa)-parseFloat(0.1);
	   if (opa>.1){
		  var cssObj = {
			 "-ms-filter progid" : "DXImageTransform.Microsoft.Alpha(Opacity="+opa*100+")",
			 "filter" : "alpha(opacity="+opa*100+")",
			 "opacity" : opa
		  };
		  $(selected).css(cssObj);
	   }
	});
   $("#Agrande").mousedown(function(e){
      size=$(selected).css("font-size");
      size=size.replace("px","");
      size++;
      var cssObj = {"font-size" : size+"px"};
      $(selected).css(cssObj);
   });
   $("#Apeque").mousedown(function(e){
      size=$(selected).css("font-size");
      size=size.replace("px","");
      if (size>5){ size--;}
      var cssObj = {"font-size" : size+"px"};
      $(selected).css(cssObj);
   });
   $("#bold").mousedown(function(e){
      weight=$(selected).css("font-weight");
      if (weight=="700"){ var cssObj = {"font-weight" : "400"};}
      else{ var cssObj = {"font-weight" : "700"};}
      $(selected).css(cssObj);
   });
   $("#italic").mousedown(function(e){
      Fstyle=$(selected).css("font-style");
      if (Fstyle=="italic"){var cssObj = {"font-style" : "normal"};}
      else{ var cssObj = {"font-style" : "italic"};}
      $(selected).css(cssObj);
   });
   $("#border1").mousedown(function(e){
      size=$(selected).css("border-bottom-width");
	  size=size.replace("px","");
      size++;
      var cssObj = {"border-width" : size+"px",
	  "border-style" : "solid"};
      $(selected).css(cssObj);
   });
   $("#border0").mousedown(function(e){
      size=$(selected).css("border-bottom-width");
      size=size.replace("px","");
      if (size>0){ size--;}
      var cssObj = {"border-width" : size+"px"};
      $(selected).css(cssObj);
   });
   $("#backTrans").mousedown(function(e){var cssObj = {"background" : ""}; $(selected).css(cssObj);$("#backColor").val("#ffffff");});
   $("#fontColor").on("input", function() {$(selected).css("color",$(this).val()); });
   $("#backColor").on("input", function() {$(selected).css("background",$(this).val()); }); 

var x0; var y0; var x2; var y2;

	$("#xira").draggable({
	   start: function(e) {
		  idName=$(selected).attr("id");
		  idImage="IMGdrag"+idName.substring(8, idName.length);
		  hideButtons();
		  var cssObj = {"visibility" : "visible"};
		  $("#xira").css(cssObj);
		  var dW =$(selected).width();
		  var dH =$(selected).height();
		  x0=findPosX(selected)+dW/2;
		  y0=(-1)*(findPosY(selected)+dH/2);
	   },
	   drag: function(e) {
		  obj=document.getElementById("xira");
		  x2=findPosX(obj)+10;
		  y2=(-1)*(findPosY(obj)+10);
		  if ((x2==x0)&&(y2>y0)){angulo=0;}
		  if ((y2>y0) && (x2>x0)){
			 angTan=(y2-y0)/(x2-x0);
			 angulo=90-(Math.atan(angTan)*180/Math.PI);
		  };
		  if ((x2>x0)&&(y2==y0)){angulo=90;}
		  if ((y2<y0) && (x2>x0)){
			 angTan=(y0-y2)/(x2-x0);
			 angulo=90+(Math.atan(angTan)*180/Math.PI);
		  };
		  if ((x2==x0)&&(y2<y0)){angulo=180;}
		  if ((y2<y0) && (x2<x0)){
			 angTan=(y0-y2)/(x0-x2);
			 angulo=-180+90-(Math.atan(angTan)*180/Math.PI);
		  };
		  if ((x2<x0)&&(y2==y0)){angulo=-90;}
		  if ((y2>y0) && (x2<x0)){
			 angTan=(x0-x2)/(y2-y0);
			 angulo=-(Math.atan(angTan)*180/Math.PI);
		  };
		  var cssObj = {
			 "transform" : "rotate("+angulo+"deg)",
			 "-ms-transform" : "rotate("+angulo+"deg)",
			 "-webkit-transform" : "rotate("+angulo+"deg)",
			 "-moz-transform" : "rotate("+angulo+"deg)",
			 "-o-transform" : "rotate("+angulo+"deg)"
		  };
		  $(selected).css(cssObj);
	   },
	   stop: function() { 
			if($(selected).attr("id").substring(4,8)=="Text"){
				showButtonsText(selected);
			}
	   }
	});
	var idName; var idImage; var xRT; var yLB;
	$("#lefttop").draggable({
	   start: function(e) {
		  hideButtons();
		  idName=$(selected).attr("id");
		  idImage="IMGdrag"+idName.substring(8, idName.length);
		  var cssObj = {"visibility" : "visible"};
		  $(this).css(cssObj);
	   },
	   drag: function(e) {
		  obj=document.getElementById("rightbottom");
		  xRT=findPosX(obj);
		  obj=document.getElementById("leftbottom");
		  yLB=findPosY(obj);
		  sizeX=xRT-e.pageX+20;
		  if (sizeX<0){sizeX=sizeX*(-1);}
		  sizeY=yLB-e.pageY+20;
		  if (sizeY<0){sizeY=sizeY*(-1);}
		  var cssObj = { "left" : e.pageX+20, "top" : e.pageY+20, "width" : sizeX, "height" : sizeY }
		  $(selected).css(cssObj);
		  if (idName.substr(0,8)=="clonediv"){
			 obj=document.getElementById(idImage);
			 obj.setAttribute("width", sizeX);
			 obj.setAttribute("height", sizeY);
		  }
	   },
	   stop: function() { 
	   		if($(selected).attr("id").substring(4,8)=="Text"){
				showButtonsText(selected);
			}
	   }
	});
	$("#righttop").draggable({
	   start: function(e) {
		  hideButtons();
		  idName=$(selected).attr("id");
		  idImage="IMGdrag"+idName.substring(8, idName.length);
		  var cssObj = {"visibility" : "visible"};
		  $(this).css(cssObj);
	   },
	   drag: function(e) {
		  var dW =$(selected).width();
		  obj=document.getElementById("lefttop");
		  xRT=findPosX(obj);
		  obj=document.getElementById("leftbottom");
		  yLB=findPosY(obj);
		  sizeX=e.pageX+20-xRT;
		  if (sizeX<0){sizeX=sizeX*(-1);}
		  sizeY=yLB-e.pageY+20;
		  if (sizeY<0){sizeY=sizeY*(-1);}
		  var cssObj = { "left" : e.pageX+20-dW, "top" : e.pageY+20, "width" : sizeX, "height" : sizeY }
		  $(selected).css(cssObj);
		  if (idName.substr(0,8)=="clonediv"){
			 obj=document.getElementById(idImage);
			 obj.setAttribute("width", sizeX);
			 obj.setAttribute("height", sizeY);
		  }
	   },
	stop: function() { 
		if($(selected).attr("id").substring(4,8)=="Text"){
				showButtonsText(selected);
		}
	}
	});
	$("#leftbottom").draggable({
	   start: function(e) {
		  hideButtons();
		  idName=$(selected).attr("id");
		  idImage="IMGdrag"+idName.substring(8, idName.length);
		  var cssObj = {"visibility" : "visible"};
		  $(this).css(cssObj);
	   },
	   drag: function(e) {
		  var dH =$(selected).height();
		  obj=document.getElementById("rightbottom");
		  xRT=findPosX(obj);
		  obj=document.getElementById("lefttop");
		  yLB=findPosY(obj);
		  sizeX=xRT-e.pageX+20;
		  if (sizeX<0){sizeX=sizeX*(-1);}
		  sizeY=e.pageY-20-yLB;
		  if (sizeY<0){sizeY=sizeY*(-1);}
		  var cssObj = { "left" : e.pageX+20, "top" : e.pageY-20-dH, "width" : sizeX, "height" : sizeY}
		  $(selected).css(cssObj);
		  if (idName.substr(0,8)=="clonediv"){
			 obj=document.getElementById(idImage);
			 obj.setAttribute("width", sizeX);
			 obj.setAttribute("height", sizeY);
		  }
	   },
	   stop: function() { 
	   		if($(selected).attr("id").substring(4,8)=="Text"){
				showButtonsText(selected);
			}
	   }
	});
	$("#rightbottom").draggable({
	   start: function(e) {
		  hideButtons();
		  idName=$(selected).attr("id");
		  idImage="IMGdrag"+idName.substring(8, idName.length);
		  var cssObj = {"visibility" : "visible"};
		  $(this).css(cssObj);
	   },
	   drag: function(e) {
		  var dW =$(selected).width();
		  var dH =$(selected).height();
		  obj=document.getElementById("lefttop");
		  xRT=findPosX(obj);
		  obj=document.getElementById("righttop");
		  yLB=findPosY(obj);
		  sizeX=e.pageX+20-xRT;
		  if (sizeX<0){sizeX=sizeX*(-1);}
		  sizeY=e.pageY-20-yLB;
		  if (sizeY<0){sizeY=sizeY*(-1);}
		  var cssObj = { "left" : e.pageX-dW, "top" : e.pageY-dH, "width" : sizeX, "height" : sizeY}
		  $(selected).css(cssObj);
		  if (idName.substr(0,8)=="clonediv"){
			 obj=document.getElementById(idImage);
			 obj.setAttribute("width", sizeX);
			 obj.setAttribute("height", sizeY);
		  }
	   },
	   stop: function() { 
	   		if($(selected).attr("id").substring(4,8)=="Text"){
				showButtonsText(selected);
			}
	   }
	   });
	});
function newText(textAdd,isNew){
   counter++;
   valueZ=giveZindex()+1;
   father[counter]="addTextNew";
   var element=$("#addTextNew").clone();
   element.addClass("tempclass");
   $("#pizarra").append(element);
   $(".tempclass").attr("id","cloneNewText"+counter);
   $("#cloneNewText"+counter).removeClass("tempclass");
   fatherDIV=document.getElementById(father[counter]);
   newDiv=document.getElementById("cloneNewText"+counter);
   document.getElementById("cloneNewText"+counter).innerHTML=textAdd;
   var cssObj = {"position" : "absolute","color" : $("#texto").css("color"),"left" : "100px","top" : "100px","font-size" :$("#texto").css("font-size"),"font-weight" : $("#texto").css("font-weight"),"font-style" : $("#texto").css("font-style"),"font-family" : $("#texto").css("font-family"),"text-align" : $("#texto").css("text-align"),"border-style" : "solid","border-width" : $("#borde").val()+"px","padding" : "4px","z-index" : valueZ};
   
   if ($("#autoW").is(':checked')){cssObj["width"]="auto";cssObj["height"]="auto";}else{cssObj["width"]=$("#textoAncho").val()+"px";cssObj["height"]=$("#textoAlto").val()+"px";}
    
   var angulo=$("#xiro").val();
	   cssObj["transform"]="rotate("+angulo+"deg)";
	   cssObj["-ms-transform"]="rotate("+angulo+"deg)";
	   cssObj["-webkit-transform"]="rotate("+angulo+"deg)";
	   cssObj["-moz-transform"]="rotate("+angulo+"deg)";
	   cssObj["-o-transform"]="rotate("+angulo+"deg)";
   
   if ($("#transparente").is(':checked')){cssObj["background"]="transparent";} else{cssObj["background"]=$("#texto").css("background-color");}
   
   if ($("#sombraTexto").is(':checked')){cssObj["text-shadow"]="3px 3px 2px rgba(150,150,150,0.9)";}else{ cssObj["text-shadow"]="none";}
   
   if ($("#sombraBorde").is(':checked')){cssObj["-moz-box-shadow"]="0 0 5px #888";cssObj["-webkit-box-shadow"]="0 0 5px #888";cssObj["box-shadow"]="0 0 5px #888";}else{cssObj["-moz-box-shadow"]="none";cssObj["-webkit-box-shadow"]="none";cssObj["box-shadow"]="none";}
   
   var opa=$("#transparencia").val();
   cssObj["-ms-filter progid"]="DXImageTransform.Microsoft.Alpha(Opacity="+opa*100+")";
   cssObj["filter"]="alpha(opacity="+opa*100+")";
   cssObj["opacity"]=opa;
   $(newDiv).css(cssObj);	
   $(newDiv).attr("title",$("#url").val());	
   
   $(newDiv).mousedown(function(e){
   	  if (selected==null){ 
		  nId=parseInt($(this).attr("id").substring(0,3),10);
		  $.ajaxSetup({async:false});
		  $.get("giveXMLBack.php",{folderG:folderGroup,typeObj:"isOpen",numId:nId},function(data){
		    if (data.isOpen=="N"){	  	
				adiante=true;
		    }
		    else{
				editOnTime(data.dtOpen);
				if (seguir){
document.getElementById("errorOpen").innerHTML=" Transaction not allowed -> "+data.usrOpen+" is editing this object";
					$("#errorOpen").css("visibility","visible");
					InitializeTimer();
					adiante=false;
				}
				else{
					adiante=true;			
				}
			}
	      }, "json");
		$.ajaxSetup({async:true}); 
		if (adiante){
			$.post("openEditXML.php",{folderG:folderGroup,typeObj:"obj",numId:nId},function(data){},"json");	
			$(newDiv).draggable( "option", "disabled", false );
			valueZ=giveZindex()+1;
			var cssObj = {"z-index" : valueZ};
			$(this).css(cssObj);	
			hideButtons();
			showButtonsText(this);
			selected=this;
		}
		else{
			$(newDiv).draggable( "option", "disabled", true );
		}
	  }
	  else{
			if (selected==this){
				valueZ=giveZindex()+1;
				var cssObj = {"z-index" : valueZ};
				$(this).css(cssObj);	
				hideButtons();
				showButtonsText(this);
			}
	  }
   })  
   $(newDiv).draggable({
		  cursor: "move",
		  start: function() {
			 valueZ=giveZindex()+1;
			 var cssObj = {"z-index" : valueZ};
			 $(newDiv).css(cssObj);
			 if (selected==this){
			 	hideButtons();
			 }
		  },
		  drag: function() {		
			valueZ=giveZindex()+1;
			var cssObj = {"z-index" : valueZ};
			$(this).css(cssObj);},
		  stop: function() {
		  	if (selected==this){
				showButtonsText(this);
			}
		  }
   });
   if (isNew){ 
	   var cssSend="";
	   var num=1000;
	   var nId=0;
	   var nDate="";
	   for (name in cssObj){
			cssSend=cssSend+name + ":" + cssObj[name]+"|";
	   }
	   $.ajaxSetup({async:false});
		$.post("saveXMLBack.php",{folderG:folderGroup,typeSave:"saveNewText",css:cssSend,url:$("#url").val(),txt:textAdd},function(data){		
				var pre=String(data.id);
				while (pre.length<3){pre="0"+pre;}
				capa=document.getElementById("cloneNewText"+counter);
				$(capa).attr("id",pre+"_Text");		
				nId=data.id;
				nDate=data.vDate;
		},"json");
		$.ajaxSetup({async:true});
		num=aObjects.length;
		aObjects[num]=nId;
		aDate[num]=nDate;
		aType[num]="Text";
   }
   else{
 		return $(newDiv);   
   }
};

function newEmbed(codigo){
   counter++;
   valueZ=giveZindex()+1;
   father[counter]="addEmbedNew";
   var element=$("#addEmbedNew").clone();
   element.addClass("tempclass");
   $("#pizarra").append(element);
   $(".tempclass").attr("id","cloneNewEmbed"+counter);
   $("#cloneNewEmbed"+counter).removeClass("tempclass");
   fatherDIV=document.getElementById(father[counter]);
   newDiv=document.getElementById("cloneNewEmbed"+counter);
   document.getElementById("cloneNewEmbed"+counter).innerHTML=codigo;
   var cssObj = {
      "position" : "absolute",
      "color" : $(fatherDIV).css("color"),
      "left" : "10px",
      "top" : "10px",
      "font-size" :$(fatherDIV).css("font-size"),
      "font-weight" : $(fatherDIV).css("font-weight"),
      "font-style" : $(fatherDIV).css("font-style"),
      "font-family" : $(fatherDIV).css("font-family"),
      "text-align" : $(fatherDIV).css("text-align"),
      "border-style" : "solid",
      "border-width" : "2px",
      "padding" : "5px",
      "width" : "auto",
      "height" : "auto",
	  "transform" :	"rotate(0deg)",
	  "-ms-transform" : "rotate(0deg)",
	  "-webkit-transform" : "rotate(0deg)",
	  "-moz-transform" : "rotate(0deg)",
	  "-o-transform" : "rotate(0deg)",
      "z-index" : valueZ,
      "background-color" : $(fatherDIV).css("background-color")
   };
   $(newDiv).css(cssObj);
   $(newDiv).mousedown(function(e){
			if (selected==null){
					nId=parseInt($(this).attr("id").substring(0,3),10);
		  			$.ajaxSetup({async:false}); //pomos en synchronous mode
		  			$.get("giveXMLBack.php",{folderG:folderGroup,typeObj:"isOpen",numId:nId},function(data){
						if (data.isOpen=="N"){	  	
							adiante=true;
						}
						else{
							editOnTime(data.dtOpen);
							if (seguir){
document.getElementById("errorOpen").innerHTML=" Transaction not allowed -> "+data.usrOpen+" is editing this object";
								$("#errorOpen").css("visibility","visible");
								InitializeTimer();
								adiante=false;
							}
							else{
								adiante=true;			
							}
						}
	      			}, "json");
				  $.ajaxSetup({async:true}); //volve a ser asíncrono
				  if (adiante){
					//facemos isOpen="Y"
					$.post("openEditXML.php",{folderG:folderGroup,typeObj:"obj",numId:nId},function(data){},"json");	
					$(newDiv).draggable( "option", "disabled", false );
					valueZ=giveZindex()+1;
					var cssObj = {"z-index" : valueZ};
					$(this).css(cssObj);	
					hideButtons();
					showButtonsEmbed(this);;
					selected=this;
				  }
				  else{
					$(newDiv).draggable( "option", "disabled", true );
				  }
	  		}
	  		else{
				  if (selected==this){															   		   
					   hideButtons();				
					   valueZ=giveZindex()+1;
					   var cssObj = {"z-index" : valueZ};
					   $(this).css(cssObj);
					   showButtonsEmbed(this);
				  }
			}
		
   });
   $(newDiv).draggable({
      cursor: "move",
      start: function() {
         valueZ=giveZindex()+1;
         var cssObj = {"z-index" : valueZ};
         $(newDiv).css(cssObj);
      	 hideButtons();
      },
      drag: function() {		
	  	valueZ=giveZindex()+1;
	  	var cssObj = {"z-index" : valueZ};
      	$(this).css(cssObj);},
      stop: function() {
		  showButtonsEmbed(this);
	  }
   });
   var cssSend="";
	   var num=1000;
	   var nId=0;
	   var nDate="";
	   for (name in cssObj){
			cssSend=cssSend+name + ":" + cssObj[name]+"|";
	   }
	   $.ajaxSetup({async:false});
		$.post("saveXMLBack.php",{folderG:folderGroup,typeSave:"saveNewEmbed",css:cssSend,txt:codigo},function(data){
				var pre=String(data.id);
				while (pre.length<3){pre="0"+pre;}
				capa=document.getElementById("cloneNewEmbed"+counter);
				$(capa).attr("id",pre+"_Embed");		
				nId=data.id;
				nDate=data.vDate;
		},"json");
		$.ajaxSetup({async:true});
		num=aObjects.length;
		aObjects[num]=nId;
		aDate[num]=nDate;
		aType[num]="Embed";
};

function createEmbed(vecId, codigo, vecCss){
   counter++;
   valueZ=giveZindex()+1;
   father[counter]="addEmbedNew";
   var element=$("#addEmbedNew").clone();
   element.addClass("tempclass");
   $("#pizarra").append(element);
   $(".tempclass").attr("id","cloneNewEmbed"+counter);
   $("#cloneNewEmbed"+counter).removeClass("tempclass");
   fatherDIV=document.getElementById(father[counter]);
   newDiv=document.getElementById("cloneNewEmbed"+counter);
   document.getElementById("cloneNewEmbed"+counter).innerHTML=codigo;
   var cssObj = {
      "position" : "absolute",
      "color" : $(fatherDIV).css("color"),
      "left" : "10px",
      "top" : "10px",
      "font-size" :$(fatherDIV).css("font-size"),
      "font-weight" : $(fatherDIV).css("font-weight"),
      "font-style" : $(fatherDIV).css("font-style"),
      "font-family" : $(fatherDIV).css("font-family"),
      "text-align" : $(fatherDIV).css("text-align"),
      "border-style" : "solid",
      "border-width" : "2px",
      "padding" : "5px",
      "width" : "auto",
      "height" : "auto",
	  "transform" :	"rotate(0deg)",
	  "-ms-transform" : "rotate(0deg)",
	  "-webkit-transform" : "rotate(0deg)",
	  "-moz-transform" : "rotate(0deg)",
	  "-o-transform" : "rotate(0deg)",
      "z-index" : valueZ,
      "background-color" : $(fatherDIV).css("background-color")
   };
   $(newDiv).css(cssObj);
   $(newDiv).mousedown(function(e){
			if (selected==null){ 
					nId=parseInt($(this).attr("id").substring(0,3),10);
		  			$.ajaxSetup({async:false});
		  			$.get("giveXMLBack.php",{folderG:folderGroup,typeObj:"isOpen",numId:nId},function(data){
						if (data.isOpen=="N"){	  	
							adiante=true; 
						}
						else{
							editOnTime(data.dtOpen); 
							if (seguir){ 
document.getElementById("errorOpen").innerHTML=" Transaction not allowed -> "+data.usrOpen+" is editing this object";
								$("#errorOpen").css("visibility","visible");
								InitializeTimer();
								adiante=false;
							}
							else{
								adiante=true;			
							}
						}
	      			}, "json");
				  $.ajaxSetup({async:true}); 
				  if (adiante){
					$.post("openEditXML.php",{folderG:folderGroup,typeObj:"obj",numId:nId},function(data){},"json");	
					$(newDiv).draggable( "option", "disabled", false );
					valueZ=giveZindex()+1;
					var cssObj = {"z-index" : valueZ};
					$(this).css(cssObj);	
					hideButtons();
					showButtonsEmbed(this);;
					selected=this;
				  }
				  else{
					$(newDiv).draggable( "option", "disabled", true );
				  }
	  		}
	  		else{
				  if (selected==this){															   		   
					   hideButtons();				
					   valueZ=giveZindex()+1;
					   var cssObj = {"z-index" : valueZ};
					   $(this).css(cssObj);
					   showButtonsEmbed(this);
				  }
			}
   });
   $(newDiv).draggable({
      cursor: "move",
      start: function() {
         valueZ=giveZindex()+1;
         var cssObj = {"z-index" : valueZ};
         $(newDiv).css(cssObj);
      	 hideButtons();
      },
      drag: function() {		
	  	valueZ=giveZindex()+1;
	  	var cssObj = {"z-index" : valueZ};
      	$(this).css(cssObj);},
      stop: function() {
		  showButtonsEmbed(this);
	  }
   });
	
	var pre=String(vecId);
	while (pre.length<3){pre="0"+pre;}
	$(newDiv).attr("id",pre+"_Embed");
	aplyStyle(pre+"_Embed",vecCss);
	return $(newDiv);
};

var newBackImage = function(){ 
	var iFrame = document.getElementById("estadoUpLoadBack").contentDocument.getElementsByTagName("body")[0];
	var loading = document.getElementById("loadingBack");
	if(iFrame.innerHTML == ""){
		setTimeout ( newBackImage, 2000 );
	}
	else{
		if(iFrame.innerHTML.substr(0,7) == "success"){
			$("#pizarra").css("background-image","url('"+iFrame.innerHTML.substring(7)+"')");
			loading.style.display = "none";
			newBackOld();	
		}
		else{
			loading.style.display = "none";
			alert("Error: "+ iFrame.innerHTML);
		}
	}
}
var newBack = function(){ 
	$("#pizarra").css("background-image","none");
	newBackOld();
}
var newBackOld = function(){ 
	$("#pizarra").css("background-color","#"+$("#colorBack").val());
	$("#pizarra").css("background-position",$("#positionBack").val());
	$("#pizarra").css("background-repeat",$("#repeatBack").val());
	$("#backGroundDialog").dialog( "close" );
	if ($("#pizarra").css("background-image")!="none"){
		
		var pos=$("#pizarra").css("background-image").indexOf("ardoraWorkFiles");
		var subStrn=$("#pizarra").css("background-image").substring(pos).replace("\'","");
		subStrn=subStrn.replace('\"','');
		var cssObj = "background-image:"+"url(../"+subStrn+"|";
	}
	else{
    	var cssObj = "background-image:"+$("#pizarra").css("background-image")+"|";
	}
	cssObj=cssObj+"background-color:"+colorToHex($("#pizarra").css("background-color"))+"|";
	cssObj=cssObj+"background-position:"+$("#pizarra").css("background-position")+"|";
	cssObj=cssObj+"background-repeat:"+$("#pizarra").css("background-repeat")+"|";	
	$.post("saveXMLBack.php",{folderG:folderGroup,typeSave:"saveBack",css:cssObj},function(data){},"json");
}
var newImage = function(){
	valuezZ= giveZindex()+1;
	var iFrame = document.getElementById("estadoUpLoad").contentDocument.getElementsByTagName("body")[0];
	var loading = document.getElementById("loading");
	if(iFrame.innerHTML == ""){setTimeout ( newImage, 2000 );}
	else{
		if(iFrame.innerHTML.substr(0,7) == "success"){		
			loading.style.display = "none";
			document.getElementById("estadoUpLoad").style.display = "block";
			counter++;
 			father[counter]="addImageNew";
   			var element=$("#addImageNew").clone(); 
            element.addClass("tempclass");
   			$("#pizarra").append(element);
   			$(".tempclass").attr("id","cloneNewImage"+counter);
   			$("#cloneNewImage"+counter).removeClass("tempclass");
   			fatherDIV=document.getElementById(father[counter]);
   			newDiv=document.getElementById("cloneNewImage"+counter);
			var cssObj = {
               "position" : "absolute",
			   "transform" : "rotate("+$("#xiroImg").val()+"deg)",
			   "-ms-transform" : "rotate("+$("#xiroImg").val()+"deg)",
			   "-webkit-transform" : "rotate("+$("#xiroImg").val()+"deg)",
			   "-moz-transform" : "rotate("+$("#xiroImg").val()+"deg)",
			   "-o-transform" : "rotate("+$("#xiroImg").val()+"deg)",
			   "-ms-filter progid" : "DXImageTransform.Microsoft.Alpha(Opacity="+$("#transparenciaImg").val()*100+")",
			   "filter" : "alpha(opacity="+$("#transparenciaImg").val()*100+")",
			   "opacity" : $("#transparenciaImg").val(),
			   "border-style" : "solid",
      			"border-width" : $("#bordeImg").val()+"px",
				"color": "#"+$("#corBordeImg").val(),
				"display": "table",
				"width" : $("#anchoThumb").val()+"px",
      			"height" : "auto",
				"top": "10px",
				"left": "10px",
				"text-align": $("#fontAliImg").val(),
				"z-index" : valueZ
            };
            
			if ($("#transparenteImg").is(':checked')){cssObj["background"]="transparent";}
		    else{cssObj["background"]=$("#corFondoImg").val();}			
			if ($("#sombraBordeImg").is(':checked')){
				cssObj["-moz-box-shadow"]="0 0 5px #888";
 	   			cssObj["-webkit-box-shadow"]="0 0 5px #888";
 	   			cssObj["box-shadow"]="0 0 5px #888";
	        }
		    else{
				cssObj["-moz-box-shadow"]="none";
 	   			cssObj["-webkit-box-shadow"]="none";
 	   			cssObj["box-shadow"]="none";   
	        }
		   
			$(newDiv).css(cssObj);
			
			$(newDiv).attr("align",$("#fontAliImg").val());
            $(newDiv).attr("title",$("#urlImaxen").val());
			newImg=document.createElement("img");
            newImg.setAttribute("id", "IMG_drag"+counter);
			newImg.setAttribute("alt",$("#altImaxen").val());
			newImg.setAttribute("longdesc",$("#comentaImaxen").val());
			var cssObj1= {
				"display":"table-cell",
				"vertical-align":"middle"
			};
			$(newImg).css(cssObj1);
			newImg.src=iFrame.innerHTML.substring(7);

            newDiv.appendChild(newImg);
			$("#cloneNewImage"+counter).mousedown(function(e){
			   if (selected==null){
		  			nId=parseInt($(this).attr("id").substring(0,3),10);
		  			$.ajaxSetup({async:false}); 
		  			$.get("giveXMLBack.php",{folderG:folderGroup,typeObj:"isOpen",numId:nId},function(data){
						if (data.isOpen=="N"){	  	
							adiante=true; 
						}
						else{
							editOnTime(data.dtOpen); 
							if (seguir){
document.getElementById("errorOpen").innerHTML=" Transaction not allowed -> "+data.usrOpen+" is editing this object";
								$("#errorOpen").css("visibility","visible");
								InitializeTimer();
								adiante=false;
							}
							else{
								adiante=true;			
							}
						}
	      			}, "json");
				  $.ajaxSetup({async:true});
				  if (adiante){
					$.post("openEditXML.php",{folderG:folderGroup,typeObj:"obj",numId:nId},function(data){},"json");	
					$(newDiv).draggable( "option", "disabled", false );
					valueZ=giveZindex()+1;;
					var cssObj = {"z-index" : valueZ};
					$(this).css(cssObj);	
					hideButtons();
					showButtons(this);
					selected=this;
				  }
				  else{
					$(newDiv).draggable( "option", "disabled", true );
				  }
	  		}
	  		else{
				  if (selected==this){															   		   
					   hideButtons();				
					   valueZ=giveZindex()+1;;
					   var cssObj = {"z-index" : valueZ};
					   $(this).css(cssObj);
					   showButtons(this);
				  }
			}
            });
            $("#cloneNewImage"+counter).draggable({
               cursor: "move",
               start: function() {
                  valueZ=giveZindex()+1;;
                  var cssObj = {"z-index" : valueZ};
                  $(this).css(cssObj);
                  hideButtons();
               },
               drag: function() {},
               stop: function() {
			   		showButtons(this);
			   }
            });
			loading.style.display = "none";		
			   var cssSend="";
			   var num=1000;
			   var nId=0;
			   var nDate="";
			   var contido=$(newImg).attr("src");
			   for (name in cssObj){
					cssSend=cssSend+name + ":" + cssObj[name]+"|";
			   }
			   $.ajaxSetup({async:false});
			   $.post("saveXMLBack.php",{folderG:folderGroup,typeSave:"saveNewImage",css:cssSend,url:$("#urlImaxen").val(),com:$("#comentaImaxen").val(),alt:$("#altImaxen").val(),imgSRC:contido},function(data){
						var pre=String(data.id);
						while (pre.length<3){pre="0"+pre;}
						capa=document.getElementById("cloneNewImage"+counter);
						$(capa).attr("id",pre+"_Image");		
						nId=data.id;
						nDate=data.vDate;
			   },"json");
			   $.ajaxSetup({async:true});
			   num=aObjects.length;
			   aObjects[num]=nId;
			   aDate[num]=nDate;
			   aType[num]="Image";
			   $("#imageNew").dialog( "close" );
		}
		else{
			loading.style.display = "none";
			alert("Error: "+ iFrame.innerHTML);
		}
	}
}
function createImage(vecId,vecAlt,vecCom,vecIH,vecLink,vecCss){
	counter++;
 	father[counter]="addImageNew";
   	var element=$("#addImageNew").clone(); 
    element.addClass("tempclass");
   	$("#pizarra").append(element);
   	$(".tempclass").attr("id","cloneNewImage"+counter);
   	$("#cloneNewImage"+counter).removeClass("tempclass");
   	fatherDIV=document.getElementById(father[counter]);
   	newDiv=document.getElementById("cloneNewImage"+counter);
    
	$(newDiv).attr("title",vecLink);
	
	newImg=document.createElement("img");
    newImg.setAttribute("id", "IMG_drag"+counter);
	newImg.setAttribute("alt",vecAlt);
	newImg.setAttribute("longdesc",vecCom);
	var cssObj1= {"display":"table-cell","vertical-align":"middle"};
	$(newImg).css(cssObj1);
	newImg.src=vecIH;
    newDiv.appendChild(newImg);
	$("#cloneNewImage"+counter).mousedown(function(e){
			   if (selected==null){
		  			nId=parseInt(vecId,10);
		  			$.ajaxSetup({async:false});
		  			$.get("giveXMLBack.php",{folderG:folderGroup,typeObj:"isOpen",numId:nId},function(data){
						if (data.isOpen=="N"){	  	
							adiante=true; 
						}
						else{
							editOnTime(data.dtOpen);
							if (seguir){
document.getElementById("errorOpen").innerHTML=" Transaction not allowed -> "+data.usrOpen+" is editing this object";
								$("#errorOpen").css("visibility","visible");
								InitializeTimer();
								adiante=false;
							}
							else{
								adiante=true;			
							}
						}
	      			}, "json");
				  $.ajaxSetup({async:true});
				  if (adiante){
					$.post("openEditXML.php",{folderG:folderGroup,typeObj:"obj",numId:nId},function(data){},"json");	
					$(newDiv).draggable( "option", "disabled", false );
					valueZ=giveZindex()+1;
					var cssObj = {"z-index" : valueZ};
					$(this).css(cssObj);	
					hideButtons();
					showButtons(this);
					selected=this;
				  }
				  else{
					$(newDiv).draggable( "option", "disabled", true );
				  }
	  		}
	  		else{
				  if (selected==this){															   		   
					   hideButtons();				
					   valueZ=giveZindex()+1;
					   var cssObj = {"z-index" : valueZ};
					   $(this).css(cssObj);
					   showButtons(this);
				  }
			}
    });
    $("#cloneNewImage"+counter).draggable({
               cursor: "move",
               start: function() {
                  valueZ=giveZindex()+1;
                  var cssObj = {"z-index" : valueZ};
                  $(this).css(cssObj);
                  hideButtons();
               },
               drag: function() {},
               stop: function() {
			   		showButtons(this);
			   }
    });
	
	var pre=String(vecId);
	while (pre.length<3){pre="0"+pre;}
	$(newDiv).attr("id",pre+"_Image");
	$(newDiv).attr("title",vecLink);
	aplyStyle(pre+"_Image",vecCss);
	return $(newDiv); 
}

var newMedia = function(){
	var iFrame = document.getElementById("estadoUpLoadMedia").contentDocument.getElementsByTagName("body")[0];
	var loading = document.getElementById("loadingMedia");
	if(iFrame.innerHTML == ""){
		setTimeout ( newMedia, 2000 );
	}
	else{
		if(iFrame.innerHTML.substr(0,7) == "success"){	
			if ($("#isAudio").is(':checked')){
				var typeMedia="Audio";
			}
			else{
				var typeMedia="Video";
			}
			loading.style.display = "none";
			document.getElementById("estadoUpLoadMedia").style.display = "block";
			valueZ=giveZindex()+1;
			counter++;
 			father[counter]="addMediaNew";
   			var element=$("#addMediaNew").clone(); 
            element.addClass("tempclass");
   			$("#pizarra").append(element);
   			$(".tempclass").attr("id","cloneNewMedia"+counter);
   			$("#cloneNewMedia"+counter).removeClass("tempclass");
   			fatherDIV=document.getElementById(father[counter]);
   			newDiv=document.getElementById("cloneNewMedia"+counter);
   			var cssObj = {
               "position" : "absolute","transform" : "rotate(0deg)","-ms-transform" : "rotate(0deg)","-webkit-transform" : "rotate(0deg)","-moz-transform" : "rotate(0deg)","-o-transform" : "rotate(0deg)",
			   "border-style" : "dotted",
      		   "border-width" : "1px",
      		   "padding" : "2px",
      		   "width" : "18px","height" : "18px",
			   "top": "10px",
			   "left": "10px",
			   "z-index" : valueZ
            };
            $(newDiv).css(cssObj);
			loading.style.display = "none";
			newH6=document.createElement("h6");
            newH6.setAttribute("id", typeMedia+"_"+counter);
			cssObjH6 ={"width" : "0px", "height" : "0px" ,"visibility" : "hidden"}
			$(newH6).css(cssObjH6);
            newH6.innerHTML=iFrame.innerHTML.substring(7);
            newDiv.appendChild(newH6);
			newB=document.createElement("div");newB.setAttribute("id", "aButton_"+counter);newB.setAttribute("class", "buttonTop fg-button ui-state-default fg-button-icon-solo ui-corner-all");newDiv.appendChild(newB);$(newB).css("top","0");$(newB).css("position","absolute");
			newSPAN=document.createElement("span");
			if ($("#isAudio").is(':checked')){
				newSPAN.setAttribute("class","ui-icon ui-icon-volume-on");
			}
			else{
				newSPAN.setAttribute("class","ui-icon ui-icon-video");
			}
			newB.appendChild(newSPAN);
			$("#cloneNewMedia"+counter).mousedown(function(e){
				if (selected==null){ 
					nId=parseInt($(this).attr("id").substring(0,3),10);
		  			$.ajaxSetup({async:false});
		  			$.get("giveXMLBack.php",{folderG:folderGroup,typeObj:"isOpen",numId:nId},function(data){
						if (data.isOpen=="N"){	  	
							adiante=true;
						}
						else{
							editOnTime(data.dtOpen);
							if (seguir){
document.getElementById("errorOpen").innerHTML=" Transaction not allowed -> "+data.usrOpen+" is editing this object";
								$("#errorOpen").css("visibility","visible");
								InitializeTimer();
								adiante=false;
							}
							else{
								adiante=true;			
							}
						}
	      			}, "json");
				  $.ajaxSetup({async:true});
				  if (adiante){
					$.post("openEditXML.php",{folderG:folderGroup,typeObj:"obj",numId:nId},function(data){},"json");	
					$(newDiv).draggable( "option", "disabled", false );
					valueZ=giveZindex()+1;
					var cssObj = {"z-index" : valueZ};
					$(this).css(cssObj);	
					hideButtons();
					showButtonsMedia(this);;
					selected=this;
				  }
				  else{
					$(newDiv).draggable( "option", "disabled", true );
				  }
	  		}
	  		else{
				  if (selected==this){															   		   
					   hideButtons();				
					   valueZ=giveZindex()+1;
					   var cssObj = {"z-index" : valueZ};
					   $(this).css(cssObj);
					   showButtonsMedia(this);
				  }
			}										   
            });
            $("#cloneNewMedia"+counter).draggable({
               cursor: "move",
               start: function() {
                  valueZ=giveZindex()+1;
                  var cssObj = {"z-index" : valueZ};
                  $(this).css(cssObj);
                  hideButtons();
               },
               drag: function() {},
               stop: function() {
			   	showButtonsMedia(this);
			   }
            });
			var cssSend="";
			var num=1000;
			var nId=0;
			var nDate="";
			for (name in cssObj){
				cssSend=cssSend+name + ":" + cssObj[name]+"|";
			}
		    $.ajaxSetup({async:false});
			$.post("saveXMLBack.php",{folderG:folderGroup,typeSave:"saveNewMedia",iH:newH6.innerHTML,css:cssSend,typeM:typeMedia},function(data){
						var pre=String(data.id);
						while (pre.length<3){pre="0"+pre;}
						capa=document.getElementById("cloneNewMedia"+counter);
						$(capa).attr("id",pre+"_"+typeMedia);		
						nId=data.id;
						nDate=data.vDate;
			},"json");
			$.ajaxSetup({async:true});
			num=aObjects.length;
			aObjects[num]=nId;
			aDate[num]=nDate;
			aType[num]="Audio";
			
			$("#mediaNew").dialog( "close" );
		}
		else{
			loading.style.display = "none";
			if (iFrame.innerHTML.substr(0,4) == "tama"){
				
				document.getElementById("errorSizeFile").innerHTML = '<p><span class="ui-icon ui-icon-alert" style="float: left; margin-right: .3em;"></span>"'+iFrame.innerHTML.substr(4,100);
				
          		$("#errorSizeFile").css("visibility","visible");
          		InitializeTimer();
			}
			else{
				alert("Error: "+ iFrame.innerHTML);
			}
		}
	}
}
function createMedia(vecId,vecIH,vecCss,typeMedia){
			counter++;
 			father[counter]="addMediaNew";
   			var element=$("#addMediaNew").clone(); 
            element.addClass("tempclass");
   			$("#pizarra").append(element);
   			$(".tempclass").attr("id","cloneNewMedia"+counter);
   			$("#cloneNewMedia"+counter).removeClass("tempclass");
   			fatherDIV=document.getElementById(father[counter]);
   			newDiv=document.getElementById("cloneNewMedia"+counter);
   			var cssObj = {"position" : "absolute","transform" : "rotate(0deg)","-ms-transform" : "rotate(0deg)","-webkit-transform" : "rotate(0deg)","-moz-transform" : "rotate(0deg)","-o-transform" : "rotate(0deg)","border-style" : "dotted","border-width" : "1px","padding" : "2px","width" : "18px","height" : "18px","top": "10px","left": "10px","z-index" : valueZ
            };
            $(newDiv).css(cssObj);
			newH6=document.createElement("h6");
            newH6.setAttribute("id", typeMedia+"_"+counter);
			cssObjH6 ={"width" : "0px", "height" : "0px" ,"visibility" : "hidden"}
			$(newH6).css(cssObjH6);
            newH6.innerHTML=vecIH;
            newDiv.appendChild(newH6);
			newB=document.createElement("div");
			newB.setAttribute("id", "aButton_"+counter);newB.setAttribute("class", "buttonTop fg-button ui-state-default fg-button-icon-solo ui-corner-all");$(newB).css("top","0");$(newB).css("position","absolute");
			newDiv.appendChild(newB);
			newSPAN=document.createElement("span");
			if (typeMedia=="Audio"){newSPAN.setAttribute("class","ui-icon ui-icon-volume-on");}else{newSPAN.setAttribute("class","ui-icon ui-icon-video");}
			newB.appendChild(newSPAN);
			$("#cloneNewMedia"+counter).mousedown(function(e){
             	if (selected==null){
		  			nId=parseInt(vecId,10);
		  			$.ajaxSetup({async:false});
		  			$.get("giveXMLBack.php",{folderG:folderGroup,typeObj:"isOpen",numId:nId},function(data){
						if (data.isOpen=="N"){	  	
							adiante=true;
						}
						else{
							editOnTime(data.dtOpen);
							if (seguir){
document.getElementById("errorOpen").innerHTML=" Transaction not allowed -> "+data.usrOpen+" is editing this object";
								$("#errorOpen").css("visibility","visible");
								InitializeTimer();
								adiante=false;
							}
							else{
								adiante=true;			
							}
						}
	      			}, "json");
				  $.ajaxSetup({async:true});
				  if (adiante){
					$.post("openEditXML.php",{folderG:folderGroup,typeObj:"obj",numId:nId},function(data){},"json");	
					$(newDiv).draggable( "option", "disabled", false );
					valueZ=giveZindex()+1;
					var cssObj = {"z-index" : valueZ};
					$(this).css(cssObj);	
					hideButtons();
					showButtonsMedia(this);;
					selected=this;
				  }
				  else{
					$(newDiv).draggable( "option", "disabled", true );
				  }
	  		}
	  		else{
				  if (selected==this){															   		   
					   hideButtons();				
					   valueZ=giveZindex()+1;
					   var cssObj = {"z-index" : valueZ};
					   $(this).css(cssObj);
					   //selected=this;
					   showButtonsMedia(this);
				  }
			}
			});
            $("#cloneNewMedia"+counter).draggable({
               cursor: "move",
               start: function() {
                  valueZ=giveZindex()+1;
                  var cssObj = {"z-index" : valueZ};
                  $(this).css(cssObj);
                  hideButtons();
               },
               drag: function() {},
               stop: function() {
			   	showButtonsMedia(this);
			   }
            });
			var pre=String(vecId);
			while (pre.length<3){pre="0"+pre;}
			$(newDiv).attr("id",pre+"_"+typeMedia);
			aplyStyle(pre+"_"+typeMedia,vecCss);
			return $(newDiv); 
}
function closeToolBar(){	
			$( "#buttonTopBar" ).animate({
					height: "0px"
				  }, 500, function() {
						$("#bNewBackGround").css({"visibility" : "hidden"});
						$("#bNewText").css({"visibility" : "hidden"});
						$("#bNewImage").css({"visibility" : "hidden"});
						$("#bNewSound").css({"visibility" : "hidden"});
						$("#bNewMovie").css({"visibility" : "hidden"});
						$("#bNewEmbed").css({"visibility" : "hidden"});
						$("#buserDataText").css({"visibility" : "hidden"});
						$("#bCloseButtonTopBar").css({"visibility" : "hidden"});
						
			})
		   openButtonTopBar=false;
}

function showButtonsMedia(obj){
   var x = findPosX(obj);
   var y = findPosY(obj);
   var dW =$(obj).width();
   var dY =$(obj).height();
   valueZ=giveZindex()+1;
   var cssObj = {"z-index": valueZ, "left" : x+dW+32+"px", "top" : y-22+"px", "visibility" : "visible"};
      $("#cancela").css(cssObj);
	  var cssObj = {"z-index": valueZ, "left" : x+dW+32+"px", "top" : y+"px","visibility" : "visible"};
      $("#borrar").css(cssObj);
	  
	  if (x+32+22+dW+40>window.innerWidth){
	  	posXGrava=x-18-40;
	  }
	  else{
	  	posXGrava=x+32+22+dW;
	  }
	  
 	var cssObj = {"z-index": valueZ, "left" : posXGrava+"px","top" : y-22+"px", "visibility" : "visible", "width" : "30px"};
      $("#grava").css(cssObj);
};
function showButtons(obj){
   var x = findPosX(obj);
   var y = findPosY(obj);
   var dW =$(obj).width();
   var dY =$(obj).height();
   valueZ=giveZindex()+1;	 	
      var cssObj = {"z-index": valueZ, "left" : x+dW+32+"px", "top" : y-22+"px", "visibility" : "visible"};
      $("#cancela").css(cssObj);
	  var cssObj = {"z-index": valueZ, "left" : x+dW+32+"px", "top" : y+"px","visibility" : "visible"};
      $("#borrar").css(cssObj);
      var cssObj = {"z-index": valueZ, "left" : x+dW+32+"px", "top" : y+22+"px", "visibility" : "visible"};
      $("#edita").css(cssObj);
	  if (x+32+22+dW+40>window.innerWidth){ 
	  	posXGrava=x-18-40;
	  }
	  else{
	  	posXGrava=x+32+22+dW;
	  }
	  var cssObj = {"z-index": valueZ, "left" : posXGrava+"px","top" : y-22+"px", "visibility" : "visible", "width" : "30px"};
      $("#grava").css(cssObj);
   var cssObj = {"z-index": valueZ,"left" : x+dW/2-10+"px","top" : y-42+"px", "visibility" : "visible"};
   $("#xira").css(cssObj);
   var cssObj = {"z-index": valueZ,"left" : x-18,"top" : y-20+"px", "visibility" : "visible"};
   $("#lefttop").css(cssObj);
	var cssObj = {"z-index": valueZ,"left" : x-18+"px","top" : y+dY+12+"px","visibility" : "visible"};
    $("#leftbottom").css(cssObj);
	var cssObj = {"z-index": valueZ,"left" : x+dW+"px","top" : y-20+"px","visibility" : "visible"};
    $("#righttop").css(cssObj);
    var cssObj = {"z-index": valueZ,"left" : x+dW+"px","top" : y+dY+12+"px","visibility" : "visible"};
    $("#rightbottom").css(cssObj);
	var cssObj = {"z-index": valueZ, "left" : x-18+"px", "top" : y+dY+36+"px",	"visibility" : "visible"};
    $("#openTextTool").css(cssObj);
	var cssObj = {"z-index": valueZ, "left" : x-18+20+"px", "top" : y+dY+36+"px",	"visibility" : "visible"};
    $("#areaTextTool").css(cssObj);
};

function showButtonsEmbed(obj){
   var x = findPosX(obj);
   var y = findPosY(obj);
   var dW =$(obj).width();
   var dY =$(obj).height();
   valueZ=giveZindex()+1;	 	
   
      var cssObj = {"z-index": valueZ, "left" : x+dW+32+"px", "top" : y-22+"px", "visibility" : "visible"};
      $("#cancela").css(cssObj);
	  var cssObj = {"z-index": valueZ, "left" : x+dW+32+"px", "top" : y+"px","visibility" : "visible"};
      $("#borrar").css(cssObj);
	  
	  if (x+32+22+dW+40>window.innerWidth){
	  	posXGrava=x-18-40;
	  }
	  else{
	  	posXGrava=x+32+22+dW;
	  }
	  
	  var cssObj = {"z-index": valueZ, "left" : posXGrava+"px","top" : y-22+"px", "visibility" : "visible", "width" : "30px"};
      $("#grava").css(cssObj);
   
   var cssObj = {"z-index": valueZ,"left" : x+dW/2-10+"px","top" : y-42+"px", "visibility" : "visible"};
   $("#xira").css(cssObj);
};
function showButtonsText(obj){
      var x = findPosX(obj);
      var y = findPosY(obj);
      var dW =$(obj).width();
      var dY =$(obj).height();
      valueZ=giveZindex()+1;
      var cssObj = {"z-index": valueZ, "left" : x+dW/2-10+"px", "top" : y-42+"px", "visibility" : "visible"};
      $("#xira").css(cssObj);
      
	  var cssObj = {"z-index": valueZ, "left" : x-18+"px", "top" : y-20+"px","visibility" : "visible"};
      $("#lefttop").css(cssObj);
      var cssObj = {"z-index": valueZ, "left" : x-18+"px", "top" : y+dY+12+"px",	"visibility" : "visible"};
      $("#leftbottom").css(cssObj);
      
	  var cssObj = {"z-index": valueZ, "left" : x+12+dW+"px","top" : y-20+"px", "visibility" : "visible"};
      $("#righttop").css(cssObj);
      var cssObj = {"z-index": valueZ, "left" : x+12+dW+"px", "top" : y+dY+12+"px", "visibility" : "visible"};
      $("#rightbottom").css(cssObj);
	  
	  var cssObj = {"z-index": valueZ, "left" : x-18+"px", "top" : y+dY+36+"px",	"visibility" : "visible"};
      $("#openTextTool").css(cssObj);
	  
	  var cssObj = {"z-index": valueZ, "left" : x-18+20+"px", "top" : y+dY+36+"px",	"visibility" : "visible"};
      $("#areaTextTool").css(cssObj);
	  

      var cssObj = {"z-index": valueZ, "left" : x+dW+32+"px", "top" : y-22+"px", "visibility" : "visible"};
      $("#cancela").css(cssObj);
	  var cssObj = {"z-index": valueZ, "left" : x+dW+32+"px", "top" : y+"px","visibility" : "visible"};
      $("#borrar").css(cssObj);
      var cssObj = {"z-index": valueZ, "left" : x+dW+32+"px", "top" : y+22+"px", "visibility" : "visible"};
      $("#edita").css(cssObj);
	  
	  if (x+32+22+dW+40>window.innerWidth){
	  	posXGrava=x-18-40;
	  }
	  else{
	  	posXGrava=x+32+22+dW;
	  }
	  
	  var cssObj = {"z-index": valueZ, "left" : posXGrava+"px","top" : y-22+"px", "visibility" : "visible", "width" : "30px"};
      $("#grava").css(cssObj);
      
};
function findPosX(obj){
   var curleft = 0;
   if(obj.offsetParent)
      while(1){
         curleft += obj.offsetLeft;
         if(!obj.offsetParent)
            break;
         obj = obj.offsetParent;
      }
   else if(obj.x)
      curleft += obj.x;
   return curleft;
};
function findPosY(obj){
   var curtop = 0;
   if(obj.offsetParent)
      while(1){
         curtop += obj.offsetTop;
         if(!obj.offsetParent)
            break;
         obj = obj.offsetParent;
      }
   else if(obj.y)
      curtop += obj.y;
   return curtop;
};

function hideButtons(){
   var cssObj = {"visibility" : "hidden"};
   $("#lefttop").css(cssObj);
   $("#righttop").css(cssObj);
   $("#leftbottom").css(cssObj);
   $("#rightbottom").css(cssObj);
	$("#borrar").css(cssObj);
	$("#edita").css(cssObj);
	$("#grava").css(cssObj);
	$("#cancela").css(cssObj);
	$("#opaMenos").css(cssObj);
	$("#opaMais").css(cssObj);
	$("#xira").css(cssObj);
	$("#Agrande").css(cssObj);
	$("#Apeque").css(cssObj);
	$("#bold").css(cssObj);
	$("#italic").css(cssObj);
	$("#fontColor").css(cssObj);
	$("#border0").css(cssObj);
	$("#border1").css(cssObj);
	$("#backColor").css(cssObj);
	$("#backTrans").css(cssObj);
	$("#text_l").css(cssObj);
	$("#text_r").css(cssObj);
	$("#text_c").css(cssObj);
	$("#text_j").css(cssObj);
	$("#areaTextTool").css(cssObj);
	$("#openTextTool").css(cssObj);
	$("#areaTextTool").css({"width" : "0px", "height": "0px"});
	isOpenTextTool=false;
};

function sizeImages() {
   var scrollPane = $(".scroll-pane");
   var scrollContent = $(".scroll-content");
   var scrollbar = $(".scroll-bar").slider({
      slide:function(e, ui){
         if( scrollContent.width() > scrollPane.width() ){ scrollContent.css("margin-left", Math.round( ui.value / 100 * ( scrollPane.width() - scrollContent.width() )) + "px"); }
         else { scrollContent.css("margin-left", 0); }
      }
   });
   var handleHelper = scrollbar.find(".ui-slider-handle")
   .mousedown(function(){
      scrollbar.width( handleHelper.width() );
   })
   .mouseup(function(){
      scrollbar.width( "100%" );
   })
   .append('<span class="ui-icon ui-icon-grip-dotted-vertical"></span>')
   .wrap('<div class="ui-handle-helper-parent"></div>').parent();
   scrollPane.css("overflow","hidden");
   function sizeScrollbar(){
      var remainder = scrollContent.width() - scrollPane.width();
      var proportion = remainder / scrollContent.width();
      var handleSize = scrollPane.width() - (proportion * scrollPane.width());
      scrollbar.find(".ui-slider-handle").css({
         width: handleSize,
         "margin-left": -handleSize/2
      });
      handleHelper.width("").width( scrollbar.width() - handleSize);
   }

function resetValue(){
   var remainder = scrollPane.width() - scrollContent.width();
   var leftVal = scrollContent.css("margin-left") == "auto" ? 0 : parseInt(scrollContent.css("margin-left"),10);
   var percentage = Math.round(leftVal / remainder * 100);
   scrollbar.slider("value", percentage);
}
function reflowContent(){
   var showing = scrollContent.width() + parseInt( scrollContent.css("margin-left"),10 );
   var gap = scrollPane.width() - showing;
   if(gap > 0){ scrollContent.css("margin-left", parseInt( scrollContent.css("margin-left"),10 ) + gap);}
}
$(window)
.resize(function(){
   resetValue();
   sizeScrollbar();
   reflowContent();
});
setTimeout(sizeScrollbar,10);
};

function sizeText() {
   var scrollPane = $(".scroll-paneText");
   var scrollContent = $(".scroll-contentText");
   var scrollbar = $(".scroll-bar-text").slider({
      slide:function(e, ui){
        if( scrollContent.width() > scrollPane.width() ){ scrollContent.css("margin-left", Math.round( ui.value / 100 * ( scrollPane.width() - scrollContent.width() ))+"px");}
        else { scrollContent.css("margin-left", 0); }
      }
   });
   var handleHelper = scrollbar.find(".ui-slider-handle")
   .mousedown(function(){ scrollbar.width( handleHelper.width() );})
   .mouseup(function(){ scrollbar.width( "100%" );})
   .append('<span class="ui-icon ui-icon-grip-dotted-vertical"></span>')
   .wrap('<div class="ui-handle-helper-parent"></div>').parent();
   scrollPane.css("overflow","hidden");
   
   function sizeScrollbar(){
      var remainder = scrollContent.width() - scrollPane.width();
      var proportion = remainder / scrollContent.width();
      var handleSize = scrollPane.width() - (proportion * scrollPane.width());
      scrollbar.find(".ui-slider-handle").css({
         width: handleSize,
         "margin-left": -handleSize/2
      });
      handleHelper.width('').width( scrollbar.width() - handleSize);
   }
   
   function resetValue(){
      var remainder = scrollPane.width() - scrollContent.width();
      var leftVal = scrollContent.css("margin-left") == "auto" ? 0 : parseInt(scrollContent.css("margin-left"),10);
      var percentage = Math.round(leftVal / remainder * 100);
      scrollbar.slider("value", percentage);
   }
   function reflowContent(){
      var showing = scrollContent.width() + parseInt( scrollContent.css("margin-left"),10 );
      var gap = scrollPane.width() - showing;
      if(gap > 0){scrollContent.css("margin-left", parseInt( scrollContent.css("margin-left"),10 ) + gap);}
   }
   $(window)
   .resize(function(){
      resetValue();
      sizeScrollbar();
      reflowContent();
   });
   setTimeout(sizeScrollbar,10);
  };

