// 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("","","")


// Constantes del StaticPath

var STATIC = "STATIC";
var IMG = "IMG";



//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){
	var image = getRandomStaticPath('/images/load.gif', IMG);
	var html = "<div class=\"loadWrapper\" id=\"load\"><img src=\'" + image + "\'/></div>";
	
	if(imageLoading){
		$('#'+layer).html(html)
		$('.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();
		var image = getRandomStaticPath('/images/load.gif',IMG);
		var html = "<div class=\"loadWrapper\" id=\"load\"><img id=\"loadGif\" src=\'" + image + "\'/></div>";
		if(imageLoading){		
			$('#'+layer).html(html);
			$('.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() );
			 			$( data ).filter( 'script' ).each( function() {
			 				$.globalEval( this.text || this.textContent || this.innerHTML || '' );
			 			});
			 		} 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 makeEmbebCode(url, img, waterMark, w, h, divId, autoStart, controls, accountGA, accountGAEmbed) {
	
	controls = controls != undefined && controls != null ? controls : "bottom";
	var hrefText = 'Mecalux';
	if (document.documentElement.lang == 'en-US') {
		hrefText = 'Interlake Mecalux';
	}
		
	var embedCode = '<div id="MecaluxVideo"></div><script type="text/javascript" src="http://' + location.host + '/javascripts/embedCode.js"></script>'
		+ '<script type="text/javascript">document.getElementById("MecaluxVideo").innerHTML = dynamicEmbedCode("'
		+ url + '", "' + img + '", "' 
		+ location.protocol + '//' + location.host + waterMark + '", "' + w + '", "' + h + '", "' + divId + '", "' + autoStart + '", "' 
		+ controls + '", "uniform", "' + accountGAEmbed + '", "' + location.host +  '", "' + location.href + '", "' + hrefText + '");</script>';
	
	return embedCode;
	
}

function showVid(url, img, waterMark, w, h, divId, autoStart, controls, stretchingType, currentGA, currentGAE, home) {
	
	var embedCode = makeEmbebCode(url, img, '', w, h, divId, autoStart, controls, currentGA, currentGAE);
	stretchingType = stretchingType != null ? stretchingType : 'exactfit';
	var dockType = home === undefined || home != true ? true : false;
	controls = controls != null ? controls : 'bottom';
	
	_gaq.push(function() {
		jwplayer( divId  ).setup({ 
			'flashplayer' : '/mediaplayer/player.swf', 
			'file' : url, 
			'height' : h, 
			'width' : w, 
			'image' : img, 
		    'controlbar' : controls, 		
		    'autostart' : autoStart, 
		    'stretching' : stretchingType,
		    'dock' : dockType,
		    'plugins' : { 
		    	'sharing-3' : { 
		    		'code' : escape(embedCode) 
		    	}, 
		    	'gapro-2' : { 
		        	'trackingobject' : _gat._getTrackerByName('pageTracker'), 
		        	'trackpercentage' : true, 
		        	'tracktime' : true, 
		        	'trackstarts' : true 
		        }
		    }
		});
	}); 
}

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,
		success: function(data) {
			$(document).append(data);
		}
	});
}

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]  );
}


function callGA(type, event, text, code){
	
	try { 
			_gaq.push(['pageTracker._trackEvent', type , event, text]);
			_gaq.push(['globalTracker._trackEvent', type , event, text]);

		
	}catch(err) {}
	return true;
}

//Determina si el String 'value' está contenido en el array 'array'
function contains(array, value){
	if (array == null || array.length == 0) {
		return false;
	}
	for (var i = 0; i < array.length; i++) {
		var o = array[i];
		if ((o == null && value == null) || (o != null && (o.toLowerCase() == value.toLowerCase()))) {
			return true;
		}
	}
	return false;
	
}


