
/*
..........................................................................
:: 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'})
});

$( document ).ready( function() {
$("a[rel='pop-up']").click(function () {
          var caracteristicas = "height=600,width=580,scrollTo,resizable=1,scrollbars=1,location=0,left=200,top=100";
          nueva=window.open(this.href, 'Popup', caracteristicas);
          return false;
         });
});


/*
..........................................................................
:: 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);
}

// 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;
}

/*
..........................................................................
:: 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;
        });
    }
});

// Dynamic forms
function DForm(elem, o) {
    // definimos el a partir del propio Element o a traves de la ID
    var _el = this.elem  = typeof elem == 'object' && elem.tagName ? elem : document.getElementById(elem);
    var _fi = this.field = _el.getElementsByTagName('FIELDSET');
    var o   = o || {};
    this.legend= [];
    this.validation = [];
    this.aniSpeed = o.aniSpeed || 600;
    this._aField = 0;
    this._evSumbit = false;
    // asignamos a cada elemento del Array legend, de no tenerlo se deja vacio
    for (var i=0,l=_fi.length; i<l; ++i) {
        this.legend.push(_fi[i].getElementsByTagName('LEGEND')[0]);
    }
} 

DForm.prototype.addValidation = function(nF, fVal) {
    /* las funciones de validacion deberian devolver o bien
     * un String con el HTML de error si es invalido
     * o FALSE si es valido
     */
    var _t = this;
    this.validation[nF] = fVal;

    if (!_t._evSumbit) {
        this._evSumbit = true;
        $(_t.elem).submit(function() {
            return _t.submit();
        });
    }
}

DForm.prototype.validate = function(nF, animacion) {
    var OKO = this.validation[nF](this.field[nF]),
        animacion = animacion === false ? false : true;
    if (typeof OKO == 'string' && OKO.length) {
        this.showError(nF, OKO, animacion)
        return false;
    } else {
        this.hideError(nF);
        return true;
    }
}

DForm.prototype.hideError = function(nF) {
    var field = this.field[nF];
    $('div.ko', field).slideUp(this.aniSpeed, function(){
        $(this).remove();
    });
}

DForm.prototype.showError = function(nF, errTxt) {
    var field = this.field[nF],
        animacion = animacion === false ? false : true,
        aniSpeed = animacion ? this.aniSpeed : 0,
        errDiv = $('div.ko', field);
    if (errDiv.length) {
        errDiv.html(errTxt).fadeOut(aniSpeed/4).fadeIn(aniSpeed/4).fadeOut(aniSpeed/4).fadeIn(aniSpeed/4);
    } else {
        $(['<div class="ko" style="display:none">', errTxt, '</div>'].join('')).prependTo(field).slideDown(aniSpeed);
    }
}

DForm.prototype.toField = function (nF) {
    var _aF = this._aField,
        $f  = $(this.field),
        val = true,
        $tabs = $(this.elem).prev('.DForm-tabs').find('a'),
        animField = function(ini, fin) {
            var $ini = $f.eq(ini),
                $fin = $f.eq(fin).css({visibility:'hidden', position:'absolute', display:'block'}), // ocultamos pero mostramos :P
                $form = $f.eq(0).closest('form'),
                dir = ini > fin ? {ini:'right', fin: 'left'} : {ini: 'left', fin: 'right'}, // los campos van a izquierda o derecha ?
                aniSpeed = this.aniSpeed,
                targetH = parseInt($fin.height()) + parseInt($fin.css('paddingTop')) + parseInt($fin.css('paddingBottom')); // calculamos la altura a la que se tiene que convertir el $form
            $form.css({position: 'relative', overflow: 'hidden'});
            $fin.css({visibility:'', position:'', display:'none'});
            $form.animate({height:targetH+'px'}, aniSpeed);
            $ini.hide('drop', {direction:dir.ini}, aniSpeed, function() {
                $fin.show('drop', {direction:dir.fin}, aniSpeed, function() {
                    $form.css({height:'auto', overflow:'auto'})
                });
            });
            $tabs.removeClass('active').eq(fin).addClass('active');
        };
    
    // hacemos las validaciones hasta que esten todas las que tocan o hasta que pete
    if (nF == _aF) return false;
    for (var i=_aF; i<nF; ++i)  {
        if (this.validation[i] && !this.validate(i, i==_aF)) { // OJO, si i!=_aF pasamos FALSE como parametro de animacion
            this.toField(i);
            val = i;
            break;
        }
    }
    
    if (val === true) {
        // hacemos la animacion hacia nF
        if (nF<$f.length) {
            animField(_aF, nF);
            this._aField = nF;
        }
        return true;
    } else {
        // hacemos la animacion, pero hacia val
        if (_aF!=val) {
            animField(_aF, val);
            this._aField = val;
        }
        return false;
    }
}

