/*
 * -------------------------------------------------------------- utilizacion de cookies
*/
function getCookie( name ) {
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
		return null;
	}
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ';', len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
} // function

function setCookie( name, value, expires, path, domain, secure ) {
	var today = new Date();
	today.setTime( today.getTime() );
	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() : '' ) + //expires.toGMTString()
		( ( path ) ? ';path=' + path : '' ) +
		( ( domain ) ? ';domain=' + domain : '' ) +
		( ( secure ) ? ';secure' : '' );
} // function

function deleteCookie( name, path, domain ) {
	if ( getCookie( name ) ) document.cookie = name + '=' +
			( ( path ) ? ';path=' + path : '') +
			( ( domain ) ? ';domain=' + domain : '' ) +
			';expires=Thu, 01-Jan-1970 00:00:01 GMT';
} // function

/*
..........................................................................
:: Menus desplegables de n-niveles                                      ::
..........................................................................
*/
$(document).ready(function() { // Prepara eventos del menu
    $('#nav li > ul').hide().parent()
        .bind('mouseenter', function() { despliega(this) })
        .bind('mouseleave', function() { pliega(this) });
});

function despliega(padre) {
    clearTimeout(padre.temporizador);
    $('#nav ul').parent('li').css({zIndex: 1});
    $(padre).css({zIndex: 1000})
	    .children('ul').fadeIn(300);
}

function pliega(padre) {
    padre.temporizador = setTimeout(function() {
		$(padre).children('ul').fadeOut(300);
    }, 300)
}

/*
..........................................................................
:: Clases para los elementos ultimo y primero de los listado            ::
..........................................................................
*/
$(document).ready(function(){
	$('li:first-child').addClass('first');
	$('li:last-child').addClass('last');
});

/*
..........................................................................
:: Links en ventana nueva                                               ::
..........................................................................
*/
$(document).ready(function() {
	$('a[rel=external]').attr({target: '_blank'})
});

/*
..........................................................................
:: Comprobar email valido                                               ::
..........................................................................
*/
String.prototype.testEmail = function() {
	var reEmail = /^(?:\w+(-\w+)*\.?)*\w+@(?:\w+(-\w+)*\.)+\w+$/;
	return reEmail.test(this);
}

/*
..........................................................................
:: Validar fecha                                                        ::
:: Requiere el uso del archivo correspondiente de lang/.../texts.js     ::
..........................................................................
*/
String.prototype.testDate = function() {
    return lang.reFecha.test(this);
}

/*
..........................................................................
:: Plugin de jQuery para cambiar PNG's para IE6 dentro de un elemento   ::
:: Ej. uso: $('div.fulanito img').pngIE6()                              ::
:: El parametro 'blank' debe ser la ruta de un GIF transparente de 1x1  ::
..........................................................................
*/
jQuery.fn.extend({
    pngIE6: function(blank) {
        if ($.support.opacity) return this;
        if (!blank) blank = 'img/blank.gif';
        return this.each( function() {
            this.style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src='+ this.src +',sizingMethod=image)';
            this.src = blank;
        });
    }
});

// DESPLEGABLES MULTIFUNCION
function asignPanelEvents(container) {
	// Si se pasa un parametro, la funciona solo asignara
	// eventos dependiendo de lo que se pase:
	// si es un elemento del DOM, dentro del mismo
	// si es una cadena de texto, en el interior de los
	// elementos que concuerden con el selector jQuery
	var $c = container ? $(container) : $('html');
	var $show = $c.find('.showPanel');
	var $panel = $c.find('.panel');
	// para cada .showPanel buscamos el panel que toca y los botones para ocultarlo, de haberlos
	$show.each( function(index) {
		var $this = $(this);
		var $thisPanel = $panel.eq(index);
		var $hide = $this.siblings('.hidePanel').add( $thisPanel.find('a,button').filter('.hidePanel') );
		// comprobamos si el panel tiene clase "activo" para mostrarlo o no y actuar en consecuencia
		if ($thisPanel.hasClass('activo')) {			
			if ($hide.length) {
				$this.hide();
			} else {
				$this.addClass('activo');
			}
			$thisPanel.show();
			$hide.show();
		} else {
			$this.show();
			$thisPanel.hide();
			$hide.hide();
		}
		$this.css('cursor','pointer');
		// asignamos el evento al .showPanel, tanto para mostrar como para ocultar
		$this.click( function() {
			if ('div' == $panel.get(index).tagName.toLowerCase()) {
				$thisPanel.slideToggle('fast');
			} else if ($thisPanel.is(':visible')) {
				$thisPanel.fadeOut('fast');
			} else {
				$thisPanel.fadeIn('fast');
			}
			if ($hide.length) {
				$this.toggle();
				$hide.toggle();
			} else {
				$this.toggleClass('activo');
			}
			return false;
		});
		// el evento del .hidePanel, de haberlo, simplemente invoca la funcion del .showPanel
		$hide.click( function() {
			$this.click();
			return false;
		});
	});
}
$( function() {
	asignPanelEvents()
});




function crearError(textoError, contenedor) {
	// contenedor debe ser el elemento del DOM donde mostrar el error
	// o un String para llegar al elemento via jQuery
	var $c = $(contenedor);
	if (!$c.find('div.ko').length) {
		$('<div class="ko" style="display:none">'+textoError+'</div>').prependTo($c).slideDown('fast');
	}
}

