/*jslint browser: true, devel: true, evil: true, forin: true */

// de momento pongo aqui esto:
var texts = {};
texts['es'] = {
	abbrHoras            : 'h. ',
	abbrMinutos          : 'min. ',
	contactarPropietario : 'Contactar con el propietario de la ruta',
	coste                : 'Coste: ',
	direccio             : 'Direcci&oacute;n',
	distancia            : 'Distancia: ',
	duracionDelRecorrido : 'Duración del recorrido: ', 
	fecha                : 'Fecha: ',
	ferry                : 'Ferri',
	formError            : 'Se ha producido un error en el servidor: por favor, vuelva a enviar el formulario. Disculpe las molestias.',
	noHayResultados      : 'No se han encontrado resultados para su b&uacute;squeda de direcci&oacute;n.',
	periodicidad         : 'Periodicidad: ',
  rotonda              : 'Rotonda',
	salida               : 'Salida',
	seleccionar          : 'Seleccionar',
	talVezQuisoDecir     : 'Tal vez quiso decir'
}
texts['ca'] = {
  abbrHoras            : 'h. ',
  abbrMinutos          : 'min. ',
	contactarPropietario : 'Contactar con el propietario de la ruta',
	coste                : 'Coste: ',
  direccio             : 'Direcci&oacute;',
	distancia            : 'Distancia: ',
	duracionDelRecorrido : 'Duración del recorrido: ',
	fecha                : 'Fecha: ',
  ferry                : 'Ferri',
	formError            : 'Se ha producido un error en el servidor: por favor, vuelva a enviar el formulario. Disculpe las molestias.',
	noHayResultados      : 'No se han encontrado resultados para su b&uacute;squeda de direcci&oacute;n.',
	periodicidad         : 'Periodicidad: ',
  rotonda              : 'Rotonda',
  salida               : 'Sortida',
	seleccionar          : 'Seleccionar',
	talVezQuisoDecir     : 'Tal vez quiso decir'
}
texts['en'] = {
  abbrHoras            : 'h. ',
  abbrMinutos          : 'min. ',
	contactarPropietario : 'Contact route owner',
	coste                : 'Cost: ',
	distancia            : 'Distance: ',
  direccio             : 'Direction',
	duracionDelRecorrido : 'Ride time: ',
	fecha                : 'Date: ',
  ferry                : 'Ferry',
	formError            : 'There is a server error, please resend your form and sorry for the inconveniences.',
	noHayResultados      : 'No results have been found.',
	periodicidad         : 'Periodicity: ',
  rotonda              : 'Roundabout',
  salida               : 'Exit',
	seleccionar          : 'Select',
	talVezQuisoDecir     : 'Did you mean:'
}
texts['eu'] = {
  abbrHoras            : 'h. ',
  abbrMinutos          : 'min. ',
	contactarPropietario : 'Contactar con el propietario de la ruta',
	coste                : 'Coste: ',
  direccio             : 'Direcci&oacute;n: ',
	distancia            : 'Distancia: ',
	duracionDelRecorrido : 'Duración del recorrido: ',
	fecha                : 'Fecha: ',
  ferry                : 'Ferri',
	formError            : 'Se ha producido un error en el servidor: por favor, vuelva a enviar el formulario. Disculpe las molestias.',
	noHayResultados      : 'No se han encontrado resultados para su b&uacute;squeda de direcci&oacute;n.',
	periodicidad         : 'Periodicidad: ',
	rotonda              : 'Rotonda',
  salida               : 'Salida',
	seleccionar          : 'Seleccionar',
	talVezQuisoDecir     : 'Tal vez quiso decir'
}

/**
 * Valida que un String sea un email canonicamente correcto
 * @param {String} sTesteo
 * @return Boolean
 */
function validarEmail( sTesteo ) {
    var reEmail = /^(?:\w+\.?)*\w+@(?:\w+\.)+\w+$/;
    return reEmail.test(sTesteo);
}

/**
 * Valida que un String sea una fecha con formato dd/mm/aa
 * @param {String} sFecha
 * @return Boolean
 */
function validarFecha( sFecha ) {
    var reFecha = /^(?:0[1-9]|[12][0-9]|3[01])\/(?:0[1-9]|1[0-2])\/(?:\d{2})$/;
    return reFecha.test( sFecha );
}

/**
 * Devuelve la parte de un String a la izquierda de la primera almohadilla (incluida)
 * @return String
 */
String.prototype.getAnchor = function() {
	return this.indexOf('#') == -1 ? '' : this.substring(this.indexOf('#'));
};