DForm.prototype.submit = function() {
    if (this.toField(this.field.length) === true) {
        return true;
    } else {
        return false;
    }
}

DForm.prototype.makeTabs = function(controls) {
    var _t = this,
        _e = _t.elem,
        _f = this.field,
        $c = $(_f).append('<div class="DForm-buttons" />').children(':last-child'),
        controls = controls === false ? false : true,
        aHtml = ['<ul class="DForm-tabs">'];
    for (var i=0,l=_f.length; i<l; ++i) {
        // anadimos los botones dentro de los fields
        if (i>0) {
            _f[i].style.display = 'none';
            if (controls) {
                $(['<button type="button" class="DForm-prev boton" value="', i-1,'">', evento.anterior, '</button>'].join('')).appendTo($c.eq(i)).click(function() {
                    _t.toField(this.value);
                });
            }
        }
        if (i<l-1) {
            if (controls) {
                $(_e).find('[type=submit]').remove();
                $(['<button type="button" class="DForm-next boton" value="', i+1,'">', evento.siguiente, '</button>'].join('')).appendTo($c.eq(i)).click(function() {
                    _t.toField(this.value);
                });
            }
        }
        if (i==l-1) {
            $(['<button type="submit" class="DForm-submit boton">', evento.enviar, '</button>'].join('')).appendTo($c.eq(i));
        }
        aHtml.push('<li id="', _e.id, '_', i, '"><a class="', i==0 ? 'active':'' ,'">', _t.legend[i] ? _t.legend[i].textContent : evento.leyenda+(i+1), '</a></li>');
    }
    aHtml.push('</ul>');
    if (controls) {
        $(aHtml.join('')).insertBefore(_e).find('li').click(function() {
            var id = this.id;
            _t.toField( id.substring(id.lastIndexOf('_')+1) );
        });
    }
}

/*
..........................................................................
:: Plugin de jQuery para el redimensionamiento automatico de lo que     ::
:: sería una imagen de fondo que puede ser cogida tanto estaticamente   ::   
:: como dinamicamente por php											::	
:: Consejos:hay que ajustar el overflow a hidden y seguramente quieras 	::
:: un DIV encima con position absolute Y overflow:auto para que se vea 	::
:: guayamente el contenido  											::
:: 		  																::
..........................................................................
*/


