/* extensiones del objeto String: */
String.prototype.getAnchor = function() {
       var subS = this.substring(this.indexOf('#'));
       if (subS == this) subS = '';
       return subS;
}

/*
 * -------------------------------------------------------------- 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 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 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';
}

/*
 * -------------------------------------------------------------- funciones auxiliares de validacion
*/
// email
String.prototype.testEmail = function() {
	var reEmail = /^(?:\w+(-\w+)*\.?)*\w+@(?:\w+(-\w+)*\.)+\w+$/;
	return reEmail.test(this);
}

// fecha (hace uso de la extension del String que viene a continuacion)
String.prototype.testDate = function(f) {
	var f = f || 'dd/mm/yyyy'; // formato de la fecha a validar, 
    f = f.replace(/([\/\-])/g, '\\$1');
    f = f.replace('dd', '(0?[1-9]|[12][0-9]|3[01])'); // dias
    f = f.replace('mm', '(0?[1-9]|1[0-2])'); // meses
    f = f.replace('yyyy', '(19|20)\\d{2}'); // anyos, solo para 1901 hasta 2099
    f = ['/\\b', f, '/'].join('');
    reFecha = eval(f);
    if (!reFecha.test(this) || this.substring(0, 2) != this.toDate().getDate()) {
        return false;
    } else {
        return true;
    }
}

// extendemos el objeto String con la clase toDate, que devuelve un objeto Date 
String.prototype.toDate = function(f, modDia, modMes) {
	var f     = f || 'dd/mm/yyyy';
    var modDia= modDia || 0;
    var modMes= modMes || 0;
    var anyo  = this.substring(f.indexOf('y'), f.lastIndexOf('y') + 1);
    var mes   = parseInt(this.substring(f.indexOf('m'), f.lastIndexOf('m') + 1), 10) + modMes;
    var dia   = parseInt(this.substring(f.indexOf('d'), f.lastIndexOf('d') + 1), 10) + modDia;
    var fecha = new Date(anyo, mes-1, dia);
    return fecha;
}

/*
 * -------------------------------------------------------------- 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)});
	$('.pestanya').click(function() {
		var $this = $(this);
		var idPestanya = this.href;
		if (this.nodeName != 'A' && this.nodeName != 'a') {
			idPestanya = $(this).find('a.pestanya').attr('href');
		}
		var pos = idPestanya.indexOf('#');
		if (pos >= 0) {
			idPestanya = idPestanya.substring(pos);
		}
		var $mostrar = $(idPestanya);
		var $elDiv = $this.closest('div');
		$elDiv.children('div').each(function() {
			$(this).hide('fast');
		});
		$mostrar.show('fast');
		return false;
	});
});

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)
}

/*
 * -------------------------------------------------------------- paneles genericos 
 * estilos asociados en css/tools.css
*/
var estadoPaneles;
try {estadoPaneles = eval(getCookie('estadoPaneles'))} catch(e) {};
estadoPaneles = estadoPaneles || {};

function initPanels(scope) {
	var scope = scope || document,
		$a = $('a.showPanel', scope),
		$p = $('.panel', scope);
	
	$p.each(function(index) {
		var sAccion = this.id && estadoPaneles[this.id] ? 'addClass' : 'removeClass',
			$thisA = $a.eq(index),
			$thisP = $p.eq(index),
			clasesOK = $thisA.filter('.active').length == $thisP.filter('.shown').length;
		// si tiene identificador actuamos segun lo almacenado en estadoPaneles o
		// si tiene las clases desemparejadas las quitamos (sAccion es 'removeClass')
		if (this.id || !clasesOK ) {
			$thisA[sAccion]('active');
			$thisP[sAccion]('shown');
		}
		// chivato para desarrollo en caso de error
		if (!clasesOK) {
			try {
				console.log('Error de emparejamiento de clases entre:');
				console.log($thisA.get(0));
				console.log($thisP.get(0));
			} catch(e) {}
		}
	});
}

$('a.showPanel').live('click', function() {
	var $a = $('a.showPanel'),
		$p = $('.panel'),
		index = $a.index(this);
	$a.eq(index).toggleClass('active');
	$p.eq(index).css('height','').slideToggle(400, function() {
		var $t = $(this);
		$t.toggleClass('shown').css({display:'', height:$.browser.msie ? '1%':''}); // height:1% para corregir bug IE
		if (this.id) {
			estadoPaneles[this.id] = $t.hasClass('shown') ? 1 : 0;
		}
	});
	return false;
});

