//recoge el asunto para el envio de algunos correos
function setSubject(subject){
	document.getElementById('addSubject').value=subject;
}
//recoge el asunto para el envio de algunos correos
function setContent(newContent){
	document.getElementById('content').value=newContent;
}
//muestra el cursor de carga
function showLoadingPointer(){
	document.body.style.cursor = 'wait';
}
//recoloca una pagina al link de la addenda
function goToAddenda() {
	window.location.href="#addenda";
}
//muestra el cursor por defecto
function showDefaultPointer(){
		document.body.style.cursor = 'auto';	
}
//muestra el incono de 'trabajando'
function showLoadingGif(){
	if (document.getElementById("loadingGif").style.visibility == "visible")
		document.getElementById("loadingGif").style.visibility = "hidden";
	else
		document.getElementById("loadingGif").style.visibility = "visible";
}
//muestra-oculta un texto
function blinkText(layer) {
	if (document.getElementById(layer)){
		if (document.getElementById(layer).style.visibility == "hidden"){
			document.getElementById(layer).style.visibility = "visible";
		}
		else{
			document.getElementById(layer).style.visibility = "hidden";
		}
	}
}

var prjIDColor = null;
//asigna un color a un proyecto
function assignColor(prjID){
	prjIDColor = prjID;
	if (document.getElementById('colorTable')){
		showLayerOnMousePosition('colorTable');
	}
}
//cambia el color de un proyecto por otro.
function changeIndicativeColor(prjId){
	var color = document.getElementById('color_'+prjId).style.background;
	var imageList = document.getElementsByTagName('img');
	for (var i=0; i<imageList.length; i++){
		if (imageList[i].getAttribute('id') == '_color_'+prjId){
			imageList[i].style.background=color;
		}
	}
	//document.getElementById('prj_'+prjId).style.background=color;//esto es para cambiar el fondo de la capa
}
//asigna un color a un proyecto cambiandolo primero en la sesion y en la bbdd a traves de AJAX.
function setColor(color){

	if (document.getElementById('colorTable')){
		document.getElementById('colorTable').style.visibility="hidden";	
	}
	
	dojo.require("dojo.io.*");
	var bindArgs = {
	    url:       	ROOT_PATH + "/setColor.php",
	    method: 	"POST",
	    content:	{ prjIDColor: prjIDColor, newColor:color},
	    load:      	function(type, data, evt){	  
 	
	    				var temp=data.split("##");
	    				if(temp[0] == "error"){ 
							showErrorWindow(temp[1]);    				
							return;
						}			
						
						document.getElementById('color_'+prjIDColor).style.background=color;
	    				changeIndicativeColor(prjIDColor);
	    			},
	    error:		function(type, error) {
	    	alert(String(type) + ' -- ' + String(error));}	    
		};
	var requestObj = dojo.io.bind(bindArgs);
}
//oculta la capa de login.
function hideLogin(){
	if (!tryLogin)
		document.getElementById('LoginGlobalDiv').style.visibility="hidden";		
}

// Temporary variables to hold mouse x-y 
var coordinateX = 0
var coordinateY = 0

// Detect if the browser is Internet Explorer or not.
// If it is not Internet Explorer, we assume that the browser is NetScape.
var iExplorer = document.all?true:false

// If !Internet Explorer -- set up for mouse capture
if (!iExplorer){ 
	document.captureEvents(Event.MOUSEMOVE)
}

// Set-up to use getMouseCoordinates function onMouseMove
document.onmousemove = getMouseCoordinates;