function getRandomStaticPath(resource, dnsname){
	
	
	var APP = new Array();
	APP[0] = 'www.mecalux.com.ar';
	APP[1] = 'www.mecalux.de';
	APP[2] = 'www.mecalux.fr';
	APP[3] = 'www.mecalux.it';
	APP[4] = 'www.mecalux.co.nl';
	APP[5] = 'www.mecalux.sk';
	APP[6] = 'www.mecalux.cz';
	APP[7] = 'www.mecalux.com.mx';
	APP[8] = 'www.mecalux.co.uk';
	APP[9] = 'www.mecalux.cl';
	APP[10] = 'www.mecalux.be';
	APP[11] = 'www.interlakemecalux.com';
	APP[12] = 'www.mecalux.es';
	APP[13] = 'www.mecalux.pt';
	APP[14] = 'www.mecaluxbelgique.be';
	APP[15] = 'www.mecalux.com.tr';
	APP[16] = 'www.mecalux.com.br';
	APP[17] = 'www.mecalux.pl';
	APP[18] = 'www.mecalux.com';
	
	var PREWP = new Array();
	PREWP[0] = 'uk.test.mecalux.com';
	PREWP[1] = 'mx.test.mecalux.com';
	PREWP[2] = 'fr.test.mecalux.com';
	PREWP[3] = 'nl.test.mecalux.com';
	PREWP[4] = 'cz.test.mecalux.com';
	PREWP[5] = 'pl.test.mecalux.com';
	PREWP[6] = 'tr.test.mecalux.com';
	PREWP[7] = 'ar.test.mecalux.com';
	PREWP[8] = 'it.test.mecalux.com';
	PREWP[9] = 'cl.test.mecalux.com';
	PREWP[10] = 'br.test.mecalux.com';
	PREWP[11] = 'be.test.mecalux.com';
	PREWP[12] = 'xx.test.mecalux.com';
	PREWP[13] = 'pe.test.mecalux.com';
	PREWP[14] = 'uy.test.mecalux.com';
	PREWP[15] = 'es.test.mecalux.com';
	PREWP[16] = 'us.test.mecalux.com';
	PREWP[17] = 'pt.test.mecalux.com';
	PREWP[18] = 'de.test.mecalux.com';
	

	
	
	var STATIC_TEST_PATH = "http://static.test.mecalux.com";
	var IMG_TEST_PATH = "http://img.test.mecalux.com";
	var STATIC_URL = "http://static";
	var IMG_URL = "http://img";
	var DEFAULT_HOST = "mecalux.com";
	
	var hostname = window.location.hostname;
	var pathSrc = "";
	if (hostname !== null) {
		
		var urlAddress = document.location.href;
		
		
	
		try{
			
				if (contains(APP, hostname) && urlAddress !== null && urlAddress !== '' && urlAddress.indexOf("www.") != -1){
					
					pathSrc = STATIC_URL + getTLDDomain();
					
					if (dnsname != null && dnsname === STATIC) {
						pathSrc = STATIC_URL + getTLDDomain();
					}
					else{
						pathSrc = IMG_URL + getTLDDomain();
					}
				}else if(contains(PREWP, hostname)){
					
					pathSrc = STATIC_TEST_PATH;
					
					if (dnsname != null && dnsname === STATIC) { 
						pathSrc = STATIC_TEST_PATH;
					} else {
						pathSrc = IMG_TEST_PATH;
					}
				}
	
				
			
			
		}catch (e){
			
			alert('ERROR : ' + e);
			
		}
	
	}
	pathSrc = pathSrc + resource;
	return pathSrc;

}

function getRandomBoolean(){
	
	return Math.random() < 0.5 ? "true" : "false";
}

function getTLDDomain(){

	
	var hostWithWWW = document.location.host.toLowerCase();
	
	var hostWithOUTwww = '';
	var index = hostWithWWW.indexOf('www.');
	if(index != -1){
		hostWithOUTwww = hostWithWWW.substring(index + 3)
	}
	else{
		hostWithOUTwww = hostWithWWW;
	}
	
	return hostWithOUTwww;

}

function callbackLoadingAdwords( data, layer, findLayer ) {
	if ( $( data ).find( '#' + findLayer ).html() === null ) {
		$( '#' + layer ).html( data );
	} else {
		$( '#' + layer ).html( $( data ).find( '#' + findLayer ).html() );
		$( data ).filter( 'script' ).each( function() {
			$.globalEval( this.text || this.textContent || this.innerHTML || '' );
		});
	}
} 