Array.prototype.filter = function(fun /*, thisp*/){
    var len = this.length;
    if (typeof fun != "function") 
        throw new TypeError();
    
    var res = new Array();
    var thisp = arguments[1];
    for (var i = 0; i < len; i++) {
        if (i in this) {
            var val = this[i]; // in case fun mutates this
            if (fun.call(thisp, val, i, this)) 
                res.push(val);
        }
    }
    
    return res;
};


// utilizacion de cookies
function getCookie(a){var b=document.cookie.indexOf(a+"=");var c=b+a.length+1;if((!b)&&(a!=document.cookie.substring(0,a.length))){return null;}if(b==-1){return null;}var d=document.cookie.indexOf(';',c);if(d==-1){d=document.cookie.length;}return unescape(document.cookie.substring(c,d));}
function setCookie(a,b,c,d,e,f){var g=new Date();g.setTime(g.getTime());if(c){c=c*86400000;}var h=new Date(g.getTime()+(c));document.cookie=a+'='+escape(b)+((c)?';expires='+h.toGMTString():'')+((d)?';path='+d:'')+((e)?';domain='+e:'')+((f)?';secure':'')}
function deleteCookie(a,b,c){if(getCookie(a)){document.cookie=a+'='+((b)?';path='+b:'')+((c)?';domain='+c:'')+';expires=Thu, 01-Jan-1970 00:00:01 GMT'}}

(function($) {
	/**
	 * Menus desplegables de n-niveles, evento de inicializacion
	 */
    jQuery(document).ready(function(){ // Prepara eventos del menú
        var menus = jQuery("#menu li.desplegable").children('div, form, ul');
        menus.hide();
        menus.parent().mouseout(function(){
            pliega(this);
        }).mouseover(function(){
            rompePliega(this);
        });
        jQuery("#menu a").focus(function(){
            despliega(this);
        }).click(function(){
            despliega(this);
        });
    });
	function despliega(link) {
	    jQuery("#menu li").children('div, form, ul').parent().css({zIndex: 1});
		// ocultar los hermanos
		jQuery(link).parent("li")
		    .siblings()
			    .children("a").removeClass("active unfolded").siblings("ul, div, form").hide();
		//mostrar el que toca
	    jQuery(link).parent().css({
			zIndex: 500
	    }).children(":hidden").show(200).siblings("a").addClass("active unfolded");
		// en caso de que sea un form
		var $form = jQuery(link).siblings('form');
		if ($form.length) {
			jQuery('body').one('click', function closeThisForm(event) {
				if (jQuery(event.target).closest('#menu').length) {
					jQuery('body').one('click', closeThisForm);
				} else {
					$form.hide(200).siblings('a').removeClass("active unfolded");
				}
			});
		}
	}
	
	function pliega(padre) {
	    padre.temporizador = setTimeout(function() {
			jQuery(padre).children("div, ul").hide(200).siblings('a').removeClass("active unfolded");
	    }, 600);
	}

	function rompePliega(padre) {
		if (!padre.temporizador) {
			return false;
		}
	    clearTimeout(padre.temporizador);
	}

	/* Decoracion para menuDestacados */
	jQuery(document).ready(function() {
		jQuery('ul.menuDestacados li:has(img)').append('<div class="decoDestacados"></div>');
	});
})(jQuery);

/**
 * Modifica el documento para adaptar un listado y una serie de DIV's, dandole una 
 * estructura y funcionalidad de pestanyas desplegables
 * @param {Object} scope define el ambito del DOM en el que sera aplicada la funcion
 */
function createTabs(scope) {
	jQuery('div.contenedorPestanyas', scope || document).each( function() {
		var $c = jQuery(this),
			$li = $c.children('ul').find('li'),
			$div = $c.children('div'),
			$shown = $div.filter('.shown');
		// preparamos el contenido
		// si hay un numero de elementos visibles distinto a 1 (por algun error u omision)
		// los reseteamos y se lo ponemos solo al primero
		if (1 !== $shown.length) {
			$shown.removeClass('shown');
			$shown = $div.eq(0).addClass('shown');
		}
		// ocultamos todos excepto el que toca
		$div.each( function(index) {
			if ($shown.attr('id') == this.id) {
				$li.eq(index).addClass('active');
			} else {
				jQuery(this).hide();	
			}
		});
		
		// eventos para los li
		// estos deben tener el href que lleve al identificador de la pestanya que activan
		// para asegurarnos que la pagina es accesible sin javascript
		$li.click( function() {
			var $this = jQuery(this),
				identificador = $this.children().attr('href').getAnchor();
				
			if ($this.hasClass('active')) {
				return false;
			}
			// reasignamos clases
			$li.removeClass('active');
			$this.addClass('active');
			$div.filter(':visible').slideUp('slow');
			jQuery(identificador).slideDown('slow');
			return false;
		});
		// eventos de hover para los li
		$li.hover( function() {
			jQuery(this).addClass('hover');
		}, function() {
			jQuery(this).removeClass('hover');
		});
	});
}

