/**
	Biblioteca basica de desarrollo en js para el grupo piñero.
	
	Complemento a jquery para utilizar cuando no se requiere toda su potencia y funciones comunes.
	
	A imagen y semejanza de jQuery, utilizaremos $gp como prefijo.
*/

if (typeof window.$gp == 'undefined') 
{
	/* -------------------------- */
	/* 	Funcionalidad por defecto.

		$gp( xxxx ) retorna el elemento xxx.
		Equivale a $gp.dom( "xxx" ).
	*/
	window.$gp = $gp = {};

	/* --------------------- */
	/* Funciones auxiliares. */
	$gp.toString = function( cadena ){
		if (cadena == null) {
			return "";
		}
		return '' + cadena;
	};

	/**
		Convierte un string en un int. Si el string es vacio o null, devuelve null.
	 */
	$gp.stringToInt = function( str )
	{
		if( str == null || str == "" )
		{
			return null;
		}
		else
		{
			return parseInt( str );
		}
	};
	
	/**
		Convierte un string en un valor float. Si l'string es null o vacio, retorna null.
	 */
	$gp.stringToFloat = function( str )
	{
		if( str == null || str == "" )
		{
			return null;
		}
		else
		{
			return parseFloat( str );
		}
	};

	/** Elimina los espacios de c.
	*/
	$gp.trim = function( c ) {
		if( !$gp.isDef( c ) )
		{
			return "";
		}
		return ( '' + c ).replace(/^\s+|\s+$/g,"");
	};

	/**
		Function: isDef
		
		Comrpueba si el elemento que se le pasa está definido.
		
		Se considera que esta definido cuando es undefined, null o bien false o una cadena vacia.
	*/
	$gp.isDef = function( a )
	{
		if ( "number" == (typeof a) ){
			return true;
		}
		if( "undefined" == (typeof a) || ( a == null ) || !a || a == "" )
		{
			return false;
		}
		return true;
	};
	
	$gp.isDefined = function( nombreVariable )
	{
		return !(typeof(window[nombreVariable]) == "undefined");
	};

	/**
		Devuelve la versión de Internet Explorer del usuario. Devuelve -1 en caso de que no se utilice IE.
	*/
	$gp.ieVersion = function()
	{
		return (navigator.appName=='Microsoft Internet Explorer')?parseFloat((new RegExp("MSIE ([0-9]{1,}[.0-9]{0,})")).exec(navigator.userAgent)[1]):-1;
	};

	/**
		Funcion para llamar a la funcion f sin importar el resultado.
	*/
	$gp.perform = function( f ) { return false; };

	/* Evita que el control actual ejecute la acción derivada del evento.
	*/
	$gp.stopEvent = function(e) {
	    if (!e) e = window.event;
	    if (e.stopPropagation) 
	    {
	        e.stopPropagation();
	    } 
	    else 
	    {
	        e.cancelBubble = true;
	    }
	};

	/* Evita que el evento se propague.		
	*/
	$gp.cancelEvent = function(e) {
	    if (!e) e = window.event;
	    if (e.preventDefault) {
	        e.preventDefault();
	    } else {
	        e.returnValue = false;
	    }
	};

	/* Formato de numeros. */
	
	/* Formatea un numero dado dando un separador de miles, de decimales y el numero de decimales solicitados. */
	$gp.formateaNumeroGenerico = function( numero, separadorMiles, separadorDecimales, numDecimales )
	{
		var negativo = "";
		numero = 0 + parseFloat( numero );
		if( numero < 0 )
		{
			numero = -numero;
			negativo = "-";
		}
		
		var numParteEntera = Math.floor( numero );
		var parteEntera = '' + numParteEntera;
	

		if( $gp.isDef( separadorMiles ) )
		{
			var parteEnteraGrouping = '';
			while( parteEntera.length > 3 )
			{
				parteEnteraGrouping += separadorMiles + parteEntera.substring( parteEntera.length - 3 );
				parteEntera = parteEntera.substring( 0, parteEntera.length - 3 );
			}
			parteEntera = parteEntera + parteEnteraGrouping;
		}
		
		if( numDecimales == 0 )
		{
			return negativo + parteEntera;
		}
		
		var parteDecimal = '' + Math.round( ( numero - numParteEntera ) * Math.pow( 10, numDecimales ) );
		while( parteDecimal.length < numDecimales )
		{
			parteDecimal = '0' + parteDecimal;
		}

		return negativo + parteEntera + separadorDecimales + parteDecimal;
	};

	$gp.formateaNumeroExt = function( precio, decimales, divisa, divisaLarga, html )
	{
		precio = 0 + precio;
		var formato = formatoPrecioExt.formato;
		var numero = $gp.formateaNumeroGenerico( precio, 
				formato.separadorGrupos, formato.separadorDecimales,
				( decimales ? formato.decimalesPorDefecto : 0 ) );
    	if( html ) {
    		if( decimales )
    		{
    			var i = numero.indexOf( formato.separadorDecimales );
    			if( i > 0 )
    			{
    				numero = numero.substring( 0, i ) + "<span class='fmtDecimales'>" + numero.substring( i ) + "</span>";
    			}
    		}
    		numero = "<span class='fmtNumero'>" + numero + "</span>";
    	}

    	if( divisa )
    	{
    		var sufijo = formato.sufijoDivisaCorta;
    		var prefijo = formato.prefijoDivisaCorta;
    		if( divisaLarga )
    		{
        		sufijo = formato.sufijoDivisaLarga;
        		prefijo = formato.prefijoDivisaLarga;
    		}
			if( $gp.isDef( prefijo ) )
			{
				if( html )
				{
					numero = "<span class='fmtMoneda'>" + prefijo + "</span>" + numero;
				}
				else
				{
					numero = prefijo + numero;
				}
			}
	
			if( $gp.isDef( sufijo ) )
			{
				if( html )
				{
					numero = numero + "<span class='fmtMoneda'>" + sufijo + "</span>";
				}
				else
				{
					numero = numero + sufijo;
				}
			}
    	}
    	
    	return numero;
	};

	/*
		Converteix un string a una data, donat el format.
		
		El format inclou un separador (primer caracter diferent de lletra) y els camps
		dd, mm y yyyy.
	*/
	$gp.stringToDate = function( strFecha, formatoFecha ){
		if( !strFecha )
		{
			return null;
		}
		var anyo = "";
		var mes = "";
		var dia = "";
		
		if( !formatoFecha ) { formatoFecha = BP_Mercado.formatoFecha; }
		
		var separadorFormatoUsado = "";
		for (var i = 0; i < formatoFecha.length; i++) {
			var cod = formatoFecha.charCodeAt(i);
			if ( (cod < 65 || cod > 90) && (cod < 97 || cod > 122)) {
				separadorFormatoUsado = formatoFecha.toLowerCase().charAt(i);
				break;
			}
		}
		
		var vFecha = strFecha.split(separadorFormatoUsado);
		var vFormato = formatoFecha.toLowerCase().split(separadorFormatoUsado);
		
		for ( var i = 0; i < vFormato.length; i++ ) {
			if ( vFormato[i] == "yyyy" || vFormato[i] == "yy" ) {
				anyo = vFecha[i];
				if (anyo.length == 2) {
					anyo = "20" + anyo;
				}
			} else if ( vFormato[i] == "MM" || vFormato[i] == "mm" ) {
				mes = vFecha[i];
			} else if ( vFormato[i] == "dd" ) {
				dia = vFecha[i];
			}
		}
		
		var myDate=new Date();
		myDate.setFullYear( Number(anyo), (Number(mes) - 1), Number(dia) );
		return myDate;
	};
	
	/*
		Converteix una data en un string, donat el format.
	*/
	$gp.dateToString = function( datFecha, formatoFecha ){
		if( datFecha == null )
		{
			return null;
		}

		var fechaRetornada = "";
	
		if( !formatoFecha ) { formatoFecha = BP_Mercado.formatoFecha; }

		var anyo = datFecha.getFullYear();
		var mes = (datFecha.getMonth() + 1) + "";
		if (mes.length == 1) {
			mes = "0" + mes;
		}
		var dia = datFecha.getDate() + "";
		if (dia.length == 1) {
			dia = "0" + dia;
		}

		var separadorFormatoUsado = "";
		for (var i = 0; i < formatoFecha.length; i++) {
			var cod = formatoFecha.charCodeAt(i);
			if ( (cod < 65 || cod > 90) && (cod < 97 || cod > 122)) {
				separadorFormatoUsado = formatoFecha.charAt(i);
				break;
			}
		}
	
		var vFormato = formatoFecha.toLowerCase().split(separadorFormatoUsado);
		
		for ( var i = 0; i < vFormato.length; i++ ) {
			if ( i != 0 ) {
				fechaRetornada += separadorFormatoUsado;
			}
			if ( vFormato[i] == "yyyy" ) {
				fechaRetornada += anyo;
			} else if ( vFormato[i] == "yy" ) {
				fechaRetornada += (anyo + "").substring(2);
			} else if ( vFormato[i] == "MM" || vFormato[i] == "mm" ) {
				fechaRetornada += mes;
			} else if ( vFormato[i] == "dd" ) {
				fechaRetornada += dia;
			}
		}
		
		return fechaRetornada;
	};

	/*
		Transforma una fecha de un formato a otro.
	*/
	$gp.dateTransformer = function(fecha, formatoActual, formatoDeseado) {
		return $gp.dateToString( $gp.stringToDate( fecha, formatoActual ), formatoDeseado );
	};

	/*
		Obtiene la hora formateada segun BP_Mercado.formatoHora.
	*/
	$gp.getHoraFormateada = function( hora )
	{
		var horaFinal = hora;
		if ( BP_Mercado.formatoHora == "12H"){
			var horas = horaFinal.substring(0,2);
			if (Number(horas) > 12){
				horaFinal = (Number(horas) - 12) + ":" + horaFinal.substring(3) + "pm";			
			} else if (horas == "00") {
				horaFinal = "12:" + horaFinal.substring(3) + "am";
			} else if (horas == "12") {
				horaFinal = "12:" + horaFinal.substring(3) + "pm";
			}else {
				horaFinal += "am";
			}
		}
		return horaFinal;
	};
	
	/*
	 Obtiene el dia de una fecha en formato yyyy-mm-dd
	 */
	$gp.getDay = function(fecha){
		var temp = fecha.split("-");
		var dia = temp[2];
		if(dia.substr(0,1)=="0")
			dia = dia.substr(1,1);
		dia = $gp.stringToInt(dia);
		return dia;
	};
		
	/*
	 Obtiene el mes de una fecha en formato yyyy-mm-dd
	 */
	$gp.getMonth = function(fecha){
		var temp = fecha.split("-");
		var mes = temp[1];
		if(mes.substr(0,1)=="0")
			mes = mes.substr(1,1);
		mes = $gp.stringToInt(mes);
		return mes;
	};
	
	/*
	 Obtiene el año de una fecha en formato yyyy-mm-dd
	 */
	 $gp.getYear = function(fecha){
		var temp = fecha.split("-");
		var year = null;
		year = temp[0];
		year = $gp.stringToInt(year);
		return year;
	};
		
	/*
	 *  Añade tantos meses como indica el parámetro 'num' a la fecha en formato yyyy-mm-dd. 
	 *  Admite números negativos.
	 */
	$gp.addMonth = function(fecha,num){
	    var aux = fecha.split( '-' );
	    var year = parseInt( aux[0],10 );
	    var mes = parseInt( aux[1],10 );
	    var dia = aux[2];
	    var signe = ( num < 0 ) ? -1 : 1;
	    num = Math.abs(num);
	    var numYears = parseInt( num / 12 );
	    var numMeses = num - ( numYears * 12 );
	    //alert( 'numeroAños = ' + numYears + ', numeroMeses = ' + numMeses );
	    year += signe * numYears;
	    mes += signe * numMeses;
	    if( mes <= 0 )
	    {
	        -- year;
	        mes += 12;
	    }
	    else if( mes > 12 )
	    {
	        ++year;
	        mes -= 12;
	    }
	    if(mes<10){
	    	mes = "0" + mes;
	    }
	    return '' + year + '-' + mes + '-' + dia;
	};

	/* 
		Converteix una data en un string en format yyyy-mm-dd (per exemple 2009-10-02).
	*/
	$gp.dateToAaaammdd = function(fecha) 
	{
		return $gp.dateToString( fecha, "yyyy-MM-dd" );
	};

	/* 
		Converteix una string en format yyyy-mm-dd en un objecte date.
	*/
	$gp.aaaammddToDate = function( fecha ) 
	{
		return $gp.stringToDate( fecha, "yyyy-MM-dd" );
	};

	/*
		Retorna una fecha amb x dies posteriors.
	*/
	$gp.addDaysToDate = function( datFecha, numDays )
	{
		var fecha = new Date(datFecha);
		fecha.setDate( fecha.getDate() + numDays );
		return fecha;
	};

	/**
		Construye una cadena introduciendo los parametros pasados en el interior de la cadena principal
		
		@param cadena Es la cadena principal que presenta fragmentos del tipo "{x}" que son luego 
		   sustituidos en el orden indicado por parámetros
		@param parametros Es un array de cadenas que sustituyen por orden los fragmentos 
		   del tipo "{x}" en la cadena principal
		
		Ejemplo de uso:
	
			var params = new Array();
			params.push("Manuel");
			params.push("Verde");
			params.push("Ford");
			alert( $gp.construyeCadenaConParametros("Hola, {0}. Este coche es {1} y su marca es {2}.", params) );
		
			Resultado: Hola, Manuel. Este coche es Verde y su marca es Ford. 
	 */
	$gp.construyeCadenaConParametros = function(cadena, parametros)
	{
		var str = cadena;
		if ( str != null && cadena != "" && parametros != null && parametros.length != 0 ) {
			for ( var i = 0; i < parametros.length; i++ ) {
				var cadenaABuscar = "{" + i + "}";
				var cadenaAIntroducir = parametros[i];
				while ( str.indexOf(cadenaABuscar) != -1 ) {
					str = str.replace( cadenaABuscar, cadenaAIntroducir );
				}
			}
		}
		return str;
	};
	
	/**
		Obtiene una representación en formato de texto de un parametro, utilizando comillas
		para indicar una cadena.
		
		Ver getStringParametros. 
	*/
	$gp.getStringParametro = function( comillas, p )
	{
		if( (p == null) || ( (typeof p) == "undefined" ) )
		{
			return "null";
		}
		else if( (typeof p) == "string" )
		{
			return comillas + p + comillas;
		}
		else if( (typeof p) == "number" )
		{
			return p;
		}
		else if( (typeof p) == "boolean" )
		{
			return p ? "true" : "false";
		}
		else if( (typeof p.getDate) == "function" )
		{
			return "aaaammddToDate( " + comillas + dateToAaaammdd( p ) + comillas + " )";
		}
		else
		{
			throw "[" + p + "] Tipo de parametro no soportado " + (typeof p) + " = " + JSON.stringify(p);
		}
	};

	/**
		Construye una lista de parametros para pasar una función.
		
		Se utiliza para generar una representación de parametros para generar
		un texto de una llamada a una función a javascript en un gestor de
		eventos.
		
		Por ejemplo:
		
			onclickCelda = " onclick=\'javascript: SELECCION_OFERTAS.seleccionaOferta( " +
						$gp.getStringParametros( "\"", numOferta, celda.fecsal, 'N', celda.numnoc, 
						origen, destino, hotel, null, familiaProducto, codigoProducto, ofecod, 
						sprind, 'N', 'S' ) + " )\'";
	*/
	$gp.getStringParametros = function( comillas )
	{
		var resultado = "";
		var separador = "";
		for( var i = 1; i < arguments.length; ++i )
		{
			resultado += separador + getStringParametro( comillas, arguments[i] );
			separador = ", ";
		}
		return resultado;
	};

	/* ----------------------- */
	/* Tratamiento de cookies. */
	
	/**
	 * Obtiene el valor de una cookie.
	 */
	$gp.getCookie = function( c_name )
	{
		if ( document.cookie.length > 0 )
		{
			var c_start = document.cookie.indexOf( c_name + "=" );
			if ( c_start != -1 )
			{
				c_start = c_start + c_name.length + 1;
				var c_end = document.cookie.indexOf( ";", c_start );
				if ( c_end == -1 ) 
				{
					c_end = document.cookie.length;
				}
				return unescape( document.cookie.substring( c_start, c_end ) );
			}
		}
		return "";
	};

	/**
	 * Establece el valor de una cookie y los dias de expiración.
	 */
	$gp.setCookie = function( name, value, expires, path, domain, secure )
	{
		// set time, it's in milliseconds
		var today = new Date();
		today.setTime( today.getTime() );
		
		/*
		if the expires variable is set, make the correct
		expires time, the current script below will set
		it for x number of days, to make it for hours,
		delete * 24, for minutes, delete * 60 * 24
		*/
		if ( expires )
		{
			expires = expires * 1000 * 60 * 60 * 24;
		}
		var expires_date = new Date( today.getTime() + (expires) );
		
		document.cookie = name + "=" +escape( value ) +
			( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
			( ( path ) ? ";path=" + path : "" ) +
			( ( domain ) ? ";domain=" + domain : "" ) +
			( ( secure ) ? ";secure" : "" );
	};

	/**
	* Borra la cookie indicada.
	*/
	$gp.deleteCookie = function( name, path, domain ) {
		if ( $gp.getCookie( name ) ) document.cookie = name + '=' +
				( ( path ) ? ';path=' + path : '') +
				( ( domain ) ? ';domain=' + domain : '' ) +
				';expires=Thu, 01-Jan-1970 00:00:01 GMT';
	};
	
	/*
		Parsea un valor json.
	*/
	$gp.fromJson = function( json )
	{
		var resultado = null;
		
		try
		{
			eval( "resultado = " + json + ";" );
		}
		catch( e )
		{
			throw "Error interno (Error en el formato de la respuesta del servidor)";
		}
		
		return resultado;
	}
	
	/*
		Convierte el objeto pasado en su representación json.
	*/
	$gp.toJson = function (obj) 
	{
		var t = typeof (obj);
		if (t != "object" || obj === null) {
	
			// simple data type
			if (t == "string") obj = '"'+obj+'"';
			return String(obj);
		}
		else {
			// recurse array or object
			var n, v, json = [], arr = (obj && obj.constructor == Array);
			for (n in obj) {
				v = obj[n]; t = typeof(v);
				if (t == "string") v = '"'+v+'"';
				else if (t == "object" && v !== null) v = $gp.toJson(v);
				json.push((arr ? "" : '"' + n + '":') + String(v));
			}
			return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
		}
	};

	/*
	 * Preloading de imatges.
	 * 
	 * Parametres:
	 * 	urlImg: Url de la imatge.
	 *  domOpc: Domini opcional, si no, la de la imatge actual.
	 */
	var cacheImatges = [];
	$gp.preloadImg = function()
	{
	    var args_len = arguments.length;
	    for (var i = args_len; i--;) {
	      var cacheImage = document.createElement('img');
	      cacheImage.src = arguments[i];
	      cacheImatges.push(cacheImage);
	    }	
	}
	
	/*
		Debug de javascript.
	*/
	$gp.canLog = false;
	/*
		Per defecte, el log no fa res.
	*/
	$gp.log = function() {}
	
	
	$gp.enterOnInput = function(e, obj){
		if( e.keyCode == 13 || e.keyCode == 32){
			$(obj).click();
		}
		
	}
	
	/*
		Si tenim activada la consola (firebug) escriu al log.
	*/
	if( window.console )
	{
		$gp.canLog = true;
		$gp.log = function()
		{
			var resultado = "";
			for( var i = 0; i < arguments.length; ++i )
			{
				resultado += arguments[i];
			}
			console.log( resultado );
		}
	}

}

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}