// Main function to retrieve mouse x-y 
function getMouseCoordinates(e) {

  if (iExplorer) { // grab the x-y if browser is Internet Explorer
	  if (!document.documentElement.scrollLeft){	
	 	coordinateX = event.clientX;  
      }
      else{
	 	coordinateX = event.clientX + document.documentElement.scrollLeft;  
	  }   
	           
      if (!document.documentElement.scrollTop){
        coordinateY = event.clientY;
      }
      else{
        coordinateY = event.clientY + document.documentElement.scrollTop;
      }
  
  } 
  else {  // grab the x-y if browser is NetScape
    coordinateX = e.pageX;
    coordinateY = e.pageY;
  }  
  
  // catch possible negative values 
  if (coordinateX < 0){coordinateX = 0;}
  if (coordinateY < 0){coordinateY = 0;} 

}
/* funcion que muestra la capa de proyectos para addToMyMusic
*/
function showAddTrackLayer(layer,track){
	if (document.getElementById(layer)){
		document.getElementById(layer).style.visibility="visible";	
		document.getElementById(layer).style.position="absolute";
	
		document.getElementById(layer).style.left=coordinateX+"px";
		document.getElementById(layer).style.top=coordinateY+"px";
		document.getElementById('formAddTrack').track_id.value=track;
	}
}
//desoculta la capa con las opciones de para los proyectos.
function showProjectOptions(project_id){
	prjIDColor = project_id;
	document.getElementById("projectOptionsDiv").style.left=(coordinateX-160)+"px";
	document.getElementById("projectOptionsDiv").style.top=(coordinateY-155)+"px";
	document.getElementById('formProjectOptions').project_id.value=project_id;
}
//muestra la capa que tenga el identificador que se pasa por parametro en la posicion del puntero desplazandola hacia la izquierda despX pixeles
function showLayerOnMousePositionLeft(layer,despX){

	if (document.getElementById(layer)){
		document.getElementById(layer).style.visibility="visible";	
		document.getElementById(layer).style.position="absolute";
	
		document.getElementById(layer).style.left=(coordinateX-despX)+"px";
		document.getElementById(layer).style.top=(coordinateY+5)+"px";
	}
}
//muestra la capa que tenga el identificador que se pasa por parametro en la posicion del puntero
function showLayerOnMousePosition(layer){

	if (document.getElementById(layer)){
		document.getElementById(layer).style.visibility="visible";	
		document.getElementById(layer).style.position="absolute";
	
		document.getElementById(layer).style.left=coordinateX+"px";
		document.getElementById(layer).style.top=coordinateY+"px";
	}
}
//muestra una capa (en la posicion asiganda por defecto a esa capa ya sea en css o donde corresponda)
function showLayer(layer){
	document.getElementById(layer).style.visibility="visible";
}
//muestra la ventanita de error
function showErrorWindow(errorDescription){
	if (document.getElementById("miniError")){
		document.getElementById("miniError").style.visibility="visible";		
		document.getElementById("errorDescription").firstChild.nodeValue = errorDescription;
	}
}
//muestra/oculta las definicionas de versiones para una obra en la pantalla de licenciamiento.
function showVersion(project){
	if (document.getElementById(project)){
	    if(document.getElementById(project).style.display == "none" &&
	      document.getElementById(project).getElementsByTagName("TR").length > 1){
	      document.getElementById(project).style.display = "block";
	    }
	    else{
		  document.getElementById(project).style.display = "none";			 
		}
	}
	  
	// showLayerOnMousePosition('colorTable');	  	
}
//muestra el bloque que contiene las obras de un proyecto
function showProject(project,prj_id){
	dojo.require("dojo.io.*");
	var bindArgs = {
	    url:       	ROOT_PATH +"/changeIsOpen.php",
	    method: 	"POST",
	    content:	{ project_id: prj_id },
	    load:      	function(type, data, evt){
	    	    		var temp=data.split("##");	    	    		
	    				if(temp[0] == "error"){ 
    						showErrorWindow(temp[1]);
    						return;
    					}
	    			},
	    error:		function(type, error) {
	    	alert(String(type) + ' -- ' + String(error));}	    
		};
		
	var requestObj = dojo.io.bind(bindArgs);
	
	if (document.getElementById(project)){
	    if(document.getElementById(project).style.display == "none"){
	      document.getElementById(project).style.display = "block";
	    }
	    else{
		  document.getElementById(project).style.display = "none";			 
		}
	}
	  
	// showLayerOnMousePosition('colorTable');	  	
}
//oculta una capa
function hideLayer(layer,value){
	
	if (!layer){
		//if (!tryLogin)			
		//	document.getElementById("LoginGlobalDiv").style.visibility="hidden";						
		if (document.getElementById("projectPopUpDiv")){		
			document.getElementById("projectPopUpDiv").style.visibility = "hidden";
		}
		if (document.getElementById("projectOptionsDiv")){
			document.getElementById("projectOptionsDiv").style.visibility = "hidden";
		}
		
		return;
	}
	
	if (value){
	// Llamar a la funci?n para procesar el "id" del proyecto
	}
	
	if (document.getElementById(layer)){
		document.getElementById(layer).style.visibility="hidden";
	}
}
//"DEPRECATED" valida el formulario de añadir proyecto
function validateAddProjectForm(text,form){	

	if (document.getElementById(text).value.length > 0){
		document.getElementById(form).submit();
	}
	else{
		alert("Project Name empty");
	}
}
//muestra una capa y oculta otra(s)hasta 3.
function ShowAndHideLayer(id2Show,id2Hide1,id2Hide2,id2Hide3){
	if (document.getElementById(id2Show)){
		document.getElementById(id2Show).style.display = "block";			 
	}
	if (document.getElementById(id2Hide1)){
		document.getElementById(id2Hide1).style.display = "none";
	}
	if (document.getElementById(id2Hide2)){
		document.getElementById(id2Hide2).style.display = "none";		
	}
	if (document.getElementById(id2Hide3)){
		document.getElementById(id2Hide3).style.display = "none";				
	}
	//setNewSearch();
}
//muestra la capa de busquedas y gestiona la existencia de parametros previos etc.
function showActiveLayer(typeSearch){
	//Distinguimos que tipo de busqueda hemos hecho en la pantalla previa
	if (typeSearch=='Normal') {
	/**
		if (document.getElementById('SearchLitleLayer'))	
			document.getElementById('SearchLitleLayer').style.display = "block";	
			**/
		if (document.getElementById('SearchMusicLitle'))	
			document.getElementById('SearchMusicLitle').style.display = "block";	
			
	}
	if (typeSearch=='Style') {
		if (document.getElementById('SearchLitleLayerStyle'))	
			document.getElementById('SearchLitleLayerStyle').style.display = "block";		
	}	
}
//añade un nuevo input a la ventanita de busquedas por estilos
function addNewSearchStyle(newStyle){
	ShowAndHideLayer('SearchStyle','SearchLitleLayer','SearchLitleLayerStyle','SearchMusicLitle');
    if (iExplorer) addInputStyle(newStyle+", ");
    else addInputStyle(newStyle);
	
	if (document.getElementById('style').value != "")
		document.getElementById('style').value += ', ' + newStyle;
	else
		document.getElementById('style').value = newStyle;
}
//añade un nuevo estilo para la busqueda por estilos e inicia la busqueda
function addAndSearchStyle(newStyle){
	addInputStyle(newStyle+", ");
	
	if (document.getElementById('estilos').value != "")
		document.getElementById('estilos').value += ', ' + newStyle;
	else
		document.getElementById('estilos').value = newStyle;

	setNewSearch();
	document.getElementById('STstyle').submit();
}
//forma parte de las funciones que añaden el input a la busqueda de estilos
function addInputStyle(values){
	var arrayCad = null;
	var i=0;	
	var NumStyles =0;	
	//nodo padre de la estructura	
	var padre 	= document.getElementById("InputStyles");	

	if (values) {//Estamos en modo "Editar B?squeda", con lo cual el primer elemento que sera el
				//que clonemos ya le ponemos el valor del estilo1
		arrayCad = values.split(', ');
		NumStyles = arrayCad.length;		
		
		var myDIV	= dojo.dom.getLastChildElement(padre,'DIV');
		var myINPUT	= dojo.dom.getLastChildElement(myDIV,'input');			
				
		if (document.getElementById(myINPUT.getAttribute("id")).value == ''){			
			document.getElementById(myINPUT.getAttribute("id")).value=arrayCad[i];
			i++;
			if (NumStyles == 1) NumStyles--;	
		}
		
	}
	//Ejecutamos el bucle do-while en dos casos diferenciados:
	/**
	1: Caso Editar B?squeda y viene mas de un estilo
	2: Estamos en Nueva busqueda a?adiendo mas nodos al padre y no tenemos en cuenta el parametro de entrada
	**/
	if ((NumStyles>0) || (!values)) {
		do{
			//nodo que clonaremos, para ello recojemos mismamente el ultimo que se creo
			var toClone	= dojo.dom.getLastChildElement(padre,'DIV');
			//cogemos los elementos html del DIV, del INPUT y del HREF, ya que tendremos que tunearlos
			var lastDIV	= toClone.cloneNode("true");	
			var lastINPUT	= dojo.dom.getLastChildElement(lastDIV,'input');
			var collectionLastHREF		= lastDIV.getElementsByTagName("a");
			var lastHREF = collectionLastHREF[0];
			
			//proceso de tunning de attributos id,name y href de los elementos que intervienen en la clonacion
			var id 	= lastDIV.getAttribute("id");
			var aux = parseInt(id.substring(5,id.length))+1;
			aux = aux.toString();
		
			id 	= "style"+aux;
			lastDIV.setAttribute("id",id);	
			
			id	= "style["+aux+"]";
			lastINPUT.setAttribute("id",id);
			lastINPUT.setAttribute("name",id);			
			
			id	= "javascript:deleteInputStyle('style"+aux+"')";
			lastHREF.setAttribute("href",id);	
		
			//aniadimos finalmente el elemento al final del padre
			padre.appendChild(lastDIV);
			//Borramos el campo de texto del nuevo estilo del form
			document.getElementById("style["+aux+"]").value='';			
			if (arrayCad) 
				document.getElementById("style["+aux+"]").value=arrayCad[i];	
		} while (++i<NumStyles);
	}
}
//añade los valores de los estilos cuando se 'edita' una búsqueda anterior por estilos.
function addInputValues(StyleSearched,TitleSearched,ReferenceSearched,TrackSearched,ComposerSearched){
	if (StyleSearched){
		NodeList = document.getElementsByName("style");	
		for (i=0;i<NodeList.length;i++){
			NodeList[i].value=StyleSearched;
		}
	}

	NodeList = document.getElementsByName("title");
	for (i=0;i<NodeList.length;i++){
		NodeList[i].value=TitleSearched;
	}
	
	NodeList = document.getElementsByName("reference");
	for (i=0;i<NodeList.length;i++){
		NodeList[i].value=ReferenceSearched;
	}
	
	NodeList = document.getElementsByName("track");
	for (i=0;i<NodeList.length;i++){
		NodeList[i].value=TrackSearched;
	}	
	
	NodeList = document.getElementsByName("compositor");
	for (i=0;i<NodeList.length;i++){
		NodeList[i].value=ComposerSearched;
	}	
}
//borra un input de la lista de input's de los estilos
function deleteInputStyle(idStyle){
	var padre 	= document.getElementById("InputStyles");	
	if (dojo.dom.getFirstChildElement(padre,'DIV')!=dojo.dom.getLastChildElement(padre,'DIV'))
		padre.removeChild(document.getElementById(idStyle));
}
/*"DEPRECATED"
function completeStyles(values){
	if (document.getElementById('style'))
		document.getElementById('style').value = values;
}
*/
//elimina los espacios que haya a la izquierda(inicio) de una cadena
function leftTrim(sString)
{
	while (sString.substring(0,1) == ' ')
	{
		sString = sString.substring(1, sString.length);
	}
	return sString;
}
//completa la lista de estilos
function completeStyles(){
	var padre 		= document.getElementById("InputStyles");
	var fields		= padre.getElementsByTagName("input");
	var estilos = "";
	var hasStyle = false;

	for( var i = 0; i < fields.length; i++) {
		var styleValue = leftTrim(fields[i].value);
		if (styleValue != '') {
			if (hasStyle) {
				estilos+= ", "+fields[i].value;				
			}
			else {
				estilos+=fields[i].value;
				hasStyle = true;
			}
		}
	}
	document.getElementById("estilos").value=estilos;
}
/* functions done for checkall and uncheckall pruposes
	activan o descativan todos los checkbox que haya en el document
*/
function checkAll(){
	inputs = document.getElementsByTagName("INPUT");
	for (i=0;i<inputs.length;i++){
		if(inputs[i].type=="checkbox")			
			inputs[i].checked=true;
	}
}
function uncheckAll(){
	inputs = document.getElementsByTagName("INPUT");
	for (i=0;i<inputs.length;i++){
		if(inputs[i].type=="checkbox")
			inputs[i].checked=false;
	}
}
//resetea los valores para una nueva busqueda.
function setNewSearch(){
	NodeList = document.getElementsByName("isNewSearch");
	i=0;
	
	for (i=0;i<NodeList.length;i++){
		NodeList[i].value=true;
	}
}