jQuery.fn.extend({
	resizableBg: function(src, options) {
		return this.each(function() {
			var $t = $(this)
				imagen = new Image(),
				claseCtrl = 'lda-resizableBg',
				options = typeof options !== 'object' ? {} : options;
			//definimos las opciones por defecto del options
			options.centrar = options.centrar || true;
				
			// preparamos el elementos para contener la nueva imagen
			$t.children('.'+claseCtrl).remove();
			imagen.src = src;
			$t.prepend(imagen).css('overflow','hidden');

			// creamos el evento de resize
			$t.add(window).resize(function() {
				var dispH = $t.height(),
					dispW = $t.width(),
					imgH  = imagen.imgH,
					imgW  = imagen.imgW,
					ratioH= dispH / imgH,
					ratioW= dispW / imgW,
					ratio = Math.max(ratioH, ratioW);
				// tamanyo
				$(imagen)
				.css('height', (ratio / ratioH)*100 + '%')
				.css('width', (ratio / ratioW)*100 + '%');
				// centrados //
				// comprobamos si tenemos que centrar en la imagen
				if ((options.centrar === true || options.centrar == 'vertical')) {
					$(imagen).css('marginTop', [
						ratio != ratioH ? (dispH - ratio*imgH)/2 : 0, 'px'
					].join(''));
				}
				if ((options.centrar === true || options.centrar == 'horizontal')) {
					$(imagen).css('marginLeft', [
						ratio != ratioW ? (dispW - ratio*imgW)/2 : 0, 'px'
					].join(''));
				}
				
				
			});

			// e iniciamos por primera vez la funcion al cargar la imagen
			imagen.onload = function() {
				imagen.imgH = imagen.height;
				imagen.imgW = imagen.width;
				$t.resize();
			}
		});
	}
});

function getSelectionStart(o) {
	if (o.createTextRange) {
		var r = document.selection.createRange().duplicate()
		r.moveEnd('character', o.value.length)
		if (r.text == '') return o.value.length
		return o.value.lastIndexOf(r.text)
	} else return o.selectionStart
}

function getSelectionEnd(o) {
	if (o.createTextRange) {
		var r = document.selection.createRange().duplicate()
		r.moveStart('character', -o.value.length)
		return r.text.length
	} else return o.selectionEnd
}

// funciones auxliares de formularios comunes
$(function() {	
	// inputs del tipo fecha
	$("input.fecha", document).each(function(){
		var $t = $(this),
			$wrap = $t.closest('label,div').wrap('<div style="position:relative"></div>').parent(), // creamos un DIV que encierre a los fruskis
			$input = null;
		// creamos un div en absoluto que contenga tres campos
		$wrap.append('<div></div>').children('div:last').css({
			position:'absolute',
			top:     $t.offset().top - $wrap.offset().top + 'px',
			left:    $t.offset().left - $wrap.offset().left + 'px',
			color:   $t.css('color')
		}).html([
			'<input type="text" class="lda-fecha lda-dia" value="',$t.val().substring(0,2),'" maxlength="2" /> / ',
			'<input type="text" class="lda-fecha lda-mes" value="',$t.val().substring(3,5),'" maxlength="2" /> / ',
			'<input type="text" class="lda-fecha lda-ano" value="',$t.val().substring(6),'" maxlength="4" />'
		].join(''));
		// definimos la variable $input y cambiamos el comportamiento del input original
		$input = $wrap.find('input.lda-fecha');
		$t.css('color',$t.css('background-color')).focus(function(){
			$input.eq(0).focus();
		});
		
		$input.keypress(function(evento){
			var $current = $(this),
				codigo = evento.keyCode,
				caracter = evento.charCode,
				posicion = getSelectionStart(this);
			// backspace
			if (!$current.hasClass('lda-dia') && 8 == codigo && 0 == posicion){
				$current.prev().focus();
				return;
			}
			// pulsar tecla al final del input
			if (!$current.hasClass('lda-ano') && caracter >= 48 && caracter <= 57 && 9 != codigo && 2 == posicion){
				$current.next().focus().val(String.fromCharCode(caracter));
				return;
			}
		})
		.each(function() {
			// cacheamos el valor
			this.cache = this.value;
		})
		.change(function() {
			$t.val([$input.eq(0).val(),'/',$input.eq(1).val(),'/',$input.eq(2).val()].join(''))
		})
		.focus(function() {
			if (this.value == this.cache) this.value='';
		})
		.blur(function() {
			if (this.value == '') this.value=this.cache;
		});
	});
});