/**
 * Inicializacion de varibles relacionadas con initPanels
*/

/**
 * Crea una serie de eventos para usar A.showPanel para controlar la visibilidad de
 * los DIV.panel de la pagina en orden correlativo.
 * Estilos asociados en css/tools.css
 * @param {Object} scope
 */
function initPanels(scope){
    var oScope = scope || document, $a = jQuery('a.showPanel', oScope), $p = jQuery('.panel', oScope);
    
    $p.each(function(index){
        var $thisA = $a.eq(index), $thisP = $p.eq(index), clasesOK = $thisA.filter('.active').length == $thisP.filter('.shown').length;
        
        // si tiene las clases desemparejadas las quitamos
        if (!clasesOK) {
            $thisA.removeClass('active');
            $thisP.removeClass('shown');
            // chivato para desarrollo en caso de error
            try {
                console.log('Error de emparejamiento de clases entre:');
                console.log($thisA.get(0));
                console.log($thisP.get(0));
            } 
            catch (e) {}
        }
    });
}
jQuery(function() {
	jQuery('a.showPanel').live('click', function() {
		var $a = jQuery('a.showPanel'),
			$p = jQuery('.panel'),
			index = $a.index(this),
			nThisShown = $p.eq(index).hasClass('shown') ? 0 : 1; // ojo que esta al reves porque AUN no se ha efectuado el cambio
		$a.eq(index).toggleClass('active');
		$p.eq(index).css('height','')[$p.eq(index).is('#caja-busca-ruta') ? 'toggle' : 'slideToggle'](400, function() {
			var $t = jQuery(this);
			// toggle class and height:1% to correct IE bug
			$t.toggleClass('shown').css({
				display: ''
			});
		})		
		// trigger custom events
		.trigger(nThisShown?'show':'hide');
		return false;
	});
	jQuery('.panel a.hide').live('click', function() {
		var index = jQuery('.panel').index(jQuery(this).closest('.panel'));
		jQuery('a.showPanel').eq(index).click();
	});
});


/**
 * extender diferentes elementos del DOM
 * @param {Object} scope Para todas las funciones: el ambito en el DOM en el cual que se aplicara la funcion
 */
function extendElements(scope) {
	var oScope = scope || document;
	
	// links
	var $a = jQuery('a', oScope);
	$a.filter('[href][rel*=external]').attr('target', '_blank');
	$a.filter('.btn-pestanya').wrapInner('<span></span>');
	
	// list-like elements
	var $el = jQuery('th, td, tr, li', oScope);
	$el.filter(':first-child').addClass('first');
	$el.filter(':last-child').addClass('last');
	$el.filter(':nth-child(2n+1)').addClass('odd').next().addClass('even');
	
	// forms
	jQuery('input.datepicker:not(.hasDatepicker)', oScope).each(function() {
		jQuery(this).datepicker();
	});

	// Para i_tarifas.php 
	// evento de cambio en la ciudad
	jQuery('#ciudades', oScope).change(function() {
		var $this = jQuery(this);
		var opt = '';
		jQuery('#resultadoTarifas').hide();
		jQuery('#origenes, #destinos').attr('disabled', 'disabled').after('<span class="inline-ajax-loader" />');
		jQuery.get('ajax/cargarEntradasSalidas.php', 'tipo=origen&ciudad=' + $this.val(), function(data) {
			jQuery('#origenes').attr('disabled', null).html(data).next('.inline-ajax-loader').remove();
		});
		jQuery.get('ajax/cargarEntradasSalidas.php', 'tipo=destino&ciudad=' + $this.val(), function(data) {
			jQuery('#destinos').attr('disabled', null).html(data).next('.inline-ajax-loader').remove();
		});
	
	});
	jQuery('#presentarTarifas').click(function() {
		clickTarifas(jQuery(this));
	});
	jQuery('#calcularDeEuros').click(function() {
		var $this = jQuery(this);
		var $a = jQuery('#lista_divisas').val();
		jQuery('#bodyTarifas').find('span.importe').each(function(index) {
			var $td = jQuery(this);
			var $euros = $td.closest('td').find('input').val();
			var importe = parseFloat($euros.replace(',', '.'));
			if (isNaN(importe)) {
				importe = 1;
			}
			var importeDestino = importe * parseFloat(tarifas[$a]);
			importeDestino = Math.round(importeDestino * 100.0) / 100.0;
			importeDestino = '' + importeDestino;
			var pos = importeDestino.indexOf('.');
			if (pos >= 0) {
				var dec = importeDestino.substring(pos + 1);
				if (dec.length == 1) {
					dec += '0';
				} else if (dec == '') {
					dec = '00';
				}
				var enteros = importeDestino.substring(0, pos);
				importeDestino = enteros + '.' + dec;
			} else {
				importeDestino += '.00';
			}
			$td.html(importeDestino.replace('.', ',') + ' ' + $a);
		});
	});
}


