// Bloqueo de submit y llamada genérica al submit
// Se utiliza en la funcion doSubmit

var  blockSubmit = true; //indica si es posible realizar el submit

// searchInProgress
// false, indica que no se ha clickado la opcion de busqueda
// true, indica que se esta realizando la búsqueda

var  searchInProgress = false;

// Variables usadas para el menu lateral
var ns6=document.getElementById&&!document.all
var ie4=document.all&&navigator.userAgent.indexOf("Opera")==-1
var arrayDesplegadas = new Array("","","")

//Menu Lateral: resaltado de una celda
function lightCell(obj, pviiColor) {
	obj.style.backgroundColor=pviiColor
}


//Metodo para la Combo de la Site Universal.
var idTimeOut;
function selectSite(cbSites) {
	target_url = cbSites.options[cbSites.selectedIndex].value;
	clearTimeout(idTimeOut);
	if (target_url!='-1')
		idTimeOut = window.setTimeout("document.location.href=target_url",1000);
}

function doThisSubmit(formName,actionValue,callFuction)
{
	if (blockSubmit) 
	{
		var i = arguments.length;
		if (i==2)
		{
   	   		blockSubmit = false;
   	   		formName.action = actionValue;
   	   		formName.submit();
	    }
	    else if (eval(callFuction))
	    {
	    	blockSubmit = false;
      	    formName.action = actionValue;
	        formName.submit();
	    }
	} 
}

// function Connect
// Comprueba que el user y el pwd est?n informados antes de realizar login
function Connect(formLogin,userOblig,pswOblig,action) {
	if ((!isWhitespace(formLogin.j_username.value))&&(!isWhitespace(formLogin.j_password.value))){
		return true;
	}
	else{
		if (isWhitespace(formLogin.j_username.value))
			alert (userOblig)
		else
			alert(pswOblig)
		return false;
	}
}

// function DisConnect
// Prepara JSP para LogOut
function  DisConnect(formLogin,action){
	formLogin._actionLog.value = action;
	formLogin.action='/home.jsp'
	formLogin.submit();
}
	
//Function for the layers the phone and the fax of
//Display of Company. Modificate 06/11/02


//Check of navigator and her edition.
function CheckNav(){
	// 0 Navegador indeterminado/no reconocido
	// 1 Netscape 4 o inferior
	// 2 Microsoft Explorer 4 o inferior
	// 3 Microsoft Explorer 5
	// 4 Netscape 5 (Mozilla)
	var navegador = 0
	if (document.layers) {navegador=1}
	if ((document.all) && !(document.getElementById)) {navegador=2}
	if (document.getElementById) {
	if (document.all) {navegador=3}
	else {navegador=4}
	}
	return navegador;
}

//Carga contenido en capa
//
// id: capa contenido
// nestref: capa madre si existe.
// url: origen
function loadSource(id,nestref,url,nameBuffer) {

	var navegador=CheckNav();
	switch (navegador){
		case 1: //Netscape 4
				var lyr = (nestref)? eval("document.layers['"+nestref+"'].document.layers['"+id+"']") : document.layers[id]
	            lyr.load(url,lyr.clip.width)
				break;
		case 2:
		case 3:	//Explorer 4+
				//self.bufferFrame.document.location = url
				//alert("Entra en el loadSource explorer 4");
                var obj;
                obj = eval("self." + nameBuffer + ".document");
                obj.location = url;
				//alert("La url es: "+url);
                break;
	
		case 4: //Netscape 6
				document.getElementById(nameBuffer).src = url;
				break;
				
		}

}

//Finaliza carga de contenido
//id: capa contenido
function loadSFinish(id,nameBuffer) {
	
    var obj=eval("self."+nameBuffer);
	if (document.all){
		 document.all[id].innerHTML = obj.document.body.innerHTML
	}
	if (!(document.all) && (document.getElementById)){
		 document.getElementById(id).innerHTML = window.frames[nameBuffer].document.getElementById('bdy').innerHTML;
	}
}

//borra espacios en blanco por la derecha y por la izquierda
function trim(s)
{
  // Remove leading spaces and carriage returns
  
  while ((s.substring(0,1) == ' ') || (s.substring(0,1) == '\n') || (s.substring(0,1) == '\r'))
  {
    s = s.substring(1,s.length);
  }

  // Remove trailing spaces and carriage returns

  while ((s.substring(s.length-1,s.length) == ' ') || (s.substring(s.length-1,s.length) == '\n') || (s.substring(s.length-1,s.length) == '\r'))
  {
    s = s.substring(0,s.length-1);
  }
  return s;
}

function doSearch(submForm)
{
	if (searchInProgress) return false;// si ya se esta buscando, aborta la accion
	searchInProgress = true; // activa el flag. A partir de ahora ya no se puede volve a buscar hasta que no se cargue la otra página.
	//borramos espacios
	document.SearchTextualForm.searchParam.value = trim(document.SearchTextualForm.searchParam.value);
	//document.SearchTextualForm.searchSection.value = getSearchSection();
	document.SearchTextualForm.searchSection.value = document.SearchTextualForm.searchSection.value;

   	document.SearchTextualForm.action=submForm;
	return true;
}
function doSearchPublication (submForm){
	if(searchInProgress) return false;
	searchInProgress = true;
	//borramos espacios
	document.SearchTextualForm.searchParam.value = trim (document.SearchTextualForm.value);
	
	if (!checkSearchField(document.SearchTextualForm.searchParam.value)){
			return false;
   	} else {
	   	document.SearchTextualForm.action=submForm;
		return true;
	}
}