var odd_reA = new RegExp( "\u00C0|\u00C1|\u00C2|\u00C3|\u00C4|\u00C5|\u00E0|\u00E1|\u00E2|\u00E3|\u00E4|\u00E5", "g" );
var odd_reE = new RegExp( "\u00C8|\u00C9|\u00CA|\u00CB|\u00E8|\u00E9|\u00EA|\u00EB", "g" );
var odd_reI = new RegExp( "\u00CC|\u00CD|\u00CE|\u00CF|\u00EC|\u00ED|\u00EE|\u00EF", "g" );
var odd_reO = new RegExp( "\u00D2|\u00D3|\u00D4|\u00D5|\u00D6|\u00F2|\u00F3|\u00F4|\u00F5|\u00F6", "g" );
var odd_reU = new RegExp( "\u00D9|\u00DA|\u00DB|\u00DC|\u00F9|\u00FA|\u00FB|\u00FC", "g" );
var odd_reN = new RegExp( "\u00D1|\u00F1", "g" );
var odd_reC = new RegExp( "\u00C7|\u00E7", "g" );
var odd_reOthers = new RegExp( "[^a-zA-Z0-9]", "g" );

String.prototype.normaliza = function()
{
    return this.replace( odd_reA, "a" ).replace( odd_reE, "e" ).replace( odd_reI, "i" ).replace( odd_reO, "o" ).replace( odd_reU, "u" ).replace( odd_reN, "n" ).replace( odd_reC, "c" ).replace( odd_reOthers, "" );
}