// almacenar cookie
$(window).unload(function() {
	var aTemp = [];
	for (i in estadoPaneles) {
		aTemp.push(i+':'+estadoPaneles[i]);
	}
	setCookie('estadoPaneles', '({' +aTemp.join(',')+ '})', 7);
});

/*
 * -------------------------------------------------------------- clases para los listados 
*/
function extendLists(scope) {
	var scope = scope || document;
	$('li:first-child', scope).addClass('first');
	$('li:last-child', scope).addClass('last');
}

/*
 * -------- evento autoadjudicable de pestanyas, requiere pasarle una HREF="#LOQUESEA"
 */
jQuery('.controlTabs li a').live('click',function() {
    var $t     = jQuery(this).not('.active'),
        $a     = $t.closest('.controlTabs').find('li a[href*=#]'),
        $tabs  = jQuery($a.map(function(){return this.href.getAnchor()}).get().join(',')),
        $toShow= jQuery(this.href.getAnchor()),
        $ul    = $toShow.parent('.tabList'), // solo aplicable en caso de existir listado (no es estrictamente necesario)
        vel    = 1000,
        targetH= 0;
    // si no existe $t petamos
    if ($t.length === 0) {
        return false;
    }
	// ocultamos los paneles destacados de producto
	$toShow.find('div.destSecProd').hide();
    // reasignamos clases
    $a.removeClass('active');
    $t.addClass('active');
    // averiguamos la altura del elemento a mostrar
    targetH = $toShow.css({visibility:'hidden',display:'block'}).height();
    $toShow.css({visibility:'visible',display:'none'});
    if ($ul.length) {
        //forzamos que el $ul vaya a targetH
        $ul.css({
            overflow:'hidden',
            height:$ul.height()
        }).animate({height:targetH}, vel, function() {
            $ul.css({overflow:'', height:''});
        });
    }
    // ocultamos las que sean visibles y mostramos la que toca
    $tabs.filter(':visible').not(this.href.getAnchor()).slideUp(vel);
    $toShow.height(0).show().animate({height:targetH}, vel, function() {
        $toShow.css({overflow:'', height:''})
		.find('div.destSecProd').fadeIn();
    });
    return false;
});
jQuery('a.closeTab').live('click',function() {
    // ocultamos las pestanas y asignamos la funcion closeTab de ser necesario
    // la unica condicion que se le pone al closeTab es que el primer elemento con identificador que encuentre en todos sus ancestros sea la propia pestana
    var id = jQuery(this).closest('[id]').attr('id');
    jQuery('#'+id).hide('blind',{direction:'vertical'},1000);
    jQuery('a[href$=#'+id+']').removeClass('active');
});

// inicializarPestanyas
function initTabs(contexto) {
    var $li= jQuery('.controlTabs li'),
        $a = $li.find('a'),
        $active = $li.find('a.active');

    if ($a.length && $li.length) {
        jQuery($a.map(function(){
            return this.href.getAnchor()
        }).get().join(',')).hide(); // ocultamos las pestanas
        if ($active.length) {
            jQuery($active.map(function(){
                return this.href.getAnchor()
            }).get().join(',')).show(); // si hay alguna activa la mostramos, faltaria mas
        }
    }
}


/*
 * -------------------------------------------------------------- eventos especiales para los enlaces
*/
function extendLinks(scope) {
	var scope = scope || document;
	$('a[rel=external]', scope).attr({target: '_blank'});
}

/*
 * 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;
        });
    }
});


/*
 * -------------------------------------------------------------- llamada global para las funciones del DOM
*/
function extendDOM(scope) {
	var scope = scope || document;
	$('img[id$=.png]', scope).pngIE6();
	extendLists(scope);
	extendLinks(scope);
	initPanels(scope);
	initTabs(scope);
}

// llamamos a distintas funciones al iniciar el DOM
$(document).ready(function() {
	// extendemos el DOM a traves de las funciones definidas a tal efecto
	extendDOM(document);
});

function getIniScroll(){
    return (window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop);
}

function scrolea(end){
    ini=getIniScroll();
    steps=20;
    for(i=1;i<=steps;i++){
        paso=Math.sin(i/steps * Math.PI/2);
        setTimeout('window.scrollTo(0,'+(Math.round(ini+(end-ini)*paso ))+')',i*40);
    }
}