//////////////////////// Para i_tarifas.php ////////////////////////
function clickTarifas($this) {
	var ciudad = jQuery('#ciudades').val();
	var origen = jQuery('#origenes').val();
	var destino = jQuery('#destinos').val(); // Formato: autopista|destino
	if (ciudad == '') {
		alert('Debe seleccionar la ciudad');
		return;
	}
	if (origen == '') {
		alert('Debe seleccionar el origen');
		return;
	}
	if (destino == '') {
		alert('Debe seleccionar un destino');
		return;
	}
	var ad = destino.split('|');
	var autopistaDestino = destino;
	if (ad.length == 2) {
		autopistaDestino = ad[0];
		destino = ad[1];
	}
	jQuery.get('ajax/getTarifa.php',
		'autopistaOrigen=' + origen + '&autopistaDestino=' + autopistaDestino + '&origen=' + ciudad + '&destino=' + destino + '&lang=' + lang,
		function(data) {
			if (data != null) {
				pintarTarifas(data);
			}
			jQuery('#resultadoTarifas').show();
		}
		);
	jQuery('#nombreOrigen').html(origen);
	jQuery('#nombreDestino').html(destino);
}
function pintarTarifas(data) {
	var debugTarifas = true;
	jQuery('#bodyTarifas').html('');
	var h = '';
	var tarifasAcumuladas = jQuery.parseJSON(data);
	var tarifaSeleccionada = jQuery('#selectTarifas').val();
	for (var tarifa in tarifasAcumuladas) {
		if (tarifaSeleccionada == '' || tarifaSeleccionada == tarifa) {
			h = imprimirFilaTarifas(h, Math.round((tarifasAcumuladas[tarifa] * 100.0)) / 100.0, '18', 'Sentido?', tarifa);
		}
	}
	jQuery('#bodyTarifas').html(h);

}
function imprimirFilaTarifas(h, importeTarifa, iva, columna4, tarifa) {
	h += ('<tr>');
	h += ('<td>' + tarifa + '</td>');
	h += ('<td><span class="importe">' + importeTarifa + '</span><input type="hidden" value="' + importeTarifa + '" /></td>');
	h += ('<td>' + iva + '</td>');
	//h += ('<td>' + columna4 + '</td>');
	h += ('</tr>');
	return h;
}
//////////////////////// FINAL Para i_tarifas.php ////////////////////////

function customizeContent(scope) {
	var $cont = jQuery('.contenido', scope);
	$cont.find('h2').filter(function() {return jQuery(this).closest('ul').length === 0}).wrapInner('<span />');
}

/**
 * Agrupa las funciones que se tienen que inicializar al cargar la pagina o una parte de ella
 * de tal forma que cuando se cargue una parte de la pagina a traves de AJAX se le pueda aplicar 
 * facilmente.
 * @param {Object} scope ambito en el DOM en el cual que se aplicara la funcion
 */
function extendDOM(scope) {
	var oScope = scope || document;
	extendElements(oScope);
	initPanels(oScope);
	createTabs(oScope);
	customizeContent(oScope);
	Shadowbox.setup('a[rel*=shadowbox]', {
	    players: ['img', 'swf', 'iframe'],
	    language: lang,
	    autoplayMovies: false
	})
	return oScope;
}

jQuery(function() {
	jQuery.datepicker.setDefaults({
		buttonText: texts[lang].seleccionar,
		showOn: 'both',
		minDate: '+1'
	});
	extendDOM(document);

	jQuery('.autoFold a.showPanel:not(.active)').live(
	    'click',
	    function() {
	        jQuery(this).closest('li').siblings().find('a.showPanel.active').click()
	    }
	);

});

/*** slider home ***/
jQuery(function ($) {
	var $controls = $('#caja-texto-controls li'),
		$tabs = $('#caja-texto-home');
	$controls.click(function () {
		var $t = $(this);
		$controls.removeClass('active');
		$t.addClass('active');
		$tabs.animate({
			marginTop: - $t.index() * 280 + 'px'
		}, 1000);
	});
});