function comboKeyPressed(submForm) {
   if (window.event.keyCode == 13) {clickSearch(submForm);}
}
function comboKeyPressedPublication(submForm) {
   if (window.event.keyCode == 13) {clickSearchPublication(submForm);}
}
function clickSearch(submForm)
{
	if (searchInProgress) return;// si ya se esta buscando, aborta la accion
	searchInProgress = true; // activa el flag. A partir de ahora ya no se puede volve a buscar hasta que no se cargue la otra página.
	
	//borramos espacios
	document.SearchTextualForm.searchSection.value = document.SearchTextualForm.searchSection.value;
	document.SearchTextualForm.searchParam.value = trim(document.SearchTextualForm.searchParam.value);
    
	document.SearchTextualForm.action=submForm;
	document.SearchTextualForm.submit();
}
function clickSearchPublication(submForm){
	if (searchInProgress) return;// si ya se esta buscando, aborta la accion
	searchInProgress = true; // activa el flag. A partir de ahora ya no se puede volve a buscar hasta que no se cargue la otra página.
	
	//borramos espacios
	document.SearchTextualForm.searchParam.value = trim(document.SearchTextualForm.searchParam.value);
    
    if (!checkSearchField(document.SearchTextualForm.searchParam.value)){
			return false;
   	} else {
	   	document.SearchTextualForm.action=submForm;
	   	document.SearchTextualForm.submit();
	}
}

function checkSearchField(field){
	if (field== null || field=='' ||field.length<2){
			searchFormatError();
			searchInProgress = false;// permite realizar más busquedas
			return false;
	}else return true;
}

function clickLeftMenuCtg(txtCompany,txtProduct,endURL) {
	if (!ns6) {
		var product = document.getElementById("product");
		endURL = (product.checked) ? "/"+txtProduct+endURL : "/"+txtCompany+endURL;
	} else {
		var form = document.forms["formLeftMenu"];
		endURL = (form.product.checked) ? "/"+txtProduct+endURL : "/"+txtCompany+endURL;
	}
	window.location.href=endURL;
}

function clickLeftMenu(endURL) {
	if (!ns6) {
		var product = document.getElementById("product");
		endURL = (product.checked) ? "/navigation/product"+endURL : "/navigation/company"+endURL;
	} else {
		var form = document.forms["formLeftMenu"];
		endURL = (form.product.checked) ? "/navigation/product"+endURL : "/navigation/company"+endURL;
	}
	window.location.href=endURL;
}

function check(param) {
	if (!ns6) {
		var opt = document.getElementsByName('selsearch')
		for(var i=0; i < opt.length; i++)
			if (opt[i].id==param)
				opt[i].checked=true
	} else {
		var form = document.forms["formLeftMenu"];
		if (param=="product")
			form.product.checked = true
		else
			form.company.checked = true
	}
}

function checkSearch(param) {

	if (!ns6) {
		var opt = document.getElementsByName('searchSection')
		for(var i=0; i < opt.length; i++)
			if (opt[i].id==param) {
				opt[i].checked=true
			}
	} else {
		var form = document.forms["SearchTextualForm"];
		if (param=="DIRECTORY")
			form.DIRECTORY.checked = true
		else
			form.CATALOGUE.checked = true
	}
	
	document.SearchTextualForm.searchSection.value =param;

}

function getSearchSection() {
	if (!ns6) {
		var opt = document.getElementsByName('rbSearch')
		for(var i=0; i < opt.length; i++)
			if (opt[i].checked) return opt[i].id
	} else {
		var form = document.forms["SearchTextualForm"];
		var ret = (form.DIRECTORY.checked) ? 'DIRECTORY' : 'CATALOGUE';
		return ret;
	}
	return 'DIRECTORY'
}

function VerPhoto(param) {
		var w
		w = open(param, "winLov", "Scrollbars=1,width=500,height=135,resizable=1");
		if (w.opener == null)
			w.opener = self;
			
		w.focus();
}
		

function loadAjaxContent(layer, action, imageLoading, callback, errorCallback){
	if(imageLoading){
		$('#'+layer).html("<div class=\"loadWrapper\" id=\"load\"><img src=\"/images/load.gif\"/></div>")
		$('.loadWrapper').css("width",$('#'+layer).css("width"));
		$('.loadWrapper').css("height",$('#'+layer).css("height"));				
	}
	$.ajax({
		  url: action,
		  cache:false,
		  success: function(data){
			if(typeof(callback)!="undefined" && callback!=null){
		 		callback(data);				 		
		 	}else{
		 		$('#'+layer).html(data);		 		
		 	}
		  },
		  error: function(data){
			if(typeof(errorCallback)!="undefined" && errorCallback!=null){
				errorCallback(data);		 		
		 	}else{
		 		$('#'+layer).html("<p>Error in request:"+action+"</p>");		
		 	}			 		  
		  }
		});	
	
}

function ajaxSubmit(formId, layer, action, imageLoading, findData, callback, errorCallback) {	
	if (blockSubmit) {
		var form = $('#' + formId + '');
		var serializedForm = form.serialize();
		if(imageLoading){		
			$('#'+layer).html("<div class=\"loadWrapper\" id=\"load\"><img id=\"loadGif\" src=\"/images/load.gif\"/></div>")
			$('.loadWrapper').css("width",$('#'+layer).css("width"));
			$('.loadWrapper').css("height",$('#'+layer).css("height"));				
			blockSubmit = false;
			
		}
		$.ajax({
			type :"POST",
			url :action,
			data :serializedForm,
			cache:false,
			dataType :"text",
			success : function(data) {	
				blockSubmit = true;
				if(typeof(callback)!="undefined" && callback!=null){
			 		callback(data);		 		
			 	}else{			 	
			 		if(typeof(findData)!="undefined" && findData!=null){	
			 			$('#'+layer).html($(data).find('#'+findData).html());
			 		}else{			 			
			 			$('#'+layer).html(data);
			 		}
			 	}
			},
			error: function(data){		
				blockSubmit = true;
				if(typeof(errorCallback)!="undefined" && errorCallback!=null){
					errorCallback(data);		 		
			 	}else{
			 		 $('#'+layer).html("<p>Error in request:"+action+"</p>");	
			 	}	
			}
		});
	}return false;		
}

function showVid(url, img, waterMark, w, h, divId, autoStart, controls) {
	if (controls == null)
		controls = 'bottom';

	var attributes = {
		id :divId,
		name :divId
	}
	var params = {
		allowfullscreen :"true",
		allowscriptaccess :"always",
		wmode :'opaque'		
	}

	var flashvars = {
		file :url,
		image :img,
		//logo :waterMark,
		height :h,
		width :w,
		autostart :autoStart,
		id : divId,
		menu: false,
		controlbar :controls
	};

	flashvars.rotatetime = '2';
	flashvars.transition = 'random'; // fade |
	flashvars.bufferlength = '1';
	flashvars.volume = '20';
	flashvars.stretching = 'uniform'; // (none|uniform|exactfit|fill)
	//flashvars.backcolor = 'ADE1FF'; // Background de la barra de controles
	//flashvars.frontcolor = '000'; // Foreground de los elementos de la barra
	// de controles
	// flashvars.screencolor = 'd6e8ff'; // Background del video (márgenes
	// superiores en WS, etc...)
	
	// swfobject.js 2.1
	
	swfobject.embedSWF("/mediaplayer/player.swf", divId, w, h, "9.0.0", false, flashvars, params, attributes);

}	


function colorBoxVideos(jQuerySelector,layer){
	$(jQuerySelector).colorbox({transition:'elastic',width:'500px',height:'400px',inline:true,opacity:'0.5',overlayClose:false,href:"#"+layer});
	return false;
}

function colorBoxVideosTutorial(jQuerySelector,layer){
	$(jQuerySelector).colorbox({transition:'elastic',width:'700px',height:'600px',inline:true,opacity:'0.5',overlayClose:false,href:"#"+layer});
	return false;
}

function colorBoxImages(jQuerySelector){
	$(jQuerySelector).colorbox({transition:"elastic",opacity:'0.5',overlayClose:false});
	return false;
}

function doMultimediaTracking(action){
	$.ajax({
		  url: action,
		  cache:false
	});
}

function colorBoxIframe(jQuerySelector){
	$(jQuerySelector).colorbox({width:"90%", height:"90%", iframe:true});
	return false;
}

/**colorbox SWF (menuproduct)**/

//Inserta la url del SWF informado en el div informado
function showSwf(url, divId, w, h) {
	
	var attributes = {
		id: divId,
		name: divId
	}
	var params = {
		allowfullscreen :'false',
		wmode :'transparent', 	
		base: '.',
		menu: 'false',
		allowscriptaccess: 'always',
		quality: 'high'
	}
	
	// swfobject.js 2.1
	swfobject.embedSWF(url, divId, w, h, "9.0.0", false, null, params, attributes);
	
}

function colorBoxSwf(jQuerySelector, layer, w, h) {
	$(jQuerySelector).colorbox({transition:'elastic',inline:true, width:w, height:h, opacity:'0.5',overlayClose:false,href:"#"+layer});
}

//Obtiene la ruta real para un formato "javascript: colorbox('rutaReal',width,height);" 
function getRealHrefColorbox(href){
	var realhref = href;
	realhref = realhref.replace("javascript:", "");
	realhref = realhref.replace("colorbox", "");
	realhref = realhref.replace("('", "");
	realhref = realhref.substring(0, realhref.indexOf("'"));
	return realhref.replace("%20", "");
}

//Obtiene valores de parámetros en url
function getURLParameter(name) {
	  		  return unescape(
	        		(RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]  );
}
