var empresa_eleg="";
Selectors.Pseudo.selected = function(){
    return (this.selected && 'option' == this.get('tag'));
};
Selectors.Pseudo.checked = function(){
    return ('input' == this.get('tag') && ('radio' == this.get('type') || 'checkbox' == this.get('type')) && this.checked);
};

String.implement({
	nl2br:function(str, is_xhtml) {
       var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
	   return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1'+ breakTag +'$2');
	}
});



var CargandoAjax = new Element('div', {
    id: 'AjaxCargando',
    styles: {
        backgroundColor: 'white',
        width: '100px',
        height: '25px',
        position: 'relative',
        zIndex: 900,
        display: 'none',
        padding: '5px',
        border: '1px solid #4A4A4C'
    },
    'class': 'txt_a',
    html: '<img style="padding-right:5px" src="images/carga_ajax.gif" align="absmiddle"/>Cargando...'

});


Element.implement({
    val: function(){
        return this.get("value");
    },
    show: function(){
        this.setStyle('display', 'block');
        this.setStyle('visibility', 'visible');
    },
    hide: function(){
        this.setStyle('display', 'none');
        this.setStyle('visibility', 'hidden');
    },
    html: function(htm){
        this.set("html", htm);
    },
    Imprimir: function(){
        var strName = 'printer-' + (new Date()).getTime(), styles = $$('link[type=text/css]').clone(), title = document.title, that = this, iframe = new IFrame({
            name: strName,
            styles: {
                width: 1,
                height: 1,
                position: 'absolute',
                left: -9999
            },
            events: {
                load: function(){
                    var doc = this.contentDocument || window.frames[strName].document;
                    doc.title = title;
                    $(doc.body).adopt(styles, that.clone());
                    this.contentWindow.focus(); // IE necesita obtener el foco sino imprime el frame padre.
                    this.contentWindow.print();
                }
            }
        }).inject($(document.body));
        iframe.dispose.delay(15000); // Destruimos el iframe luego de 15 segundos.
    },
	print:function(){
		this.contentWindow.focus(); // IE necesita obtener el foco sino imprime el frame padre.
        this.contentWindow.print();
	},
    PNG: function(){
        if (Browser.Engine.trident4) {
            for (var i = 0; i < document.images.length; i++) {
                var img = document.images[i];
                var imgName = img.src.toUpperCase();
                if (imgName.substring(imgName.length - 3, imgName.length) == "PNG") {
                    var imgID = (img.id) ? "id='" + img.id + "' " : "";
                    var imgClass = (img.className) ? "class='" + img.className + "' " : "";
                    var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' ";
                    var imgStyle = "display:inline-block;" + img.style.cssText;
                    if (img.align == "left") 
                        imgStyle = "float:left;" + imgStyle;
                    if (img.align == "right") 
                        imgStyle = "float:right;" + imgStyle;
                    if (img.parentElement.href) 
                        imgStyle = "cursor:hand;" + imgStyle;
                    var strNewHTML = "<span " + imgID + imgClass + imgTitle;
                    +" style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";" +
                    "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader" +
                    "(src=\'" +
                    img.src +
                    "\', sizingMethod='scale');\"></span>";
                    img.outerHTML = strNewHTML;
                    i = i - 1;
                }
            }
            var imgURL = this.getStyle('background-image');
            var imgURLLength = imgURL.length;
            //alert(imgURL);
            if (imgURL.indexOf(".png") != -1) {
                //alert(imgURL);
                //alert(imgURL.substring(4,imgURLLength  - 1));
                this.setStyles({
                    background: 'none',
                    filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled='true', sizingMethod='crop', src='" + imgURL.substring(5, imgURLLength - 2) + "')"
                });
            };
                    }
        
        
    },
    reflect: function(options){
        var img = this;
        if (img.get("tag") == "img") {
            options = $extend({
                height: 0.33,
                opacity: 0.5
            }, options);
            
            img.unreflect();
            
            function doReflect(){
                var reflection, reflectionHeight = Math.floor(img.height * options.height), wrapper, context, gradient;
                
                if (Browser.Engine.trident) {
                    reflection = new Element("img", {
                        src: img.src,
                        styles: {
                            width: img.width,
                            height: img.height,
                            marginBottom: -img.height + reflectionHeight,
                            filter: "flipv progid:DXImageTransform.Microsoft.Alpha(opacity=" + (options.opacity * 100) + ", style=1, finishOpacity=0, startx=0, starty=0, finishx=0, finishy=" + (options.height * 100) + ")"
                        }
                    });
                }
                else {
                    reflection = new Element("canvas");
                    if (!reflection.getContext) 
                        return;
                    try {
                        context = reflection.setProperties({
                            width: img.width,
                            height: reflectionHeight
                        }).getContext("2d");
                        context.save();
                        context.translate(0, img.height - 1);
                        context.scale(1, -1);
                        context.drawImage(img, 0, 0, img.width, img.height);
                        context.restore();
                        context.globalCompositeOperation = "destination-out";
                        
                        gradient = context.createLinearGradient(0, 0, 0, reflectionHeight);
                        gradient.addColorStop(0, "rgba(255, 255, 255, " + (1 - options.opacity) + ")");
                        gradient.addColorStop(1, "rgba(255, 255, 255, 1.0)");
                        context.fillStyle = gradient;
                        context.rect(0, 0, img.width, reflectionHeight);
                        context.fill();
                    } 
                    catch (e) {
                        return;
                    }
                }
                reflection.setStyles({
                    display: "block",
                    border: 0
                });
                
                wrapper = new Element(($(img.parentNode).get("tag") == "a") ? "span" : "div").injectAfter(img).adopt(img, reflection);
                wrapper.className = img.className;
                img.store("reflected", wrapper.style.cssText = img.style.cssText);
                wrapper.setStyles({
                    width: img.width,
                    height: img.height + reflectionHeight,
                    overflow: "hidden"
                });
                img.style.cssText = "display: block; border: 0px";
                img.className = "reflected";
            }
            
            if (img.complete) 
                doReflect();
            else 
                img.onload = doReflect;
        }
        
        return img;
    },
    unreflect: function(){
        var img = this, reflected = this.retrieve("reflected"), wrapper;
        img.onload = $empty;
        
        if (reflected !== null) {
            wrapper = img.parentNode;
            img.className = wrapper.className;
            img.style.cssText = reflected;
            img.store("reflected", null);
            wrapper.parentNode.replaceChild(img, wrapper);
        }
        
        return img;
    },
    enVivo: function(event, selector, fn){
        this.addEvent(event, function(e){
            var t = $(e.target);
            if (!t.match(selector)) 
                return false;
            fn.apply(t, [e]);
        }
.bindWithEvent(this, selector, fn));
    },
    fadeTo: function(value, duration){
        (duration == "") ? speed = 500 : speed = duration;
        var elt = this;
        elt = new Fx.Tween(elt, {
            duration: speed,
            //transition : Fx.Transitions.Quad.easeIn,
            wait: true
        });
        elt.start('opacity', value);
    },
    muestraAjax: function(){
        div = this;
        contenedor = div.getParent();
        coord = contenedor.getCoordinates();
        CargandoAjax.setStyles({
            "top": (coord.height / 2 - 30),
            "left": ((coord.width / 2) - 90)
        });
        contenedor.grab(CargandoAjax);
        CargandoAjax.show();
    },
    escondeAjax: function(){
        div = (this);
        CargandoAjax.hide();
    },
	tooltip:function(options){
		 options = $extend({
				div:this.get("id"),
				ancho: 319,
                alto: 73,
				fondo:"images/tooltip_2.png",
                bntCerrar: '<div style="font-family:verdana;font-size:12px;color:#000000;top:3px;position:relative"><strong>X</strong></div>',
                alinear: "izquierda",
                html: this.get("html"),
                estiloInterior: "txtToolTip",
                forzarCierre: true
         }, options);
		new Tooltips(options)
	}
    
});


/****/

var Decor = new Class({
    tipOlvido: "",
    ZOOM: "",
	slide:'',
    initialize: function(){
        dbug.enable();
    },
	activaActualizacion:function(){
		if($('frmactualizaDatos')){
			new FormCheck("frmactualizaDatos", {
               display: {
                    scrollToFirst: false,
					errorsLocation : 0,
					indicateErrors : 2,
					showErrors : 1,
					addClassErrorToField : 1
                },
                submitByAjax: true,
				onAjaxRequest:function(){
					$('div_aviso_actualizacion').removeClass("mensajeOk").set("html","Guardando datos....");
				},
                onAjaxSuccess: function(e){
					$('div_aviso_actualizacion')
					.addClass("mensajeOk").set("html","<img style='padding-right:8px' src='images/pass_ok.png' align='absmiddle'/>Datos Grabados correctamente");
					new Request.CroosDomain("http://www.decor-club.com/index.html",{
						  onSuccess:function(data){
							 // alert(data.results);
						  }
					});//.send($('frmactualizaDatos').toQueryString());
                }
            });
		}
	},
    activaFormSpryContact: function(){
        if ($('formContacto')) {
            $('formContacto').addEvent("submit", function(e){
                e.preventDefault();
				var ret = Spry.Widget.Form.validate($('formContacto'));
                if (ret) {
                    $('msgContacto').show();
                    $('formContacto').set("send", {
                        onSuccess: function(){
                            Alertas("<p>Gracias por enviarnos tus comentarios.Pronto nos pondremos en contacto contigo.</p>");
                            $('formContacto').reset();
                            setTimeout(function(){
                                window.location.href = 'index.php';
                                return false;
                            }, 3000);
                        }
                    });
                    this.send();
                }
            });
        }
    },
    activaZoomEncarte: function(){
        this.ZOOM = new AZoom("aZoom", {
            capaZoom: "barra_en",
            mas: "mas",
            menos: "menos",
            altoImagen: 483,
            anchoImagen: 833,
            limita: "si"
        });
        
    },
    verDetalleEncarte: function(url){
        (url == "") ? pag = "sec/listaDetalleEncartes.php" : pag = url;
        new Request.JSON({
            url: pag,
            onSuccess: function(e){
                fila = e.filas;
                new Asset.image("images/encarte" + fila[0].imagen);
                $('aZoom').set("src", "images/encarte/" + fila[0].imagen)
                $('pag_en').set("html", e.navegacion)
                $('aZoom').show();
                this.ZOOM.resetearZoom();
            }.bind(this)
        }).send("id=" + $('idEncarte').get("value"));
    },
    verNovedades: function(url){
        (url == "") ? pag = "sec/listaNovedades.php" : pag = url;
        if ($('capa_novedades')) {
            $('capa_novedades').set("load", {
                onSuccess: function(){
                    $('capa_novedades').escondeAjax()
                }
            }).muestraAjax();
            var tween = $('capa_novedades').get('tween', {
                property: 'opacity'
            });
            tween.start(0).chain(function(){
                $('capa_novedades').load(pag);
                tween.start(1);
            });
        }
    },
    slideHome: function(){
        if ($('cabecera_decorcenter')) {
            this.slideshow = new ASlide('cabecera_decorcenter', '#cabecera_decorcenter img');
            $('cabecera_decorcenter').setStyle("visibility", "visible");
            this.slideshow.start();
			this.animaHome();
        }
    },
    cerrarSesion: function(){
        if ($('cerrar_sesion')) {
            $('cerrar_sesion').addEvent("click", function(){
                window.location.href = 'login/logout.php';
                return false;
            }).setStyle("cursor", "pointer").set("title", "Cerrar sesion");
        }
    },
    enviaEncuesta: function(){
        var theForm = typeof form != 'object' ? document.getElementById('formEncuesta') : form;
        var ret = Spry.Widget.Form.validate(theForm);
        if (ret) {
            return true
        }
        else {
            jQuery('.scrollBar').jScrollPane({
                showArrows: false,
                scrollbarWidth: 25
            });
            return false;
        }
    },
    activaRadios: function(){
        $$('#conteni_encuesta input[type="radio"]').addEvent("click", function(){
            var actual = this.get("value");
            (actual == "otro") ? $('texto_' + this.get("name")).show() : $('texto_' + this.get("name")) ? $('texto_' + this.get("name")).set("value", "").hide() : ''
        });
    },
    activaEncuesta: function(){
        if ($('formEncuesta')) {
            new FormCheck("formEncuesta", {
                display: {
                    errorsLocation: 3,
                    indicateErrors: 2,
                    flashTips: true,
                    fadeDuration: 1000
                }
            });
            
        }
    },
    alternativa: function(id){
        ($(id).get("checked")) ? $('texto_' + id).show() : $('texto_' + id).set("value", "").hide();
    },
    validaPass: function(){
        pass = $('pass_anterior').val();
        estado = $('estado').val();
        if (pass.length < 3) {
            return false;
        }
        user = $('id_usuario_edit').val();
        new Request({
            url: '_editaPass.php?comprobar_pass=yes',
            onSuccess: function(e){
                if (e == "ok") {
                    if ($('pass_anterior').hasClass('pass_error')) {
                        $('pass_anterior').removeClass('pass_error');
                        $('pass_anterior').addClass('pass_ok');
                    }
                    else {
                        $('pass_anterior').addClass('pass_ok');
                    }
                    $('estado').set("value", "1");
                }
                else {
                    if ($('pass_anterior').hasClass('pass_ok')) {
                        $('pass_anterior').removeClass('pass_ok');
                        $('pass_anterior').addClass('pass_error')
                    }
                    else {
                        $('pass_anterior').addClass('pass_error')
                    }
                    $('estado').set("value", "0");
                }
            }
        }).send("p=" + pass + "&u=" + user);
    },
    enviaPromotick: function(){
        if ($('formPromotick')) {
            $('formPromotick').submit();
        }
        
    },
    verAmbientes: function(id){
        (id == "") ? $accion = 0 : $accion = id;
        if ($('prod_ambientes')) {
            $('prod_ambientes').set("load", {
                onSuccess: function(){
                    $('prod_ambientes').escondeAjax();
                    //var Tips1 = new Tips('.Tips1');
					Cufon.refresh;
                }
            }).muestraAjax();
            var tween = $('prod_ambientes').get('tween', {
                property: 'opacity',
                duration: 800
            });
            tween.start(0).chain(function(){
                $('prod_ambientes').load("sec/listaAmbientes.php?c=" + $accion);
                tween.start(1);
            });
            
        }
    },
    pagAmbientes: function(url){
        if ($('prod_ambientes')) {
            var tween = $('prod_ambientes').get('tween', {
                property: 'opacity'
            });
            tween.start(0).chain(function(){
                $('prod_ambientes').load(url);
            });
            $('prod_ambientes').set("load", {
                onSuccess: function(){
                    $('prod_ambientes').escondeAjax();
                    tween.start(1);
                }
            }).muestraAjax();
        }
    },
	verCategoriasAmbientes:function(id){
		(id == "") ? $accion = 0 : $accion = id;
        if ($('prod_categoria_ambientes' )) {
            $('prod_categoria_ambientes').set("load", {
                onSuccess: function(){
                    $('prod_categoria_ambientes').escondeAjax();
                }
            }).muestraAjax();
            var tween = $('prod_categoria_ambientes').get('tween', {
                property: 'opacity',
                duration: 800
            });
            tween.start(0).chain(function(){
                $('prod_categoria_ambientes').load("sec/listaCategoriasAmbientes.php?c=" + $accion);
                tween.start(1);
            });
            
        }
	},
	pagCategoriasAmbientes: function(url){
        if ($('prod_categoria_ambientes')) {
            var tween = $('prod_categoria_ambientes').get('tween', {
                property: 'opacity'
            });
            tween.start(0).chain(function(){
                $('prod_categoria_ambientes').load(url);
            });
            $('prod_categoria_ambientes').set("load", {
                onSuccess: function(){
                    $('prod_categoria_ambientes').escondeAjax();
                    tween.start(1);
                }
            }).muestraAjax();
        }
    },	
    verImagenAmbiente: function($id){
        new Ventana({
            titulo: "",
            url: "popup_ambiente.php?id=" + $id,
            modal: true,
            fondo: "",
            alto: 604,
            ancho: 683,
            borde: 0,
            separacion: 0,
            btnCerrar: "cerrar_prod"
        }).render();
    },
    verEncartes: function(){
        if ($('capa_encarte')) {
            $('capa_encarte').set("load", {
                onSuccess: function(){
                    $('capa_encarte').escondeAjax();
                    //var Tips1 = new Tips('.Tips1');
                }
            }).muestraAjax();
            var tween = $('capa_encarte').get('tween', {
                property: 'opacity',
                duration: 800
            });
            tween.start(0).chain(function(){
                $('capa_encarte').load("sec/listaEncartes.php");
                tween.start(1);
            });
            
        }
    },
    pagEncartes: function(url){
        if ($('capa_encarte')) {
            var tween = $('capa_encarte').get('tween', {
                property: 'opacity'
            });
            tween.start(0).chain(function(){
                $('capa_encarte').load(url);
            });
            $('capa_encarte').set("load", {
                onSuccess: function(){
                    $('capa_encarte').escondeAjax();
                    tween.start(1);
                }
            }).muestraAjax();
        }
    },
    verImagenEncarte: function($id){
        new Ventana({
            titulo: "",
            url: "popup_encarte.php?id=" + $id,
            modal: true,
            fondo: "",
            alto: 548,
            ancho: 872,
            borde: 0,
            separacion: 0,
            btnCerrar: "cerrar_encarte"
        }).render();
    },
    verOfertas: function(){
        if ($('capa_novedades')) {
            $('capa_novedades').set("load", {
                onSuccess: function(){
                    $('capa_novedades').escondeAjax();
                    //var Tips1 = new Tips('.Tips1');
                }
            }).muestraAjax();
            var tween = $('capa_novedades').get('tween', {
                property: 'opacity',
                duration: 800
            });
            tween.start(0).chain(function(){
                $('capa_novedades').load("sec/listaOfertas.php");
                tween.start(1);
            });
            
        }
    },
    pagOfertas: function(url){
        if ($('capa_novedades')) {
            var tween = $('capa_novedades').get('tween', {
                property: 'opacity'
            });
            tween.start(0).chain(function(){
                $('capa_novedades').load(url);
            });
            $('capa_novedades').set("load", {
                onSuccess: function(){
                    $('capa_novedades').escondeAjax();
                    tween.start(1);
                }
            }).muestraAjax();
            
            
        }
    },
    verImagenOferta: function($id){
        new Ventana({
            titulo: "",
            url: "popup_ofertas.php?id=" + $id,
            modal: true,
            fondo: "",
            alto: 604,
            ancho: 683,
            borde: 0,
            separacion: 0,
            btnCerrar: "cerrar_prod"
        }).render();
    },
    verProductos: function(id){
		
		if($('caja-productos')){
			box=$('caja-productos');
		}
		if($('cabecera_decorcenter')){
			box=$('cabecera_decorcenter');
			this.slideshow.stop();
		}
	
        if (box) {
            (id) ? $id = id : $id = 0;
            box.set("load", {
                onSuccess: function(){
                    box.escondeAjax();
                    
                    //var Tips1 = new Tips('.Tips1');
                }
            }).muestraAjax();
            var tween = box.get('tween', {
                property: 'opacity',
                duration: 800
            });
            tween.start(0).chain(function(){
                box.load("sec/listaLineas.php?c=" + $id);
                tween.start(1);
            });
            
        }
    },
    verMarcas: function(id){
	
		if($('caja-productos')){
			box=$('caja-productos');
		}
		if($('cabecera_decorcenter')){
			box=$('cabecera_decorcenter');
			this.slideshow.stop();
		}

        if (box) {
            (id) ? $id = id : $id = 0;
            box.set("load", {
                onSuccess: function(){
                    box.escondeAjax();
                    //var Tips1 = new Tips('.Tips1');
                }
            }).muestraAjax();
            var tween = box.get('tween', {
                property: 'opacity',
                duration: 800
            });
            tween.start(0).chain(function(){
                box.load("sec/listaMarcas.php?l=" + $id);
                tween.start(1);
            });
            
        }
    },
    verProductosFinal: function(id){
	
		if($('caja_prod_detalles')){
			box=$('caja_prod_detalles');
		}
		if($('cabecera_decorcenter')){
			box=$('cabecera_decorcenter');
			this.slideshow.stop();
		}
        if (box) {
            (id) ? $id = id : $id = 0;
            box.set("load", {
                onSuccess: function(){
                   box.escondeAjax();
                    //var Tips1 = new Tips('.Tips1');
                    dbug.nolog();
                },
                onRequest: function(){
                    dbug.nolog();
                }
            }).muestraAjax();
            var tween = box.get('tween', {
                property: 'opacity',
                duration: 800
            });
            tween.start(0).chain(function(){
                box.load("sec/listaFinalProductos.php?m=" + $id);
                tween.start(1);
            });
            
        }
    },
    pagProductos: function(url){
	
		if($('caja-productos')){
			box=$('caja-productos');
		}
		if($('cabecera_decorcenter')){
			box=$('cabecera_decorcenter');
			this.slideshow.stop();
		}
        if (box) {
            var tween = box.get('tween', {
                property: 'opacity'
            });
            tween.start(0).chain(function(){
                box.load(url);
            });
            box.set("load", {
                onSuccess: function(){
                    box.escondeAjax();
                    tween.start(1);
                }
            }).muestraAjax();
            
            
        }
    },
	pagProductosInternos:function(url){
		if($('caja_prod_detalles')){
			box=$('caja_prod_detalles');
		}
		if($('cabecera_decorcenter')){
			box=$('cabecera_decorcenter');
			this.slideshow.stop();
		}
	
	
	
		 if (box) {
            var tween = box.get('tween', {
                property: 'opacity'
            });
            tween.start(0).chain(function(){
                box.load(url);
            });
            box.set("load", {
                onSuccess: function(){
                    box.escondeAjax();
                    tween.start(1);
                }
            }).muestraAjax();
            
            
        }
	},
	 verProductosFinalMarca: function(id){
        if ($('caja_prod_detalles')) {
            (id) ? $id = id : $id = 0;
            $('caja_prod_detalles').set("load", {
                onSuccess: function(){
                    $('caja_prod_detalles').escondeAjax();
                    //var Tips1 = new Tips('.Tips1');
                    dbug.nolog();
                },
                onRequest: function(){
                    dbug.nolog();
                }
            }).muestraAjax();
            var tween = $('caja_prod_detalles').get('tween', {
                property: 'opacity',
                duration: 800
            });
            tween.start(0).chain(function(){
                $('caja_prod_detalles').load("sec/listaFinalProductosMarca.php?m=" + $id);
                tween.start(1);
            });
            
        }
    },	
    verPopupProducto: function($id){
        new Ventana({
            titulo: "",
            url: "popup_detalles2.php?id=" + $id,
            modal: true,
            fondo: "",
			alto: 581,
            ancho: 604,
            borde: 0,
            separacion: 0,
            btnCerrar: "cerrar_revest",
			onCerrar:function(){
				$$('.moot_tipo_alex').hide();
			}
        }).render();
    },
	verPopupProductoEs:function($id){
		new Ventana({
            titulo: "",
            url: "popup_detalles_hidro.php?id=" + $id,
            modal: true,
            fondo: "",
			alto: 595,
            ancho: 670,
            borde: 0,
            separacion: 0,
            btnCerrar: "cerrar_revest",
			onCerrar:function(){
				$$('.moot_tipo_alex').hide();
				if(typeof hs=="object"){
					hs.close();
				}
			}
        }).render();
	},
	verPopupIluminacionFinal: function($id){
        new Ventana({
            titulo: "",
            url: "popup_detalles_iluminacion.php?id=" + $id,
            modal: true,
            fondo: "",
			alto: 581,
            ancho: 604,
            borde: 0,
            separacion: 0,
            btnCerrar: "cerrar_revest",
			onCerrar:function(){
				$$('.moot_tipo_alex').hide();
			}
        }).render();
    },	
    verNovedad: function($id){
        new Ventana({
            titulo: "",
            url: "popup_novedades.php?id=" + $id,
            modal: true,
            fondo: "",
            alto: 604,
            ancho: 683,
            borde: 0,
            separacion: 0,
            btnCerrar: "cerrar_prod",
            onLoad: function(){
                setTimeout(function(){
                    jQuery('#div_img_oferta').jScrollPane({
                        showArrows: true
                    });
                    jQuery('#div_img_oferta').fadeIn();
                }, 500);
            }
        }).render();
    },
    verColoresProducto: function(id){
        if ($('acabados_revest')) {
            (id) ? $id = id : $id = 0;
            $('acabados_revest').set("load", {
                onSuccess: function(){
                    //var Tips1 = new Tips('.Tips1');
                    dbug.nolog();
                },
                onRequest: function(){
                    dbug.nolog();
                }
            });
            var tween = $('acabados_revest').get('tween', {
                property: 'opacity',
                duration: 800
            });
            tween.start(0).chain(function(){
                $('acabados_revest').load("sec/listaFinalColores.php?id=" + $id);
                tween.start(1);
            });
            
        }
    },
    pagColoresProducto: function(url){
        if ($('acabados_revest')) {
            var tween = $('acabados_revest').get('tween', {
                property: 'opacity'
            });
            tween.start(0).chain(function(){
                $('acabados_revest').load(url);
            });
            $('acabados_revest').set("load", {
                onSuccess: function(){
                    tween.start(1);
                }
            })
            
            
        }
    },
    verDetallesProducto: function($id){
		var tween = $('imgColorMediano').get('tween', {
                property: 'opacity',
				duration:800	
         });
	 
		var tween2=$('caracteristicasColor').get('tween', {
                property: 'opacity',
				duration:800	
         });
	 
		$('titulosColor').set("tween",{duration:800}).tween("top","130px;");
		$('caracteristicasColor').set("tween",{duration:800}).tween("top","380px;");
		
		//tween2.start(0);
		
		this.eligeColor($id);
		tween.start(0).chain(function(){
		
			if($('bxSD')){
				$('bxSD').fade("out");
				$('txtTuNombre').set("value","Tu Nombre");
				$('nombreDeAmigo').set("value","Nombre Amigo");
				$('emailDeAmigo').set("value","Email Amigo");
				$('msgSendEmail').set("html","");
			}
		
				new Request.JSON({
					url:"sec/detalleImagen.php?id=" + $id,
					onSuccess:function(e){
						$('codigoColor').set("html",e.codigo);
						if($('link_descarga')){
							$('link_descarga').set("href","download.php?file="+e.imagen_descarga);
						}
						$('nombreColor').set("html",e.color);
						$('imgColorMediano').set("src","images/lineas_de_marca/"+e.imagen);
							tween.start(1);
						$('caracteristicasColor').tween("top","0px;");
						$('caracteristicasColor').set("html",e.caracteristicas);
						
						//tween2.start(1);
							
						$('titulosColor').tween("top","0px;");
						
						$('lksend').set("value",e.idEnvioAmigo);
						
					}.bind(this)
				}).send();
        });
    },
    activaFormTrabajo: function(){
        if ($('pestanas_trabaja')) {
            var TabbedPanels1 = new Spry.Widget.TabbedPanels("TabbedPanels1");
            
			setTimeout(function(){
				$('pestanas_trabaja').show();
			},1200);
			
            $('form1').addEvent("submit", function(e){
                e.preventDefault();
                if (Spry.Widget.Form.validate($('form1'))) {
                    this.send();
                   // $('grabar1').set("value", "Grabado").set("disabled", true);
                    TabbedPanels1.showPanel(1);
                    return false;
                }
                else {
                    return false;
                }
            });
            
            
            $('form2').addEvent("submit", function(e){
                e.preventDefault();
                if (Spry.Widget.Form.validate($('form2'))) {
                    this.send();
                   // $('grabar2').set("value", "Grabado").set("disabled", true);
                    TabbedPanels1.showPanel(2);
                    return false;
                }
                else {
                    return false;
                }
            });
			
			 $('form3').addEvent("submit", function(e){
                e.preventDefault();
                if (Spry.Widget.Form.validate($('form3'))) {
                    this.send();
                   // $('grabar2').set("value", "Grabado").set("disabled", true);
                    TabbedPanels1.showPanel(3);
                    return false;
                }
                else {
                    return false;
                }
            });
            
			
			
			
			
            /*$('form3').addEvent("submit", function(e){
              //  e.preventDefault();
                
              //  $('grabar3').set("value", "Grabado").set("disabled", 1);
              //  alert("Gracias por enviarnos tu informacion");
                return true;
            });
            */
			
           
			
			
			$('pestanaExperienciaLaboral').addEvent("click", function(e){
                var theForm1 = typeof form != 'object' ? document.getElementById('form1') : form;
                var ret1 = Spry.Widget.Form.validate(theForm1);
				
                if (!ret1) {  //alextab
                    alert("Debes completar el primer formulario primero");
                    setTimeout(function(){
                        TabbedPanels1.showPanel(0);
                    }, 100);
                }
				
				
				 //TabbedPanels1.showPanel(1);
            });
			
            
            $('pestanapreparacionAcademica').addEvent("click", function(){
                var theForm2 = typeof form != 'object' ? document.getElementById('form2') : form;
                var ret2 = Spry.Widget.Form.validate(theForm2);
				
                if (!ret2) { //alextab
                    if (Spry.Widget.Form.validate($('form1'))) {
                        alert("Debes completar el segundo formulario");
                        setTimeout(function(){
                            TabbedPanels1.showPanel(1);
                        }, 100);
                    }
                    else {
                        alert("Debes completar el primer formulario primero");
                        setTimeout(function(){
                            TabbedPanels1.showPanel(0);
                        }, 100);
                    }
                    
                }
				
				//TabbedPanels1.showPanel(2);
            });
			
			 $('pestanainfoadicional').addEvent("click", function(){
			 
                var theForm3 = typeof form != 'object' ? document.getElementById('form3') : form;
                var ret3 = Spry.Widget.Form.validate(theForm3);
				
                if (!ret3) { //alextab
                    if (Spry.Widget.Form.validate($('form2'))) {
                        alert("Debes completar el tercer formulario");
                        setTimeout(function(){
                            TabbedPanels1.showPanel(1);
                        }, 100);
                    }
                    else {
                        alert("Debes completar el primer formulario primero");
                        setTimeout(function(){
                            TabbedPanels1.showPanel(0);
                        }, 100);
                    }
                    
                }
			//	TabbedPanels1.showPanel(3);
            });
			
			
			
		
			
			
			
        }
    },
	msgEnviado:function(){
		 $('grabar3').set("value", "Grabado").set("disabled", 1);
         alert("Gracias por enviarnos tu curriculum");
		 setTimeout(function(){
			window.location.href='index.php';
			return false;
		 },3000)
	},
    NoCV: function(){
        $('msgError').set("html", "El Documento no es un archivo de Word v&aacute;lido");
    },
	eligeColor:function(i){
		$$('.colorElegido').removeClass('colorElegido');
		if(!$('liColor_'+i).hasClass("colorElegido")){
			$('liColor_'+i).addClass("colorElegido");
			if($(empresa_eleg)){
				$(empresa_eleg).removeClass("colorElegido");
			}
		empresa_eleg='liColor_'+i;
		}	
	},
	verPopupIluminacion:function(){$empty},
	animaHome:function(){
		if($('promoOferta')){		
			var Morph =$('promoOferta').get("morph");
			$('e-decor_ofertas').
			addEvents({
				"mouseenter":function(){
					$('enlaces_decorcenter').setStyle("z-index",4);
					Morph.start({
						"margin-top":0,
						"opacity":1
					});
				},
				"mouseleave":function(){
					Morph.start({
						"margin-top":200,
						"opacity":0
					}).chain(function(){
						$('enlaces_decorcenter').setStyle("z-index",0);
					});
				}
			});
			
		}
		
		setTimeout(function(){
			Morph.start({
						"margin-top":200,
						"opacity":0
					}).chain(function(){
						$('enlaces_decorcenter').setStyle("z-index",0);
					});
		},5000);
	},
	activaTips:function(id){
		if($('tips_decor')){
			var Map=new MapTips('tips_decor',{
				classCirculo:'circuloTip',
				ajax:true,
				url:'sec/tips.php?id='+id,
				efecct:true,
				effectDuration:1
				//transitionEfecct:'bounce:out'
			});
		/*
			tip1={numero:1,izquierda:100,arriba:100}
			tip2={numero:2,izquierda:350,arriba:200}
			tip3={numero:3,izquierda:450,arriba:10}
			
			Map.addTip(tip1);
			Map.addTip(tip2);
			Map.addTip(tip3);
		*/	
			
		}
	},
	remover:function(){
		Map.removeAll();
	},
	verMarcasxFicha:function(id){
		if ($('caja-productos')) {
            (id) ? $id = id : $id = 0;
            $('caja-productos').set("load", {
                onSuccess: function(){
                    $('caja-productos').escondeAjax();
                    //var Tips1 = new Tips('.Tips1');
                }
            }).muestraAjax();
            var tween = $('caja-productos').get('tween', {
                property: 'opacity',
                duration: 800
            });
            tween.start(0).chain(function(){
                $('caja-productos').load("sec/listaMarcasxFicha.php?f=" + $id);
                tween.start(1);
            });
            
        }
	},
	pagFichas:function(url){
		if ($('caja-productos')) {
            var tween = $('caja-productos').get('tween', {
                property: 'opacity'
            });
            tween.start(0).chain(function(){
                $('caja-productos').load(url);
            });
            $('caja-productos').set("load", {
                onSuccess: function(){
                    $('caja-productos').escondeAjax();
                    tween.start(1);
                }
            }).muestraAjax();
            
            
        }
	},
	verFichas:function(id){
		if ($('caja-productos')) {
            (id) ? $id = id : $id = 0;
            $('caja-productos').set("load", {
                onSuccess: function(){
                    $('caja-productos').escondeAjax();
                    //var Tips1 = new Tips('.Tips1');
                }
            }).muestraAjax();
            var tween = $('caja-productos').get('tween', {
                property: 'opacity',
                duration: 800
            });
            tween.start(0).chain(function(){
                $('caja-productos').load("sec/listaFichas.php?f=" + $id);
                tween.start(1);
            });
            
        }
	},
	filterCategories:function(id,tipo){
		box=$('formBusquedaFilter');
        if (box) {
            (id) ? $id = id : $id = 0;
			
            box.set("load", {
				onRequest:function(){
					box.html("<div style='position:relative;margin:0 auto;color:#666;padding:60px 0 0 0' align='center'>Cargando...</div>");
				},
                onSuccess: function(){
                
                }
            })
			
            var tween = box.get('tween', {
                property: 'opacity',
                duration: 800
            });
			
			if(tipo=="categoria"){
				box.load("sec/boxFind_categoria.php?c="+id+"&tipo="+tipo);
			}else{
				box.load("sec/boxFind.php?c=" + id+"&tipo="+tipo);
			}
        }
		
	},
	filterTypes:function(val,type){
		
		var vals=$('foromBusqueda').toQueryString();
		
		
		
		if(val==0){
			//alert("Debes elegir para poder ver los resultados");
			return false;
		}
		
		//($('tiposBusqueda').val()!="")?subc=$('tiposBusqueda').val():subc="0";
		
		
		this.blankLists(type);
		
		new Request.JSON({
			url:"sec/listFilters.php",
			onSuccess:function(e){
			
				$(type).html("<option value='0'>"+$(type).get("data")+"</option>");
				e.each(function(k){
					new Element('option',{
						'value':k.id,
						'html':k.nombre
					}).inject($(type));
				});
				
				switch(type){
					//case 'tipos':this.verProductos(val);break;
					//case 'marcas':this.verMarcas(val);break;
					//case 'productos':this.verProductosFinal(val);break;
					//case 'results1': this.viewResults(val)
					
				}
				
			}.bind(this)
			
		}).send("id="+val+"&type="+type); //.send("id="+val+"&type="+type+"&categ="+$('cBusqueda').val()+"&sub="+subc);
		
		
		
		//.send(vals);
		
		
		switch(type){
			/*case 'tipos':this.verProductos(val);break;
			case 'marcas':this.verMarcas(val);break;
			case 'productos':this.verProductosFinal(val);break;
			case 'results1': this.viewResults(val);break;
			*/
			
			//case 'tipos':this.listResults(val,vals);break;
			//case 'marcas':this.listResults(val,vals);break;
			//case 'productos':this.listResults(val,vals);break;
			//case 'results1': this.listResults(val,vals);break;
			
		}
		
		
		
		//.send("id="+val+"&type="+type+"&categ="+$('cBusqueda').val()+"&sub="+subc);
		
	},
	listResults:function(id,list){
	
		if($('caja-productos')){
			box=$('caja-productos');
		}
		if($('cabecera_decorcenter')){
			box=$('cabecera_decorcenter');
			this.slideshow.stop();
		}
	
        if (box) {
		
            (id) ? $id = id : $id = 0;
			
            box.set("load", {
                onSuccess: function(){
                    box.escondeAjax();
                    
                    //var Tips1 = new Tips('.Tips1');
                },
				data:list,
				method:"get"
            }).muestraAjax();
			
            var tween = box.get('tween', {
                property: 'opacity',
                duration: 800
            });
			
            tween.start(0).chain(function(){
                box.load("sec/listaResults.php?c=" + $id);
                tween.start(1);
            });
            
        }
	},
	viewFilters:function(id,tipo){
	
		var vals=$('foromBusqueda').toQueryString();
	
		if($('caja_prod_detalles')){
			box=$('caja_prod_detalles');
		}
		if($('cabecera_decorcenter')){
			box=$('cabecera_decorcenter');
			this.slideshow.stop();
		}
        if (box) {
            (id) ? $id = id : $id = 0;
            box.set("load", {
                onSuccess: function(){
                   box.escondeAjax();
                }
            }).muestraAjax();
			
            var tween = box.get('tween', {
                property: 'opacity',
                duration: 800
            });
			
            tween.start(0).chain(function(){
				switch(tipo){
					case 'format':
						//box.load("sec/listaResultadosFormatos.php?f=" + $id);
						this.listResults(id,vals);
					break;
					case 'acabado':
						//box.load("sec/listaResultadosAcabados.php?f=" + encodeURIComponent($id));
						this.listResults(encodeURIComponent($id),vals);
					break;
					case 'color':
						//box.load("sec/listaResultadosColores.php?f=" + encodeURIComponent($id));
						this.listResults(encodeURIComponent($id),vals);
					break;
					
					case 'mark':
						//box.load("sec/listaResultadosMarca.php?f=" + encodeURIComponent($id));
						this.listResults(encodeURIComponent($id),vals);
					break;
				}
                
                tween.start(1);
            }.bind(this));
            
        }
	},
	viewResults:function(id){
		if($('caja-productos')){
			box=$('caja-productos');
		}
		if($('cabecera_decorcenter')){
			box=$('cabecera_decorcenter');
			this.slideshow.stop();
		}
		
		box.set("load", {
            onSuccess: function(){
                box.escondeAjax();
                   //var Tips1 = new Tips('.Tips1');
            }
        }).muestraAjax();
		
		subCat=$('tiposBusqueda').val();
		
		switch($('cBusqueda').val()){
			case "2":
				box.load("resultados2.php?id="+id);
			break;
			case "3":
				box.load("resultados2.php?id="+id);
			break;
			case "6":
				if(subCat==26 || subCat==27 ){
					box.load("resultados1.php?id="+id);
				}else{
					box.load("resultados2.php?id="+id);
				}
			break;
			case "8":
				box.load("resultados2.php?id="+id);
			break;
			
			default:
				box.load("resultados1.php?id="+id);
			break;
		}
		
		
	},
	blankLists:function(type){
		t=$$('.'+type);
		t.each(function(e){
			//e.html("<option value='0'>"+e.get("title")+"</option>");
		});
		
	},
	verResultados: function(key){
        if ($('caja_prod_detalles')) {
            (key) ? key= key : key = 0;
            $('caja_prod_detalles').set("load", {
                onSuccess: function(){
                    $('caja_prod_detalles').escondeAjax();
                }
            }).muestraAjax();
            var tween = $('caja_prod_detalles').get('tween', {
                property: 'opacity',
                duration: 800
            });
            tween.start(0).chain(function(){
                $('caja_prod_detalles').load("sec/listaResultados.php?q="+key+"&t="+$('criterioBusqueda').get("value"));
                tween.start(1);
            });
            
        }
    },
	sentToFriend:function(type,id){
	
		if(!$('bxSD')){
		
			var send= new Element("div",{
				styles:{
					position:'relative',
					width:500,
					height : 120,
					visibility:'hidden'
				},
				id:'bxSD',
				'class':'boxEmail'
			}).inject($('caja_detalles'));
			
			
			var closeBox= new Element("div",{
				styles:{
					height:15,
					width:15,
					position:'relative',
					top:5,
					'float':'right',
					cursor :'pointer'
				},
				html:"X",
				title:'cerrar',
				'class':'closeBoxEmail'
			}).inject(send);
			closeBox.
			addEvent("click",function(){
				$('bxSD').fade("out");
			});
			
			var Contenido=new Element("div",function(){
				styles:{
					padding:5
				}
			}).inject(send);
			
			formHtml='<div style="padding:10px"><h3 align="left">Enviar a Amigo</h3><form name="" id="frmSend" action="sec/envioAmigo.php">'+
					 '<input type="text"  onblur="if(this.value==\'\') this.value=\'Tu Nombre\'" onfocus="if(this.value==\'Tu Nombre\') this.value=\'\'" name="txtTuNombre" id="txtTuNombre" value="Tu Nombre" >'+
					 '<input type="text"  onblur="if(this.value==\'\') this.value=\'Nombre Amigo\'" onfocus="if(this.value==\'Nombre Amigo\') this.value=\'\'" name="nombreDeAmigo" id="nombreDeAmigo" value="Nombre Amigo" >'+
					 '<input type="text"  onblur="if(this.value==\'\') this.value=\'Email Amigo\'" onfocus="if(this.value==\'Email Amigo\') this.value=\'\'"  name="emailDeAmigo" id="emailDeAmigo" value="Email Amigo" >'+
					 '<input type="hidden" name="tipo" id="tipo" value="'+type+'" >'+
					 '<input type="hidden" name="id" id="lksend" value="'+id+'" >'+
					 '<input type="submit" name="emailDeAmigo" id="emailDeAmigo" value="Enviar" >'+
					 '</form></div><div id="msgSendEmail" style="width:350px"></div>';
					 
			Contenido.set("html",formHtml);
			
			
			
			$('frmSend').set("send",{
				onSuccess:function(res){
					$('msgSendEmail').set("html","Email enviado.Gracias");
					setTimeout(function(){
						$('bxSD').fade("out");
						$('txtTuNombre').set("value","Tu Nombre");
						$('nombreDeAmigo').set("value","Nombre Amigo");
						$('emailDeAmigo').set("value","Email Amigo");
						$('msgSendEmail').set("html","");
						
					},800);
					
				},
				noCache:true,
				method:"get"
			});
			
			$('frmSend').
			addEvent("submit",function(e){
				e.stop();
				
				emailNuevo=$('emailDeAmigo').get("value");
				
				//if (/^w+([.-]?w+)*@w+([.-]?w+)*(.w{2,3})+$/.test(emailNuevo)){
				if (emailNuevo.indexOf("@")==-1){
					alert("Debes llenar los campos correctamente");
					return false;
					
				}else{
					this.send();
					return true;
				}
				
			});
			
			
		}
		
		
		$('bxSD').fade("in");
	}
});



var MapTips=new Class({
	Implements: [Options, Events],
	container:'',
	options:{
		ancho:'',
		alto:'',
		cursor:'',
		classCirculo:'',
		ajax:false,
		url:'',
		efecct:false,
		effectDuration:1.8,
		transitionEfecct:'linear',
		opacityDuration:1.5,
		opacityImage:1
	},
	_panorama:'',
	_tip:'',
	initialize:function(container,options){
		this.setOptions(options);
		this.container=$(container);
		
		this.container.setStyle("overflow","hidden");
		
		this.container.getElement("img").set("tween",{duration:this.options.opacityDuration*1000});
		
	
		if(this.options.ajax){
			_url=this.options.url;
			new Request.JSON({
				url:_url,
				onSuccess:function(tips){
					this.container.getElement("img").tween("opacity",this.options.opacityImage);
					tips.each(function(e){
						this.addTip(e);
					}.bind(this));
				}.bind(this)
			}).send();
		}
	},
	addTip:function(_obj){
		_temp=new Element('div',{
			styles:{
				left:_obj._left.toInt(),
				top:_obj._top.toInt(),
				position: 'absolute',
				display:'none'
			},
			'class':this.options.classCirculo + " mapstipsClass",
			html:_obj.numero
		});
		
		var Area=this.container;
		
		if(this.options.efecct){
			this.container.grab(_temp);
			$coords=this.container.getCoordinates();
			_temp.set("morph",{
				duration:this.options.effectDuration*1000,
				"onStart":function(){
					_temp.setStyles({
						left:$coords.left,
						top:$coords.top
					}).show();
				},
				"transition":this.options.transitionEfecct,
				"onComplete":function(){
					new ATips(this,{
						previus:true,
						previusClass:'previoTip',
						closeClass:'closeTip',
						tipClass:'tip',
						hookClass:'hook',
						html:_obj.contenido,
						scrollSpecial:true,
						limita:true,
						limitArea:Area,
						offsetX : 25,
						offsetY : 25,
						previusText :"Click para ver Tip"
					});	
				}.bind(_temp)
			})
			.morph({
				left:[$coords.left,_obj._left.toInt()],
				top:[$coords.top,_obj._top.toInt()]
			});
			
		}else{
			_temp.show();
			this.container.grab(_temp);
			new ATips(_temp,{
				previus:true,
				previusClass:'previoTip',
				closeClass:'closeTip',
				tipClass:'tip',
				hookClass:'hook',
				html:_obj.contenido,
				scrollSpecial:true
			});	
		}
		
		
			
		
		
		
	},
	removeAll:function(){
		$$('.mapstipsClass')
		.fade("out").chain(function(){
			this.destroy();
		});
	}
});


var ATips= new Class({
	Implements:[Options,Events],
	options:{
		previus:false,
		previusClass:'',
		previusText:'Click para ver',
		anchoTip:330,
		altoTip:168,
		closeClass:'',
		tipClass:'',
		offsetX:0,
		offsetY:0,
		viewPortInside:false,
		hook:'',
		hookClass:'',
		html:'',
		scrollSpecial:false,
		limita:false,
		limitArea:''
	},
	container:'',
	_tip:'',
	_hook:'',
	_contTip:'',
	_close:'',
	_coors:'',
	_previus:'',
	_open:false,
	onShow:$empty(),
	onHide:$empty(),
	_limits:'',
	_left:false,
	_right:false,
	_top:false,
	_down:false,
	_normal:false,
	initialize:function(container,options){
		this.setOptions(options);
		($type(container=="object"))? this.container=container:this.container=$(container);
		this._coors=this.container.getCoordinates();
		this.container.setStyles({"cursor":"pointer"});
		
		this._tip=new Element("div",{
			styles:{
				position:'absolute',
				height:this.options.altoTip,
				width:this.options.anchoTip,
				left:((this._coors.left) + (this._coors.width)).toInt() - this.options.offsetX,
				top:((this._coors.top) + (this._coors.height)).toInt() - this.options.offsetY,
				visibility:'hidden',
				zIndex:500
			}
		});
		
		
		this._hook= new Element("div",{
			styles:{
				position:'relative',
				left:0
				//top:0
			},
			'class':this.options.hookClass
		}).injectInside(this._tip);
		
		
		this._contTip=new Element("div",{
			styles:{
				position:'relative',
				height:this.options.altoTip,
				width:this.options.anchoTip,
				left:0,
				top:0,
				zIndex:500
			},
			'class':this.options.tipClass +' AtipClass'
		}).injectInside(this._tip);
		
		this._close=new Element("span",{
			styles:{
				'float':'right',
				position:'relative',
				cursor:'pointer',
				display :'inline-block'
			},
			'class':this.options.closeClass
		}).injectInside(this._contTip).addEvent("click",this.hide.bind(this));
		
		
		
		new Element("div",{
			styles:{
				clear:'both',
				height:this.options.altoTip - 50,
				width:this.options.anchoTip - 30,
				margin:'0 auto',
				overflow:'auto'
			},
			'class':'scrolll',
			html:this._nl2br(this.options.html)
		}).injectInside(this._contTip);

		if(this.options.previus){
			this.container.addEvents({
				"mouseenter":function(){
					this.showPrevius();
				}.bind(this),
				"mouseleave":function(){
					this.hidePrevius();
				}.bind(this),
				"click":function(e){
					e.stop();
					this.show();
				}.bind(this)
			});
			
			
			this._previus=new Element("div",{
				styles:{
					position:'absolute',
					border:'1px solid #000',
					width:'auto',
					left:((this._coors.left) + (this._coors.width)).toInt(),
					top:this._coors.top,
					visibility:'hidden',
					zIndex:500
				},
				'class':this.options.previusClass,
				html:this.options.previusText
			});
			
			$$('body').grab(this._previus);
		}
		
		$$('body').grab(this._tip);
	
		if(this.options.limita){
			($type(this.options.limitArea=="object"))? this._limits=this.options.limitArea:this._limits=$(this.options.limitArea);
				$coorTip=this._limits.getCoordinates();
				var espacioTip=this._tip.getCoordinates();
				
				if($coorTip.top+$coorTip.height < espacioTip.top+espacioTip.height){
						this._tip.setStyles({
							top:espacioTip.top -espacioTip.height - this.options.offsetY
						});
					this._down=true;
					
				}
				
				
				if($coorTip.left+$coorTip.width < espacioTip.left+espacioTip.width){
					this._tip.setStyles({
						left:espacioTip.left -espacioTip.width - this.options.offsetX
					});
					this._left=true;	
					this._right=true;
					
					if($coorTip.top+$coorTip.height < espacioTip.top+espacioTip.height){
						this._tip.setStyles({
							top:espacioTip.top -espacioTip.height - this.options.offsetY
						});
						this._down=true;
					}
					
					
				}
				
				this._hookPosition();
		}
		
		
		if(this.options.scrollSpecial){
			//maldito jQuery
			$el=this._contTip.get("id");
			jQuery('.scrolll').jScrollPane({
				showArrows:true
			});
			
			if(Browser.Engine.trident){ //maldito explorer
				jQuery('.jScrollPaneContainer').css({"top":"5px","width":"300px","height":"120px"});
			}else{
				jQuery('.jScrollPaneContainer').css({"top":"22px","width":"300px","height":"120px"});
			}
			
		}
		
		
	},
	_hookPosition:function(){
		if(!this._down){
			return false;
		}
		var _newHook= this._hook.clone();
		this._hook.destroy();
		

		if(this._left){
			_newHook.setStyles({"background-position":"-40px 0px","top":"-2px","margin":"0 0 0 300px"});
			this._tip.setStyles({"left":this._tip.getStyle("left").toInt() + this.options.offsetX});
		}else if(this._right){
			_newHook.setStyles({"background-position":"-31px 0px","top":"-2px"});
		}else {
			_newHook.setStyles({"background-position":"-61px -0px","top":"-2px"});
		}
		
		this._tip.grab(_newHook);
	},
	_nl2br:function(str, is_xhtml) {
       var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
	   return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1'+ breakTag +'$2');
	},
	showPrevius:function(){
		if(this.options.previus){
			if(!this._open){
				this._previus.fade("in");
			}
		}
	},
	hidePrevius:function(){
		if(this.options.previus){
			this._previus.fade("out");	
		}
	},
	show:function(){
		this.closeAll();
		this.hidePrevius();
		this._tip.fade("in").addClass("activeATip");
		this._open=true;
		this.fireEvent("show");
	},
	hide:function(){
		this._tip.fade("out").removeClass("activeATip");
		this._open=false;
		this.fireEvent("hide");
	},
	closeAll:function(){
		$$('.activeATip').fade("out");
	},
	_mover:function(){
		this._tip.morph({
			left:[this._tip.getStyle("left").toInt(),((this._coors.left) + (this._coors.width)).toInt() - this.options.offsetX],
			top:[((this._coors.top) + (this._coors.height)).toInt() - this.options.offsetY]
		});
	}
});




var Ventana = new Class({
    Implements: [Options, Events],
    options: {
        modal: false,
        ancho: 350,
        titulo: '',
        alto: 350,
        id: "VentanaMoo",
        fondo: "white",
        fondoModal: "#000",
        opacidad: 0.2,
        html: "",
        url: "",
        arrastra: false,
        juntoA: "",
        separacion: 10,
        borde: 1,
        btnCerrar: "",
        imagenFondo: "",
        colorfondoCabecera: "",
        colorBorde: "",
        textoCerrar: "",
        anchoPrivado: 35,
        htmlCerrar: "",
        estiloCabecera: "",
        onCerrar: $empty(),
        onLoad: $empty()
    },
    initialize: function(options){
        this.setOptions(options);
        av = window.getWidth() / 2;
        alv = window.getHeight() / 2;
        ad = this.options.ancho / 2;
        ald = this.options.alto / 2;
        ventana = new Element("div", {
            id: this.options.id,
            styles: {
                backgroundColor: this.options.fondo,
                padding: this.options.separacion + 'px',
                height: this.options.alto + 'px',
                width: this.options.ancho + 'px',
                position: 'absolute',
                border: this.options.borde + 'px solid #CCC',
                left: parseInt(av) - parseInt(ad),
                top: parseInt(alv) - parseInt(ald),
                zIndex: 1200,
                display: 'none'
            }
        
        });
        
        if (!$(this.options.juntoA)) {
            ventana.set('html', '<div id="header__moo" class="cabecera__moo" style="padding:10px;height:15px" >' +
            '<div style="width:85%;float:left;">' +
            this.options.titulo +
            '</div>' +
            '<div align="right" id="cierra_v_moo" style="float:left;width:15%;cursor:pointer;" title=""></div>' +
            '</div>' +
            '<div style="border-top:0px solid #CCC;padding:35px;height:' +
            parseInt(this.options.alto - 25) +
            'px;overflow:auto;vertical-align:middle" align="center" id="conte__moo" class="cuerpo__moo">' +
            '</div>');
            
        }
        else {
            ventana.set('html', '<div style="border-top:0px solid #CCC;height:' + parseInt(this.options.alto) +
            'px;overflow:auto;vertical-align:middle" align="center" id="conte__moo" class="cuerpo__moo">' +
            '</div>');
        }
        
    },
    render: function(){
        if (!this.options.modal) {
            $$('select').setStyle("visibility", "hidden");
            $$('body').grab(ventana);
            
            if (!$(this.options.juntoA)) {
                $('cierra_v_moo').addEvent('click', this.cerrar.bind(this));
            }
            
            if (this.options.url == "") {
                $('conte__moo').set('html', this.options.html);
            }
            else {
                $('conte__moo').set("load", {
                    evalScripts: true,
                    evalResponse: true,
                    onSuccess: function(){
                        this.fireEvent('load');
                    }.bind(this)
                });
                $('conte__moo').load(this.options.url);
            }
            
        }
        else {
            var modal = new Element('div', {
                id: "VentanaMooModal",
                styles: {
                    backgroundColor: this.options.fondoModal,
                    opacity: this.options.opacidad,
                    height: window.getScrollHeight(),
                    width: window.getScrollWidth(),
                    zIndex: 1009,
                    position: 'absolute',
                    top: '0px',
                    left: '0px',
                    visibility: 'hidden'
                }
            });
            $$('select').setStyle("visibility", "hidden");
            $$('body').grab(modal);
            modal.tween("opacity", [0, this.options.opacidad]);
            //modal.fadeTo(this.options.opacidad);
            $$('body').grab(ventana);
            
            if (this.options.separacion == 0) {
                $('conte__moo').setStyle("padding", "0px");
            }
            
            if (this.options.htmlCerrar != "") {
                $('cierra_v_moo').set("html", this.options.htmlCerrar);
            }
            if (this.options.colorBorde != "") {
                ventana.setStyles({
                    "border-color": this.options.colorBorde
                });
            }
            if (this.options.estiloCabecera != "") {
                $('header__moo').addClass(this.options.estiloCabecera);
            }
            if (this.options.imagenFondo != "") {
                $('conte__moo').setStyle("background-image", "url(" + this.options.imagenFondo + ")");
                $('conte__moo').setStyle("background-repeat", "repeat-x");
            }
            
            this.posicionar();
            if (this.options.url == "") {
                $('conte__moo').set('html', this.options.html);
            }
            else {
                try {
                    $('conte__moo').set('load', {
                        'evalResponse': true,
                        'onSuccess': function(){
                            if ($(this.options.btnCerrar) && this.options.url) {
                                $(this.options.btnCerrar).addEvent('click', this.cerrar.bind(this)).setStyle("cursor", "pointer").set("title", "");
                            }
                            else {
                                $('cierra_v_moo').addEvent('click', this.cerrar.bind(this));
                            }
                            this.fireEvent('load');
                        }.bind(this)
                    });
                    
                } 
                catch (err) {
                    txt = "There was an error on this page.\n\n";
                    txt += "Error description: " + err.description + "\n\n";
                    txt += "Click OK to continue.\n\n";
                    alert(txt);
                }
                
                $('conte__moo').load(this.options.url);
            }
        }
        
        if (this.options.arrastra == "si") {
            if ($('header__moo')) {
                $('header__moo').setStyle("cursor", "move");
                $(ventana).makeDraggable({
                    handle: 'header__moo'/*,container:document.body*/
                });
            }
            
        }
        
        document.addEvents({
            'keypress': function(e){
                if (e.key == 'esc') {
                    if ($('conte__moo')) {
                        this.cerrar();
                    }
                }
            }.bind(this)
        });
        window.addEvents({
            'resize': function(){
                if ($('conte__moo')) {
                    //	$('VentanaMooModal').morph({"width":window.getScrollWidth(),"height":window.getScrollHeight()});
                    this.posicionar();
                }
                
            }.bind(this)            ,
            "scroll": function(){
                if ($('conte__moo')) {
                    //$('VentanaMooModal').morph({"width":window.getScrollWidth(),"height":window.getScrollHeight()});
                    this.posicionar();
                }
            }.bind(this)
        });
        
        if ($('VentanaMooModal')) {
            $('VentanaMooModal').addEvent("click", function(){
                if ($('conte__moo')) {
                    this.cerrar();
                }
            }.bind(this));
            
        }
        
        
        
        
        var pos = window.getHeight();
        var posAncho = window.getWidth();
        sizes = window.getSize();
        scrollito = window.getScroll();
        
        
        ventana.setStyles({
            //top:0 + defaz.toInt()  
            'top': (scrollito.y + (sizes.y - this.options.alto) / 2).toInt()
        });
        
        
    },
    cerrar: function(){
        //window.removeEvent('keypress',function(e){});
        $$('select').setStyle("visibility", "visible");
        $('VentanaMooModal').set("tween", {
            duration: 500,
            onComplete: function(){
                $('VentanaMooModal').destroy();
            }
        });
        if ($(this.options.id)) {
            $(this.options.id).destroy();
        }
        $('VentanaMooModal').tween("opacity", [this.options.opacidad, 0])
        
        $$('select').setStyle("visibility", "visible");
        this.fireEvent('cerrar');
    },
    load: function(){
    },
    posicionar: function(){
        var scrollventana = new Fx.Scroll(window, {
            wait: false,
            duration: 800,
            transition: Fx.Transitions.Sine.easeInOut
        });
        if ($(this.options.juntoA != "")) {
            var pos = $(this.options.juntoA).getCoordinates();
            scrollventana.toElement($(this.options.juntoA).getParent());
            try {
                ventana.set('morph', {
                    duration: 800,
                    transition: 'quad:out',
                    onComplete: function(){
                        //$('VentanaMooModal').setStyles({"width","100","height":"100"})
                    }
                }).setStyle("left", pos.left - (this.options.ancho / 2).toInt());
                ventana.morph({
                    opacity: [0.5, 1],
                    top: pos.top - (this.options.alto).toInt() - 30
                });
            } 
            catch (err) {
                txt = "There was an error on this page.\n\n";
                txt += "Error description: " + err.description + "\n\n";
                txt += "Click OK to continue.\n\n";
                alert(txt);
            }
            
            
        }
        else {
            var pos = window.getHeight();
            var posAncho = window.getWidth();
            sizes = window.getSize();
            scrollito = window.getScroll();
            //ventana.setStyles({"top":0,"display":"none"});
            /*
             ventana.setStyles({
             //top:0 + defaz.toInt()
             'top': (scrollito.y + (sizes.y - this.options.alto) / 2).toInt()
             });
             */
            try {
                //$('VentanaMooModal').morph({"width":window.getScrollWidth(),"height":window.getScrollHeight()});
                //ventana.setStyles({'top': (scrollito.y + (sizes.y - this.options.alto) / 2).toInt()});
                ventana.set('morph', {
                    duration: 500,
                    transition: 'sine:in:out',
                    onComplete: function(){
                        //scrollventana.toElement($('conte__moo'));
                        ventana.setStyles({
                            "display": "block"
                        });
                    }
                }).morph({                    /*'top': (scrollito.y + (sizes.y - this.options.alto) / 2).toInt(),
                     "left":posAncho / 2 - (this.options.ancho / 2).toInt()
                     */
                });
                $('cierra_v_moo').addEvent('click', this.cerrar.bind(this));
                
                
            } 
            catch (err) {
                txt = "There was an error on this page.\n\n";
                txt += "Error description: " + err.description + "\n\n";
                txt += "Click OK to continue.\n\n";
                alert(txt);
            }
            
        }
    }
});

function Alertas(msg, w){
    if (!w) {
        $ancho = 300;
    }
    else {
        $ancho = w;
    }
    
    
    new Ventana({
        id: "ventana_1_registroooo",
        titulo: 'www.decor-center.com',
        modal: true,
        html: "<div class='contenidoVentana'>" + msg + "</div>",
        ancho: $ancho,
        alto: 120,
        arrastra: "si",
        fondo: "#FFF",
        estiloCabecera: "fondocabecera",
        separacion: 0,
        colorBorde: "#ccc",
        htmlCerrar: "X",
        borde: 3
    }).render();
}

var Tooltips = new Class({
    Implements: Options,
    options: {
        objeto: "moo__tip",
        clase: "mootips",
        ancho: 250,
        alto: 150,
        fondo: "",
        html: "",
        div: "moo",
        posicion: "arriba",
        estiloInterior: "",
        evento: "over",
        bntCerrar: "",
        colorFondo: "",
        borde: "",
        forzarCierre: true,
        aliner: "",
        opacidad: 1,
        cerrarTodos: true,
		top:'',
		left:''
    },
    initialize: function(options){
        this.setOptions(options);
        this.cerrar();
        if (this.options.evento == "over") {
            this.bntCerrar = "";
        }
        
        
        moo___tip = new Element("div", {
            id: 'moo_tip__' + this.options.div,
            styles: {
                backgroundImage: 'url(' + this.options.fondo + ')',
                backgroundRepeat: 'no-repeat',
                border: '0px solid blue',
                width: this.options.ancho + 'px',
                height: this.options.alto + 'px',
                position: 'absolute',
                visibility: 'hidden',
                padding: '0px',
                zIndex: 1500
            },
            'class': 'moot_tipo_alex',
            html: '<div align="right" style="padding-right:10px;margin-top:2px;float:right"  id="cierraTip__' + this.options.div + '">' + this.options.bntCerrar + '</div><div style="padding:10px">' +
            '<div class="' +this.options.estiloInterior +'">' +this.options.html +'</div></div>'
        });
        if (this.options.fondo != "") {
            //	 $('moo_tip__').setStyle("border","0");
        }
        
        if (this.options.colorFondo != "") {
            moo___tip.setStyle("background-color", this.options.colorFondo);
        }
        
        if (this.options.borde != "") {
            moo___tip.setStyle("border", this.options.borde);
        }
        moo___tip.setStyle("top", "0px");
        
        moo___tip.setOpacity(this.options.opacidad);
        
        if (!$('moo_tip__' + this.options.div)) {
            $$('body').grab(moo___tip);
        }
        
        
        moo___tip.PNG();
        $(this.options.div).addEvents({
            "mouseenter": function(e){
                e.stop();
                if (this.options.evento == "over") {
                    this.mostrar();
                }
                
                
            }.bind(this)            ,
            "mouseleave": function(){
                if (this.options.evento == "over" || this.options.forzarCierre == false) {
                    this.cerrar();
                }
            }.bind(this)            ,
            "click": function(e){
                e.stop();
                if (this.options.evento == "click") {
                    this.mostrar();
                }
            }.bind(this)
        }).setStyle('cursor', 'pointer');
        
        $('cierraTip__' + this.options.div).addEvent("click", function(){
            this.cerrar();
        }.bind(this)).setStyle("cursor", "pointer");
        
        //this.iniciar();
        
        document.addEvent("click", function(){
            if (moo___tip) {
                //this.cerrar();
            }
        }.bind(this));
        
        
    },
    iniciar: function(){
    
    
    },
    mostrar: function(){
        
            $$('.moot_tipo_alex').hide();
        
        
        pos = $(this.options.div).getCoordinates();
        if (this.options.alinear != "") {
            switch (this.options.alinear) {
                case "izquierda":
                    miizquierdaarriba = (pos.left).toInt();
                    miizquierdaabajo = (pos.left).toInt();
                    break;
                default:
                    miizquierdaarriba = (pos.left).toInt() - (this.options.ancho / 2);
                    miizquierdaabajo = (pos.left).toInt() - ((this.options.ancho - pos.width) / 2).toInt();
            }
            
        }
        switch (this.options.posicion) {
            case "arriba":
                $('moo_tip__' + this.options.div).setStyles({
                    'left': miizquierdaarriba,
                    'top': (pos.top) - this.options.alto - 10
                }).morph({
                    'top': [$('moo_tip__' + this.options.div).getStyle("top"), (pos.top).toInt() - this.options.alto]
                });
                break;
                
            case "abajo":
                $('moo_tip__' + this.options.div).setStyle('left', miizquierdaabajo).morph({
                    'top': [(pos.top).toInt() + pos.height + 10, (pos.top).toInt() + pos.height]
                });
                break;
            case "centroArriba":
                $('moo_tip__' + this.options.div).setStyle('left', miizquierdaarriba + $(this.options.div).getStyle("width").toInt() / 2).morph({
                    'top': [(pos.top - this.options.alto) - 20, (pos.top).toInt() - this.options.alto]
                });
            break;
			
			case "personalizado":
                $('moo_tip__' + this.options.div)
				.setStyle('left', this.options.left).morph({
                    'top': this.options.top
                });
            break;
        }
        $('moo_tip__' + this.options.div).show();
        //$('moo_tip__'+this.options.div).fadeTo(this.options.opacidad);
    },
    cerrar: function(){
        if ($('moo_tip__' + this.options.div)) {
            $('moo_tip__' + this.options.div).hide();
            //$('moo_tip__'+this.options.div).destroy();
        }
    }
});
var Hints = new Class({
    Implements: Options,
    options: {
        campo: "",
        texto: ""
    },
    initialize: function(options){
        this.setOptions(options);
        $(this.options.campo).set("value", this.options.texto);
        $(this.options.campo).set("autocomplete", "off").addEvents({
            "focus": function(){
                atext = $(this.options.campo).get("value");
                if (atext == this.options.texto || atext == "") {
                    $(this.options.campo).set("value", "");
                }
            }.bind(this)            ,
            "blur": function(){
                atext = $(this.options.campo).get("value");
                if (atext == this.options.texto || atext == "") {
                    $(this.options.campo).set("value", this.options.texto);
                }
            }.bind(this)
        });
    }
});

var ASlide = new Class({
    options: {
        showControls: false,
        showDuration: 5000,
        showTOC: false,
        tocWidth: 20,
        tocClass: 'toc',
        tocActiveClass: 'toc-active'
    },
    Implements: [Options, Events],
    initialize: function(container, elements, options){
        //settings
        this.container = $(container);
        this.elements = $$(elements);
        this.currentIndex = 0;
        this.interval = '';
        if (this.options.showTOC) 
            this.toc = [];
        
        //assign
        this.elements.each(function(el, i){
           // var capa = new Element('div', {});
            //capa.inject(this.container);
            if (this.options.showTOC) {
                this.toc.push(new Element('a', {
                    text: i + 1,
                    href: '#',
                    'class': this.options.tocClass + '' + (i == 0 ? ' ' + this.options.tocActiveClass : ''), //modificado para dulce
                    //'class': 'toc'+(i+1)+' ' + (i == 0 ? ' ' + 'toc'+(i+1)+'-active' : ''),
                    events: {
                        click: function(e){
                            if (e) 
                                e.stop();
                            this.stop();
                            this.show(i);
                        }.bind(this)
                    },
                    styles: {
                        left: 270 + ((i + 1) * (this.options.tocWidth + 70)) //mpodificado parsa dulce  < ((i + 1) * (this.options.tocWidth + 10)) >
                    }
                }).inject(this.container));
                //.inject(capa))
            }
            
            if (i > 0) 
                el.set('opacity', 0);
        }, this);
        
        //next,previous links
        if (this.options.showControls) {
            this.createControls();
            
        }
        //events
        this.container.addEvents({
            mouseenter: function(){
                this.stop();
            }.bind(this)            ,
            mouseleave: function(){
                this.start();
            }.bind(this)
        });
        
    },
    show: function(to){
        //alert(this.currentIndex+1);
        this.elements[this.currentIndex].fade('out');
        if (this.options.showTOC) 
            this.toc[this.currentIndex].removeClass(this.options.tocActiveClass);
        this.elements[this.currentIndex = ($defined(to) ? to : (this.currentIndex < this.elements.length - 1 ? this.currentIndex + 1 : 0))].fade('in');
        if (this.options.showTOC) 
            this.toc[this.currentIndex].addClass(this.options.tocActiveClass);
    },
    start: function(){
        this.interval = this.show.bind(this).periodical(this.options.showDuration);
    },
    stop: function(){
        $clear(this.interval);
    },
    //"private"
    createControls: function(){
        var next = new Element('a', {
            href: '#',
            id: 'next',
            text: '>>',
            events: {
                click: function(e){
                    if (e) 
                        e.stop();
                    this.stop();
                    this.show();
                }.bind(this)
            }
        }).inject(this.container);
        var previous = new Element('a', {
            href: '#',
            id: 'previous',
            text: '<<',
            events: {
                click: function(e){
                    if (e) 
                        e.stop();
                    this.stop();
                    this.show(this.currentIndex != 0 ? this.currentIndex - 1 : this.elements.length - 1);
                }.bind(this)
            }
        }).inject(this.container);
    }
});

/*require Slider*/
var AZoom = new Class({
    Implements: Options,
    options: {
        capaZoom: "",
        barraZoom: "",
        mas: "",
        menos: "",
        anchoImagen: "",
        altoImagen: "",
        limita: ""
    },
    imagen: "",
    clon: "",
    Zoomactual: "",
    slider: "",
    moverconRueda: "",
    imagenZoom: "",
    contenedor: "",
    tamanoInicial: "",
    initialize: function(imagen, options){
        this.setOptions(options);
        this.imagen = $(imagen);
        this.imagen.getParent().setStyle("overflow", "hidden");
        this.imagenZoom = new Asset.image(this.imagen.get("rel"));
        this.tamanoInicial = this.imagen.getCoordinates();
        this.imagen.setStyles({
            "top": 0,
            "left": 0,
            "cursor": "move"
        });
        if (this.options.limita != "") {
            this.contenedor = new Element("div", {}).injectBefore(this.imagen).adopt(this.imagen);
            anchoLimite = this.imagen.getParent().getStyle("width");
            altoLimite = this.imagen.getParent().getStyle("height");
            this.contenedor.setStyles({
                "width": anchoLimite,
                "height": altoLimite,
                "top": 0,
                "left": 0
            });
            this.imagen.makeDraggable({
                wait: true,
                container: this.contenedor,
                onDrag: function(){
                    if (Browser.Engine.trident) {
                        this.imagen.setStyle("cursor", "url(images/mano_cerrada.cur),move");
                    }
                    else {
                        this.imagen.setStyle("cursor", "url(images/mano_cerrada.cur),move");
                    }
                    
                }.bind(this)                ,
                onDrop: function(){
                    if (Browser.Engine.trident) {
                        this.imagen.setStyle("cursor", "url(images/mano.cur),move");
                    }
                    else {
                        this.imagen.setStyle("cursor", "url(images/mano.cur),move");
                    }
                    
                }.bind(this)
            });
        }
        else {
            this.imagen.makeDraggable({
                wait: true,
                onDrag: function(){
                    if (Browser.Engine.trident) {
                        this.setStyle("cursor", "url(images/mano_cerrada.cur),move");
                    }
                    else {
                        this.setStyle("cursor", "url(images/mano_cerrada.cur),move");
                    }
                    
                }
            });
        }
        
        
        el = $(this.options.capaZoom);
        this.slider = new Slider(el, el.getElement('div'), {
            steps: 20,
            range: [0, 100],
            wheel: true,
            onChange: function(value){
                todoActual = this.imagen.getCoordinates();
                if (value != 0) {
                    this.contenedor.set("align", "center");
                    if (todoActual.width < todoActual.height) {
                        this.imagen.set("morph", {
                            duration: 100
                        }).setStyles({
                            'margin-left': '-' + ((value * 1.9)) + 'px',
                            'margin-top': '-' + ((value) * 2.5) + 'px',
                            'width': (((value * 3.5) + this.options.anchoImagen)),
                            'height': ((((value * (5.2))) + this.options.altoImagen) - 3)
                        });
                        this.contenedor.setStyles({
                            'margin-left': -(todoActual.width - this.tamanoInicial.width),
                            'margin-top': -(todoActual.height - this.tamanoInicial.height),
                            'width': (2 * todoActual.width - this.tamanoInicial.width),
                            'height': (2 * todoActual.height - this.tamanoInicial.height)
                        });
                    }
                    else {
                    
                        this.imagen.set("morph", {
                            duration: 100
                        }).setStyles({
                            'margin-left': '-' + ((value * 1.9)) + 'px',
                            'margin-top': '-' + ((value) * 2.5) + 'px',
                            'width': (((value * 5.2) + this.options.anchoImagen)),
                            'height': ((((value * (3.5))) + this.options.altoImagen) - 3)
                        });
                        this.contenedor.setStyles({
                            'margin-left': -(todoActual.width - this.tamanoInicial.width),
                            'margin-top': -(todoActual.height - this.tamanoInicial.height),
                            'width': (2 * todoActual.width - this.tamanoInicial.width),
                            'height': (2 * todoActual.height - this.tamanoInicial.height)
                        });
                    }
                    this.Zoomactual = value;
                }
                else 
                    if (value == 0 || value == 5) {
                    
                        this.imagen.setStyles({
                            'margin-left': '0px',
                            'margin-top': '0px',
                            'width': this.anchoImagen,
                            'height': this.altoImagen,
                            'left': 0,
                            'top': 0
                        });
                        
                        this.contenedor.setStyles({
                            'margin-left': '0px',
                            'margin-top': '0px',
                            'width': this.imagen.getStyle("width"),
                            'height': this.imagen.getStyle("height"),
                            'left': 0,
                            'top': 0
                        });
                        this.Zoomactual = value;
                    }
                
                
            }
.bind(this)
        
        }).set(0);
        
        $(this.options.mas).addEvent("click", function(){
            this.aumentarZoom();
        }.bind(this)).setStyle("cursor", "pointer");
        $(this.options.menos).addEvent("click", function(){
            this.disminuirZoom();
        }.bind(this)).setStyle("cursor", "pointer");
        
        if (this.options.moverconRueda != "") {
            this.imagen.addEvent("mousewheel", function(e){
                var e = new Event(e).stop();
                if (e.wheel > 0) {
                    this.Zoomactual = this.Zoomactual + 5
                    this.slider.set(this.Zoomactual);
                }
                else {
                    this.Zoomactual = this.Zoomactual - 5
                    this.slider.set(this.Zoomactual);
                }
            }.bind(this));
        }
        
    },
    aumentarZoom: function(){
        this.Zoomactual = this.Zoomactual + 5
        this.slider.set(this.Zoomactual);
    },
    disminuirZoom: function(){
        this.Zoomactual = this.Zoomactual - 5
        this.slider.set(this.Zoomactual);
    },
    resetearZoom: function(){
        this.imagen.setStyles({
            'margin-left': '0px',
            'margin-top': '0px',
            'width': this.options.anchoImagen,
            'height': this.options.altoImagen,
            'left': 0,
            'top': 0
        });
        this.slider.set(0);
    }
});


/***slimbox**/

/*
 Slimbox v1.71 - The ultimate lightweight Lightbox clone
 (c) 2007-2009 Christophe Beyls <http://www.digitalia.be>
 MIT-style license.
 */
var Slimbox = (function(){
    var F = window, n = Browser.Engine.trident4, u, g, G = -1, o, w, E, v, y, M, s, m = {}, t = new Image(), K = new Image(), I, a, h, q, J, e, H, c, A, L, x, i, d, C;
    F.addEvent("domready", function(){
        $(document.body).adopt($$(I = new Element("div", {
            id: "lbOverlay",
            events: {
                click: D
            }
        }), a = new Element("div", {
            id: "lbCenter"
        }), H = new Element("div", {
            id: "lbBottomContainer"
        })).setStyle("display", "none"));
        h = new Element("div", {
            id: "lbImage"
        }).injectInside(a).adopt(q = new Element("div", {
            styles: {
                position: "relative"
            }
        }).adopt(J = new Element("a", {
            id: "lbPrevLink",
            href: "#",
            events: {
                click: B
            }
        }), e = new Element("a", {
            id: "lbNextLink",
            href: "#",
            events: {
                click: f
            }
        })));
        c = new Element("div", {
            id: "lbBottom"
        }).injectInside(H).adopt(new Element("a", {
            id: "lbCloseLink",
            href: "#",
            events: {
                click: D
            }
        }), A = new Element("div", {
            id: "lbCaption"
        }), L = new Element("div", {
            id: "lbNumber"
        }), new Element("div", {
            styles: {
                clear: "both"
            }
        }))
    });
    function z(){
        var N = F.getScroll(), O = F.getSize();
        $$(a, H).setStyle("left", N.x + (O.x / 2));
        if (v) {
            I.setStyles({
                left: N.x,
                top: N.y,
                width: O.x,
                height: O.y
            })
        }
    }
    function l(N){
        ["object", n ? "select" : "embed"].forEach(function(P){
            Array.forEach(document.getElementsByTagName(P), function(Q){
                if (N) {
                    Q._slimbox = Q.style.visibility
                }
                Q.style.visibility = N ? "hidden" : Q._slimbox
            })
        });
        I.style.display = N ? "" : "none";
        var O = N ? "addEvent" : "removeEvent";
        F[O]("scroll", z)[O]("resize", z);
        document[O]("keydown", p)
    }
    function p(O){
        var N = O.code;
        return u.closeKeys.contains(N) ? D() : u.nextKeys.contains(N) ? f() : u.previousKeys.contains(N) ? B() : false
    }
    function B(){
        return b(w)
    }
    function f(){
        return b(E)
    }
    function b(N){
        if (N >= 0) {
            G = N;
            o = g[N][0];
            w = (G || (u.loop ? g.length : 0)) - 1;
            E = ((G + 1) % g.length) || (u.loop ? 0 : -1);
            r();
            a.className = "lbLoading";
            m = new Image();
            m.onload = k;
            m.src = o
        }
        return false
    }
    function k(){
        a.className = "";
        d.set(0);
        h.setStyles({
            backgroundImage: "url(" + o + ")",
            display: ""
        });
        q.setStyle("width", m.width);
        $$(q, J, e).setStyle("height", m.height);
        A.set("html", g[G][1] || "");
		
		Cufon.set('fontFamily', 'DIN').replace('#lbCaption'); //modificado solo para decor
		Cufon.now();
		
        L.set("html", (((g.length > 1) && u.counterText) || "").replace(/{x}/, G + 1).replace(/{y}/, g.length));
        if (w >= 0) {
            t.src = g[w][0]
        }
        if (E >= 0) {
            K.src = g[E][0]
        }
        M = h.offsetWidth;
        s = h.offsetHeight;
        var P = Math.max(0, y - (s / 2)), N = 0, O;
        if (a.offsetHeight != s) {
            N = i.start({
                height: s,
                top: P
            })
        }
        if (a.offsetWidth != M) {
            N = i.start({
                width: M,
                marginLeft: -M / 2
            })
        }
        O = function(){
            H.setStyles({
                width: M,
                top: P + s,
                marginLeft: -M / 2,
                visibility: "hidden",
                display: ""
            });
            d.start(1)
        };
        if (N) {
            i.chain(O)
        }
        else {
            O()
        }
    }
    function j(){
        if (w >= 0) {
            J.style.display = ""
        }
        if (E >= 0) {
            e.style.display = ""
        }
        C.set(-c.offsetHeight).start(0);
        H.style.visibility = ""
    }
    function r(){
        m.onload = $empty;
        m.src = t.src = K.src = o;
        i.cancel();
        d.cancel();
        C.cancel();
        $$(J, e, h, H).setStyle("display", "none")
    }
    function D(){
        if (G >= 0) {
            r();
            G = w = E = -1;
            a.style.display = "none";
            x.cancel().chain(l).start(0)
        }
        return false
    }
    Element.implement({
        slimbox: function(N, O){
            $$(this).slimbox(N, O);
            return this
        }
    });
    Elements.implement({
        slimbox: function(N, Q, P){
            Q = Q ||
            function(R){
                return [R.href, R.title]
            };
            P = P ||
            function(){
                return true
            };
            var O = this;
            O.removeEvents("click").addEvent("click", function(){
                var R = O.filter(P, this);
                return Slimbox.open(R.map(Q), R.indexOf(this), N)
            });
            return O
        }
    });
    return {
        open: function(P, O, N){
            u = $extend({
                loop: false,
                overlayOpacity: 0.2,
                overlayFadeDuration: 400,
                resizeDuration: 400,
                resizeTransition: false,
                initialWidth: 250,
                initialHeight: 250,
                imageFadeDuration: 400,
                captionAnimationDuration: 400,
                counterText: "Image {x} of {y}",
                closeKeys: [27, 88, 67],
                previousKeys: [37, 80],
                nextKeys: [39, 78]
            }, N || {});
            x = new Fx.Tween(I, {
                property: "opacity",
                duration: u.overlayFadeDuration
            });
            i = new Fx.Morph(a, $extend({
                duration: u.resizeDuration,
                link: "chain"
            }, u.resizeTransition ? {
                transition: u.resizeTransition
            } : {}));
            d = new Fx.Tween(h, {
                property: "opacity",
                duration: u.imageFadeDuration,
                onComplete: j
            });
            C = new Fx.Tween(c, {
                property: "margin-top",
                duration: u.captionAnimationDuration
            });
            if (typeof P == "string") {
                P = [[P, O]];
                O = 0
            }
            y = F.getScrollTop() + (F.getHeight() / 2);
            M = u.initialWidth;
            s = u.initialHeight;
            a.setStyles({
                top: Math.max(0, y - (s / 2)),
                width: M,
                height: s,
                marginLeft: -M / 2,
                display: ""
            });
            v = n || (I.currentStyle && (I.currentStyle.position != "fixed"));
            if (v) {
                I.style.position = "absolute"
            }
            x.set(0).start(u.overlayOpacity);
            z();
            l(1);
            g = P;
            u.loop = u.loop && (g.length > 1);
            return b(O)
        }
    }
})();

// AUTOLOAD CODE BLOCK (MAY BE CHANGED OR REMOVED)
Slimbox.scanPage = function(){
    $$("a").filter(function(el){
        return el.rel && el.rel.test(/^lightbox/i);
    }).slimbox({/* Put custom options here */}, null, function(el){
        return (this == el) || ((this.rel.length > 8) && (this.rel == el.rel));
    });
};
if (!/android|iphone|ipod|series60|symbian|windows ce|blackberry/i.test(navigator.userAgent)) {
    window.addEvent("domready", Slimbox.scanPage);
}


/**mi consola**/
var dbug = {
    logged: [],
    timers: {},
    firebug: false,
    enabled: false,
    log: function(){
        dbug.logged.push(arguments);
    },
    nolog: function(msg){
        dbug.logged.push(arguments);
    },
    time: function(name){
        dbug.timers[name] = new Date().getTime();
    },
    timeEnd: function(name){
        if (dbug.timers[name]) {
            var end = new Date().getTime() - dbug.timers[name];
            dbug.timers[name] = false;
            dbug.log('%s: %s', name, end);
        }
        else 
            dbug.log('no such timer: %s', name);
    },
    enable: function(silent){
        var con = window.firebug ? firebug.d.console.cmd : window.console;
        
        if ((!!window.console && !!window.console.warn) || window.firebug) {
            try {
                dbug.enabled = true;
                dbug.log = function(){
                    try {
                        (con.debug || con.log).apply(con, arguments);
                    } 
                    catch (e) {
                        console.log(Array.slice(arguments));
                    }
                };
                dbug.time = function(){
                    con.time.apply(con, arguments);
                };
                dbug.timeEnd = function(){
                    con.timeEnd.apply(con, arguments);
                };
                if (!silent) 
                    dbug.log('enabling dbug');
                for (var i = 0; i < dbug.logged.length; i++) {
                    dbug.log.apply(con, dbug.logged[i]);
                }
                dbug.logged = [];
            } 
            catch (e) {
                dbug.enable.delay(400);
            }
        }
    },
    disable: function(){
        if (dbug.firebug) 
            dbug.enabled = false;
        dbug.log = dbug.nolog;
        dbug.time = function(){
        };
        dbug.timeEnd = function(){
        };
    },
    cookie: function(set){
        var value = document.cookie.match('(?:^|;)\\s*jsdebug=([^;]*)');
        var debugCookie = value ? unescape(value[1]) : false;
        if ((!$defined(set) && debugCookie != 'true') || ($defined(set) && set)) {
            dbug.enable();
            dbug.log('setting debugging cookie');
            var date = new Date();
            date.setTime(date.getTime() + (24 * 60 * 60 * 1000));
            document.cookie = 'jsdebug=true;expires=' + date.toGMTString() + ';path=/;';
        }
        else 
            dbug.disableCookie();
    },
    disableCookie: function(){
        dbug.log('disabling debugging cookie');
        document.cookie = 'jsdebug=false;path=/;';
    }
};

(function(){
    var fb = !!window.console || !!window.firebug;
    var con = window.firebug ? window.firebug.d.console.cmd : window.console;
    var debugMethods = ['debug', 'info', 'warn', 'error', 'assert', 'dir', 'dirxml'];
    var otherMethods = ['trace', 'group', 'groupEnd', 'profile', 'profileEnd', 'count'];
    function set(methodList, defaultFunction){
        for (var i = 0; i < methodList.length; i++) {
            dbug[methodList[i]] = (fb && con[methodList[i]]) ? con[methodList[i]] : defaultFunction;
        }
    };
    set(debugMethods, dbug.log);
    set(otherMethods, function(){
    });
})();
if ((!!window.console && !!window.console.warn) || window.firebug) {
    dbug.firebug = true;
    var value = document.cookie.match('(?:^|;)\\s*jsdebug=([^;]*)');
    var debugCookie = value ? unescape(value[1]) : false;
    if (window.location.href.indexOf("jsdebug=true") > 0 || debugCookie == 'true') 
        dbug.enable();
    if (debugCookie == 'true') 
        dbug.log('debugging cookie enabled');
    if (window.location.href.indexOf("jsdebugCookie=true") > 0) {
        dbug.cookie();
        if (!dbug.enabled) 
            dbug.enable();
    }
    if (window.location.href.indexOf("jsdebugCookie=false") > 0) 
        dbug.disableCookie();
}
/***/


/****/



/****/


/**para DECORCLUB**/
var DecorClub = new Class({
    tipOlvido: "",
    initialize: function(){
    },
    cerrarSesion: function(){
        if ($('cerrar_sesion')) {
            $('cerrar_sesion').addEvent("click", function(){
                window.location.href = 'login/logout.php';
                return false;
            }).setStyle("cursor", "pointer").set("title", "Cerrar sesion");
        }
    },
    enviaEncuesta: function(){
        var theForm = typeof form != 'object' ? document.getElementById('formEncuesta') : form;
        var ret = Spry.Widget.Form.validate(theForm);
        if (ret) {
            return true
        }
        else {
            jQuery('.scrollBar').jScrollPane({
                showArrows: false,
                scrollbarWidth: 25
            });
            return false;
        }
    },
    activaRadios: function(){
        $$('#conteni_encuesta input[type="radio"]').addEvent("click", function(){
            var actual = this.get("value");
            (actual == "otro") ? $('texto_' + this.get("name")).show() : $('texto_' + this.get("name")) ? $('texto_' + this.get("name")).set("value", "").hide() : ''
        });
    },
    activaEncuesta: function(){
        if ($('formEncuesta')) {
            new FormCheck("formEncuesta", {
                display: {
                    errorsLocation: 3,
                    indicateErrors: 2,
                    flashTips: true,
                    fadeDuration: 1000
                }
            });
            
        }
    },
    alternativa: function(id){
        ($(id).get("checked")) ? $('texto_' + id).show() : $('texto_' + id).set("value", "").hide();
    },
    activaLogin: function(){
        if ($('conteni_sesion')) {
            if ($('formLogin')) {
               // new FormCheck('formLogin');
            }
            else {
				
                //var checkForm = new FormCheck('formLoginEdicion');
				
				
                $('formLoginEdicion').addEvent("submit", function(e){
                    e.preventDefault();
					
					var ret = Spry.Widget.Form.validate($("formLoginEdicion")); //solo para spry
					
                    if (ret) {
                        $('mensaje_pass').set("html", "Grabando....");
                        new Request({
                            url: "_editaPass.php?grabar_pass=yes",
                            onSuccess: function(){
                                $('mensaje_pass').set("html", "Grabado completo.");
								//$('passMD5').set("value",MD5($('nuevo_pass_repetido').get("value")));
								$('nuevo_pass').set("value",MD5($('nuevo_pass_repetido').get("value")));
                                this.submit();
								//return false;
                            }
						.bind(this)
                        }).send($('formLoginEdicion').toQueryString());
                        
					}else{
						return false;
					}
                });
            }
            
            this.tipOlvido = new Tooltips({
                div: "olvidarClave",
                ancho: 322,
                alto: 122,
                bntCerrar: '<div style="font-family:verdana;font-size:12px;color:#000000;top:3px;position:relative"><strong>X</strong></div>',
                fondo: "images/bg_toll.png",
                alinear: "izquierda",
                evento: "click",
                html: '<div style="padding:15px;padding-top:0px;">' +
                '<form autocomplete="off" id="form_recuerda_olvido" action="remember.php" method="post" style="padding-top:0px;margin-top:0px">' +
                '<div class="mgs_ok" style="padding-top:8px;margin-bottom:5px">S&oacute;lo tiene que escribir la direcci&oacute;n de correo electr&oacute;nico que utiliz&oacute; para registrarse, y le enviaremos su informaci&oacute;n de acceso a esa direcci&oacute;n inmediatamente.<br></div>' +
                '<input style="width:180px;font-size:11px;float:left;top:4px;position:relative" class="validate[\'required\',\'email\'] text-input txt_input" type="text" id="email_recordar" name=\"email_recordar\">&nbsp;' +
                '<input src="images/b_enviar.png" type="image" >' +
                '<div id="msg_recordar_olvido" class="mgs_ok"></div>' +
                '</form>' +
                '</div>',
                estiloInterior: "txtToolTip",
                forzarCierre: true
            });
            new FormCheck('form_recuerda_olvido', {
                display: {
                    errorsLocation: 0,
                    indicateErrors: 2,
                    showErrors: 1,
                    addClassErrorToField: 1,
                    scrollToFirst: false
                },
                submitByAjax: true,
                onAjaxRequest: function(){
                    $('msg_recordar_olvido').show();
                    $('msg_recordar_olvido').set("html", "");
                },
                onAjaxSuccess: function(e){
                    $('msg_recordar_olvido').hide();
                    if (e == "god") {
                        $('msg_recordar_olvido').set("html", "<b><div style='color:green; padding-top:3px'>Gracias a su mensaje ha sido enviado con &eacute;xito</div></b>").show();
                        $('form_recuerda_olvido').reset();
                        setTimeout(function(){
                            $('moo_tip__ayuda_email').hide();
                            $('msg_recordar_olvido').set("html", "");
                        }, 2000);
                    }
                    else {
                        $('msg_recordar_olvido').set("html", "<b><div style='color:red; top:-5px;position:relative'>Este email no esta registrado en nuestra web.</div></b>").show();
                    }
                    
                },
                onAjaxFailure: function(){
                    alert("errorr");
                }
            });
            
        }
    },
    validaPass: function(){
        pass = $('pass_anterior').val();
        estado = $('estado').val();
        if (pass.length < 2) {
            return false;
        }
        new Request({
            url: '_editaPass.php?comprobar_pass=yes',
            onSuccess: function(e){
                if (e == "ok") {
                    if ($('pass_anterior').hasClass('pass_error')) {
                        $('pass_anterior').removeClass('pass_error');
                        $('pass_anterior').addClass('pass_ok');
                    }
                    else {
                        $('pass_anterior').addClass('pass_ok');
                    }
                    $('estado').set("value", "1");
                }
                else {
                    if ($('pass_anterior').hasClass('pass_ok')) {
                        $('pass_anterior').removeClass('pass_ok');
                        $('pass_anterior').addClass('pass_error')
                    }
                    else {
                        $('pass_anterior').addClass('pass_error')
                    }
                    $('estado').set("value", "0");
                }
            }
        }).send("p=" + pass);
    },
    validaDNI: function(){
        dni = $('dni').val();
        if (dni.length < 8) {
            return false;
        }
        new Request({
            url: '_validaDNI.php',
            onSuccess: function(e){
                if (e == "ok") {
                    $('msgDNI').set("html", "");
                    return true;
                }
                else {
                    $('msgDNI').set("html", "DNI existente <b>(" + dni + ")</b>.");
                    $('dni').set("value", "");
                }
            }
        }).send("dni=" + dni);
    },
    enviaPromotick: function(){
        if ($('formPromotick')) {
            $('formPromotick').submit();
				var ret = Spry.Widget.Form.validate($('formPromotick'));
					if(ret){
						return true;
					}else{
						return false;
					}
        }
        
    },
	activaEdicionDatos:function(){
		if($('frmactualizaDatos')){
			
		}
	}
    
});


/***formcheck**/

var FormCheck = new Class({

    Implements: [Options, Events],
    
    options: {
    
        tipsClass: 'fc-tbx', //tips error class
        errorClass: 'fc-error', //div error class
        fieldErrorClass: 'fc-field-error', //error class for elements
        submit: true, //false : just validate the form and do nothing else. Use onValidateSuccess event to execute some code
        trimValue: false, //trim (remove whitespaces before and after) the value
        validateDisabled: false, //skip validation on disabled input if set to false.
        submitByAjax: false, //false : standard submit way, true : submit by ajax
        ajaxResponseDiv: false, //element to inject ajax response into (can also use onAjaxSuccess) [cronix] 
        ajaxEvalScripts: false, //use evalScripts in the Request response [cronix] 
        onAjaxRequest: $empty, //Function to fire when the Request event starts 
        onAjaxSuccess: $empty, //Function to fire when the Request receives .  Args: response [the request response] - see Mootools docs for Request.onSuccess 
        onAjaxFailure: $empty, //Function to fire if the Request fails
        onSubmit: $empty, //Function to fire when user submit the form
        onValidateSuccess: $empty, //Function to fire when validation pass
        onValidateFailure: $empty, //Function to fire when validation fails
        display: {
            showErrors: 0,
            titlesInsteadNames: 0,
            errorsLocation: 1,
            indicateErrors: 1,
            indicateErrorsInit: 0,
            keepFocusOnError: 0,
            checkValueIfEmpty: 1,
            addClassErrorToField: 0,
            removeClassErrorOnTipClosure: 0,
            fixPngForIe: 1,
            replaceTipsEffect: 1,
            flashTips: 0,
            closeTipsButton: 1,
            tipsPosition: "right",
            tipsOffsetX: -45,
            tipsOffsetY: 0,
            listErrorsAtTop: false,
            scrollToFirst: true,
            fadeDuration: 0
        },
        
        alerts: {
            required: "Este campo es obligatorio.",
            alpha: "Este campo solo acepta letras.",
            alphanum: "Este campo s&oacute;lo acepta letras y n&uacute;meros.",
            nodigit: "No se aceptan d&iacute;gitos.",
            digit: "Por favor solo ingrese numero enteros.",
            digitltd: "Este valor debe estar entre %0 y %1",
            number: "Por favor ingrese un n&uacute;mero v&aacute;lido.",
            email: "Por favor ingrese un email v&aacute;lido.",
            image: 'Este campo s&olo acepta im&aacute;genes',
            phone: "Por favor ingrese un numero de tel&eacute;fono v&acute;lido.",
            phone_inter: "Por favor ingrese un numero internacional de tel&eacute;fono v&acute;lido.",
            url: "Por favor ingrese una correcta URL.",
            
            confirm: "Este campo es diferente de  %0",
            differs: "Este campo debe ser diferente de  %0",
            length_str: "El tama&ntilde;o es incorrecto, debe ser contener entre %0 y %1",
            length_fix: "El tama&ntilde;o es incorrecto, debe contener exactamente %0 caracteres",
            lengthmax: "El tama&ntilde;o es incorrecto, debe ser como m&aacute;ximo %0",
            lengthmin: "El tama&ntilde;o es incorrecto, debe ser mayor a %0",
            words_min: "Este campo debe estar entre %0 palabras, actualmente: %1 palabras",
            words_range: "Eset campo debe contener %0-%1 palabras, actualmente: %2 palabras",
            words_max: "Este campo debe contener como m&aacute;ximo %0 palabras, actualmente: %1 palabras",
            checkbox: "Por favor revise el check",
            radios: "Por favor seleccione una opci&oacute;n",
            select: "Por favor seleccione un valor"
        },
        
        regexp: {
            required: /[^.*]/,
            alpha: /^[a-z ._-]+$/i,
            alphanum: /^[a-z0-9 ._-]+$/i,
            digit: /^[-+]?[0-9]+$/,
            nodigit: /^[^0-9]+$/,
            number: /^[-+]?\d*\.?\d+$/,
            email: /^([a-zA-Z0-9_\.\-\+%])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/,
            image: /.(jpg|jpeg|png|gif|bmp)$/i,
            phone: /^[\d\s ().-]+$/, // alternate regex : /^[\d\s ().-]+$/,/^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,5})|(\(?\d{2,6}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}$/
            phone_inter: /^\+{0,1}[0-9 \(\)\.\-]+$/,
            url: /^(http|https|ftp)\:\/\/[a-z0-9\-\.]+\.[a-z]{2,3}(:[a-z0-9]*)?\/?([a-z0-9\-\._\?\,\'\/\\\+&amp;%\$#\=~])*$/i
        }
    },
    
    /*
     Constructor: initialize
     Constructor
     
     Add event on formular and perform some stuff, you now, like settings, ...
     */
    initialize: function(form, options){
        if (this.form = $(form)) {
            this.form.isValid = true;
            this.regex = ['length'];
            this.setOptions(options);
            
            //internalization
            if (typeof(formcheckLanguage) != 'undefined') 
                this.options.alerts = $merge(this.options.alerts, formcheckLanguage);
            
            this.validations = [];
            this.alreadyIndicated = false;
            this.firstError = false;
            
            var regex = new Hash(this.options.regexp);
            regex.each(function(el, key){
                this.regex.push(key);
            }, this);
            
            this.form.getElements("*[class*=validate]").each(function(el){
                if (el.get('tag') == 'select' || el.get('tag') == 'input' || el.get('tag') == 'textarea') 
                    this.register(el);
            }, this);
            
            this.form.addEvents({
                "submit": this.onSubmit.bind(this)
            });
            
            if (this.options.display.fixPngForIe) 
                this.fixIeStuffs();
            document.addEvent('mousewheel', function(){
                this.isScrolling = false;
            }
.bind(this));
        }
    },
    register: function(el, position){
        el.validation = [];
        el.getProperty("class").split(' ').each(function(classX){
            if (classX.match(/^validate(\[.+\])$/)) {
                var valid = true;
                //we check if group is already registered
                if (el.type == "radio") {
                    this.validations.each(function(valider){
                        if (valider.name == el.name) 
                            valid = false;
                    }, this)
                }
                var validators = eval(classX.match(/^validate(\[.+\])$/)[1]);
                for (var i = 0; i < validators.length; i++) {
                    el.validation.push(validators[i]);
                    if (validators[i].match(/^confirm\[/)) {
                        var field = eval(validators[i].match(/^.+(\[.+\])$/)[1].replace(/([A-Z0-9\._-]+)/i, "'$1'"));
                        if (this.form[field].validation.contains('required')) {
                            el.validation.push('required');
                        }
                    }
                    if (validators[i].match(/^target:.+/)) {
                        el.target = validators[i].match(/^target:(.+)/)[1];
                    }
                }
                //new push way
                if (position && position <= this.validations.length) {
                    var newValidations = [];
                    this.validations.each(function(valider, i){
                        if (position == i + 1 && valid) {
                            newValidations.push(el);
                            this.addListener(el);
                        }
                        newValidations.push(valider);
                    }, this);
                    this.validations = newValidations;
                }
                else {
                    if (valid) {
                        this.validations.push(el);
                        this.addListener(el);
                    }
                }
            }
        }, this);
    },
    dispose: function(element){
        this.validations.erase(element);
    },
    addListener: function(el){
        el.errors = [];
        
        if (this.options.display.indicateErrorsInit) {
            this.validations.each(function(el){
                if (!this.manageError(el, 'submit')) 
                    this.form.isValid = false;
            }, this);
            return true;
        }
        
        if (el.validation[0] == 'submit') {
            el.addEvent('click', function(e){
                if (this.onSubmit(e)) 
                    this.form.submit();
            }.bind(this));
            return true;
        }
        
        if (this.isChildType(el) == false) 
            el.addEvent('blur', function(){
                (function(){
                    if (!this.fxRunning && (el.element || this.options.display.showErrors == 1) && (this.options.display.checkValueIfEmpty || el.value)) 
                        this.manageError(el, 'blur')
                }.bind(this)).delay(100);
            }.bind(this))
        //We manage errors on radio
        else 
            if (this.isChildType(el) == true) {
                //We get all radio from the same group and add a blur option
                var nlButtonGroup = this.form.getElements('input[name="' + el.getProperty("name") + '"]');
                nlButtonGroup.each(function(radio){
                    radio.addEvent('blur', function(){
                        (function(){
                            if ((el.element || this.options.display.showErrors == 1) && (this.options.display.checkValueIfEmpty || el.value)) 
                                this.manageError(el, 'click');
                        }.bind(this)).delay(100);
                    }.bind(this))
                }, this);
            }
    },
    validate: function(el){
        el.errors = [];
        el.isOk = true;
        
        //skip validation and trim if specified
        if (!this.options.validateDisabled && el.get('disabled')) 
            return true;
        if (this.options.trimValue && el.value) 
            el.value = el.value.trim();
        
        el.validation.each(function(rule){
            if (this.isChildType(el)) {
                if (this.validateGroup(el) == false) {
                    el.isOk = false;
                }
            }
            else {
                var ruleArgs = [];
                
                if (rule.match(/target:.+/)) 
                    return;
                
                if (rule.match(/^.+\[/)) {
                    var ruleMethod = rule.split('[')[0];
                    ruleArgs = eval(rule.match(/^.+(\[.+\])$/)[1].replace(/([A-Z0-9\._-]+)/i, "'$1'"));
                }
                else 
                    var ruleMethod = rule;
                
                if (this.regex.contains(ruleMethod) && el.get('tag') != "select") {
                    if (this.validateRegex(el, ruleMethod, ruleArgs) == false) {
                        el.isOk = false;
                    }
                }
                if (ruleMethod == 'confirm') {
                    if (this.validateConfirm(el, ruleArgs) == false) {
                        el.isOk = false;
                    }
                }
                if (ruleMethod == 'differs') {
                    if (this.validateDiffers(el, ruleArgs) == false) {
                        el.isOk = false;
                    }
                }
                if (ruleMethod == 'words') {
                    if (this.validateWords(el, ruleArgs) == false) {
                        el.isOk = false;
                    }
                }
                if (el.get('tag') == "select" || (el.type == "checkbox" && ruleMethod == 'required')) {
                    if (this.simpleValidate(el) == false) {
                        el.isOk = false;
                    }
                }
                if (rule.match(/%[A-Z0-9\._-]+$/i) || (el.isOk && rule.match(/~[A-Z0-9\._-]+$/i))) {
                    if (eval(rule.slice(1) + '(el)') == false) {
                        el.isOk = false;
                    }
                }
            }
        }, this);
        
        if (el.isOk) 
            return true;
        else 
            return false;
    },
    simpleValidate: function(el){
        if (el.get('tag') == 'select' && el.selectedIndex <= 0) {
            el.errors.push(this.options.alerts.select);
            return false;
        }
        else 
            if (el.type == "checkbox" && el.checked == false) {
                el.errors.push(this.options.alerts.checkbox);
                return false;
            }
        return true;
    },
    validateRegex: function(el, ruleMethod, ruleArgs){
        var msg = "";
        if (ruleArgs[1] && ruleMethod == 'length') {
            if (ruleArgs[1] == -1) {
                this.options.regexp.length = new RegExp("^[\\s\\S]{" + ruleArgs[0] + ",}$");
                msg = this.options.alerts.lengthmin.replace("%0", ruleArgs[0]);
            }
            else 
                if (ruleArgs[0] == ruleArgs[1]) {
                    this.options.regexp.length = new RegExp("^[\\s\\S]{" + ruleArgs[0] + "}$");
                    msg = this.options.alerts.length_fix.replace("%0", ruleArgs[0]);
                }
                else {
                    this.options.regexp.length = new RegExp("^[\\s\\S]{" + ruleArgs[0] + "," + ruleArgs[1] + "}$");
                    msg = this.options.alerts.length_str.replace("%0", ruleArgs[0]).replace("%1", ruleArgs[1]);
                }
        }
        else 
            if (ruleArgs[0] && ruleMethod == 'length') {
                this.options.regexp.length = new RegExp("^.{0," + ruleArgs[0] + "}$");
                msg = this.options.alerts.lengthmax.replace("%0", ruleArgs[0]);
            }
            else {
                msg = this.options.alerts[ruleMethod];
            }
        if (ruleArgs[1] && ruleMethod == 'digit') {
            var regres = true;
            if (!this.options.regexp.digit.test(el.value)) {
                el.errors.push(this.options.alerts[ruleMethod]);
                regres = false;
            }
            if (ruleArgs[1] == -1) {
                var valueres = (el.value.toInt() >= ruleArgs[0].toInt());
                msg = this.options.alerts.digitmin.replace("%0", ruleArgs[0]);
            }
            else {
                var valueres = (el.value.toInt() >= ruleArgs[0].toInt() && el.value.toInt() <= ruleArgs[1].toInt());
                msg = this.options.alerts.digitltd.replace("%0", ruleArgs[0]).replace("%1", ruleArgs[1]);
            }
            if (regres == false || valueres == false) {
                el.errors.push(msg);
                return false;
            }
        }
        else 
            if (this.options.regexp[ruleMethod].test(el.value) == false) {
                el.errors.push(msg);
                return false;
            }
        return true;
    },
    
    /*
     Function: validateConfirm
     Private method
     
     Perform confirm validations
     */
    validateConfirm: function(el, ruleArgs){
    
        var confirm = ruleArgs[0];
        if (el.value != this.form[confirm].value) {
            if (this.options.display.titlesInsteadNames) 
                var msg = this.options.alerts.confirm.replace("%0", this.form[confirm].getProperty('title'));
            else 
                var msg = this.options.alerts.confirm.replace("%0", confirm);
            el.errors.push(msg);
            return false;
        }
        return true;
    },
    
    /*
     Function: validateDiffers
     Private method
     
     Perform differs validations
     */
    validateDiffers: function(el, ruleArgs){
        var differs = ruleArgs[0];
        if (el.value == this.form[differs].value) {
            if (this.options.display.titlesInsteadNames) 
                var msg = this.options.alerts.differs.replace("%0", this.form[differs].getProperty('title'));
            else 
                var msg = this.options.alerts.differs.replace("%0", differs);
            el.errors.push(msg);
            return false;
        }
        return true;
    },
    
    /*
     Function: validateWords
     Private method
     
     Perform word count validation
     */
    validateWords: function(el, ruleArgs){
        var min = ruleArgs[0];
        var max = ruleArgs[1];
        
        var words = el.value.replace(/[ \t\v\n\r\f\p]/m, ' ').replace(/[,.;:]/g, ' ').clean().split(' ');
        
        if (max == -1) {
            if (words.length < min) {
                el.errors.push(this.options.alerts.words_min.replace("%0", min).replace("%1", words.length));
                return false;
            }
        }
        else {
            if (min > 0) {
                if (words.length < min || words.length > max) {
                    el.errors.push(this.options.alerts.words_range.replace("%0", min).replace("%1", max).replace("%2", words.length));
                    return false;
                }
            }
            else {
                if (words.length > max) {
                    el.errors.push(this.options.alerts.words_max.replace("%0", max).replace("%1", words.length));
                    return false;
                }
            }
        }
        return true;
    },
    
    
    /*
     Function: isFormValid
     public method
     
     Determine if the form is valid
     
     Return true or false
     */
    isFormValid: function(){
        this.form.isValid = true;
        this.validations.each(function(el){
            var validation = this.manageError(el, 'testonly');
            if (!validation) 
                this.form.isValid = false;
        }, this);
        return this.form.isValid;
    },
    
    /*
     Function: isChildType
     Private method
     
     Determine if the field is a group of radio or not.
     */
    isChildType: function(el){
        return ($defined(el.type) && el.type == 'radio') ? true : false;
    },
    
    /*
     Function: validateGroup
     Private method
     
     Perform radios validations
     */
    validateGroup: function(el){
        el.errors = [];
        var nlButtonGroup = this.form[el.getProperty("name")];
        el.group = nlButtonGroup;
        var cbCheckeds = false;
        
        for (var i = 0; i < nlButtonGroup.length; i++) {
            if (nlButtonGroup[i].checked) {
                cbCheckeds = true;
            }
        }
        if (cbCheckeds == false) {
            el.errors.push(this.options.alerts.radios);
            return false;
        }
        else {
            return true;
        }
    },
    
    /*
     Function: listErrorsAtTop
     Private method
     
     Display errors
     */
    listErrorsAtTop: function(obj){
        if (!this.form.element) {
            this.form.element = new Element('div', {
                'id': 'errorlist',
                'class': this.options.errorClass
            }).injectTop(this.form);
        }
        if ($type(obj) == 'collection') {
            new Element('p').set('html', "<span>" + obj[0].name + " : </span>" + obj[0].errors[0]).injectInside(this.form.element);
        }
        else {
            if ((obj.validation.contains('required') && obj.errors.length > 0) || (obj.errors.length > 0 && obj.value && obj.validation.contains('required') == false)) {
                obj.errors.each(function(error){
                    new Element('p').set('html', "<span>" + obj.name + " : </span>" + error).injectInside(this.form.element);
                }, this);
            }
        }
        window.fireEvent('resize');
    },
    
    /*
     Function: manageError
     Private method
     
     Manage display of errors boxes
     */
    manageError: function(el, method){
        var isValid = this.validate(el);
        if (method == 'testonly') 
            return isValid;
        if ((!isValid && el.validation.flatten()[0].contains('confirm[')) || (!isValid && el.validation.contains('required')) || (!el.validation.contains('required') && el.value && !isValid)) {
            if (this.options.display.listErrorsAtTop == true && method == 'submit') 
                this.listErrorsAtTop(el);
            if (this.options.display.indicateErrors == 2 || this.alreadyIndicated == false || el.name == this.alreadyIndicated.name) {
                if (!this.firstError) 
                    this.firstError = el;
                
                this.alreadyIndicated = el;
                
                if (this.options.display.keepFocusOnError && el.name == this.firstError.name) 
                    (function(){
                        el.focus()
                    }).delay(20);
                this.addError(el);
                return false;
            }
        }
        else 
            if ((isValid || (!el.validation.contains('required') && !el.value))) {
                this.removeError(el);
                return true;
            }
        return true;
    },
    
    /*
     Function: addError
     Private method
     
     Add error message
     */
    addError: function(obj){
        //determine position
        var coord = obj.target ? $(obj.target).getCoordinates() : obj.getCoordinates();
        
        if (!obj.element && this.options.display.indicateErrors != 0) {
            if (this.options.display.errorsLocation == 1) {
                var pos = (this.options.display.tipsPosition == 'left') ? coord.left : coord.right;
                var options = {
                    'opacity': 0,
                    'position': 'absolute',
                    'float': 'left',
                    'left': pos + this.options.display.tipsOffsetX,
                    'z-Index': 900
                }
                obj.element = new Element('div', {
                    'class': this.options.tipsClass,
                    'styles': options
                }).injectInside(document.body);
                this.addPositionEvent(obj);
            }
            else 
                if (this.options.display.errorsLocation == 2) {
                    obj.element = new Element('div', {
                        'class': this.options.errorClass,
                        'styles': {
                            'opacity': 0
                        }
                    }).injectBefore(obj);
                }
                else 
                    if (this.options.display.errorsLocation == 3) {
                        obj.element = new Element('div', {
                            'class': this.options.errorClass,
                            'styles': {
                                'opacity': 0
                            }
                        });
                        if ($type(obj.group) == 'object' || $type(obj.group) == 'collection') 
                            obj.element.injectAfter(obj.group[obj.group.length - 1]);
                        else 
                            obj.element.injectAfter(obj);
                    }
        }
        if (obj.element && obj.element != true) {
            obj.element.empty();
            if (this.options.display.errorsLocation == 1) {
                var errors = [];
                obj.errors.each(function(error){
                    errors.push(new Element('p').set('html', error));
                });
                var tips = this.makeTips(errors).injectInside(obj.element);
                if (this.options.display.closeTipsButton) {
                    tips.getElements('a.close').addEvent('mouseup', function(){
                        this.removeError(obj, 'tip');
                    }.bind(this));
                }
                obj.element.setStyle('top', coord.top - tips.getCoordinates().height + this.options.display.tipsOffsetY);
            }
            else {
                obj.errors.each(function(error){
                    new Element('p').set('html', error).injectInside(obj.element);
                });
            }
            
            if (!this.options.display.fadeDuration || Browser.Engine.trident && Browser.Engine.version == 5 && this.options.display.errorsLocation < 2) {
                obj.element.setStyle('opacity', 1);
            }
            else {
                obj.fx = new Fx.Tween(obj.element, {
                    'duration': this.options.display.fadeDuration,
                    'ignore': true,
                    'onStart': function(){
                        this.fxRunning = true;
                    }.bind(this)                    ,
                    'onComplete': function(){
                        this.fxRunning = false;
                        if (obj.element && obj.element.getStyle('opacity').toInt() == 0) {
                            obj.element.destroy();
                            obj.element = false;
                        }
                    }.bind(this)
                })
                if (obj.element.getStyle('opacity').toInt() != 1) 
                    obj.fx.start('opacity', 1);
            }
        }
        if (this.options.display.addClassErrorToField && this.isChildType(obj) == false) {
            obj.addClass(this.options.fieldErrorClass);
            obj.element = obj.element || true;
        }
        
    },
    
    /*
     Function: addPositionEvent
     
     Update tips position after a browser resize
     */
    addPositionEvent: function(obj){
        if (this.options.display.replaceTipsEffect) {
            obj.event = function(){
                var coord = obj.target ? $(obj.target).getCoordinates() : obj.getCoordinates();
                new Fx.Morph(obj.element, {
                    'duration': this.options.display.fadeDuration
                }).start({
                    'left': [obj.element.getStyle('left'), coord.right + this.options.display.tipsOffsetX],
                    'top': [obj.element.getStyle('top'), coord.top - obj.element.getCoordinates().height + this.options.display.tipsOffsetY]
                });
            }
.bind(this);
            
        }
        else {
            obj.event = function(){
                var coord = obj.target ? $(obj.target).getCoordinates() : obj.getCoordinates();
                obj.element.setStyles({
                    'left': coord.right + this.options.display.tipsOffsetX,
                    'top': coord.top - obj.element.getCoordinates().height + this.options.display.tipsOffsetY
                });
            }
.bind(this)
        }
        window.addEvent('resize', obj.event);
    },
    
    /*
     Function: removeError
     Private method
     
     Remove the error display
     */
    removeError: function(obj, method){
        if ((this.options.display.addClassErrorToField && !this.isChildType(obj) && this.options.display.removeClassErrorOnTipClosure) || (this.options.display.addClassErrorToField && !this.isChildType(obj) && !this.options.display.removeClassErrorOnTipClosure && method != 'tip')) 
            obj.removeClass(this.options.fieldErrorClass);
        
        if (!obj.element) 
            return;
        this.alreadyIndicated = false;
        obj.errors = [];
        obj.isOK = true;
        window.removeEvent('resize', obj.event);
        if (this.options.display.errorsLocation >= 2 && obj.element) {
            new Fx.Tween(obj.element, {
                'duration': this.options.display.fadeDuration
            }).start('height', 0);
        }
        if (!this.options.display.fadeDuration || Browser.Engine.trident && Browser.Engine.version == 5 && this.options.display.errorsLocation == 1 && obj.element) {
            this.fxRunning = true;
            obj.element.destroy();
            obj.element = false;
            (function(){
                this.fxRunning = false
            }
.bind(this)).delay(200);
        }
        else 
            if (obj.element && obj.element != true) {
                obj.fx.start('opacity', 0);
            }
    },
    
    /*
     Function: focusOnError
     Private method
     
     Create set the focus to the first field with an error if needed
     */
    focusOnError: function(obj){
        if (this.options.display.scrollToFirst && !this.alreadyFocused && !this.isScrolling) {
            if (!this.options.display.indicateErrors || !this.options.display.errorsLocation) {
                var dest = obj.getCoordinates().top - 30;
            }
            else 
                if (this.alreadyIndicated.element) {
                    switch (this.options.display.errorsLocation) {
                        case 1:
                            var dest = obj.element.getCoordinates().top;
                            break;
                        case 2:
                            var dest = obj.element.getCoordinates().top - 30;
                            break;
                        case 3:
                            var dest = obj.getCoordinates().top - 30;
                            break;
                    }
                    this.isScrolling = true;
                }
            if (window.getScroll.y != dest) {
                new Fx.Scroll(window, {
                    duration: "long",
                    onComplete: function(){
                        this.isScrolling = false;
                        if (obj.getProperty('type') != 'hidden') 
                            obj.focus();
                    }
.bind(this)
                }).start(0, dest);
            }
            else {
                this.isScrolling = false;
                obj.focus();
            }
            this.alreadyFocused = true;
        }
    },
    
    /*
     Function: fixIeStuffs
     Private method
     
     Fix png for IE6
     */
    fixIeStuffs: function(){
        if (Browser.Engine.trident4) {
            //We fix png stuffs
            var rpng = new RegExp('url\\(([\.a-zA-Z0-9_/:-]+\.png)\\)');
            var search = new RegExp('(.+)formcheck\.css');
            for (var i = 0; i < document.styleSheets.length; i++) {
                if (document.styleSheets[i].href.match(/formcheck\.css$/)) {
                    var root = document.styleSheets[i].href.replace(search, '$1');
                    var count = document.styleSheets[i].rules.length;
                    for (var j = 0; j < count; j++) {
                        var cssstyle = document.styleSheets[i].rules[j].style;
                        var bgimage = root + cssstyle.backgroundImage.replace(rpng, '$1');
                        if (bgimage && bgimage.match(/\.png/i)) {
                            var scale = (cssstyle.backgroundRepeat == 'no-repeat') ? 'crop' : 'scale';
                            cssstyle.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, src=\'' + bgimage + '\', sizingMethod=\'' + scale + '\')';
                            cssstyle.backgroundImage = "none";
                        }
                    }
                }
            }
        }
    },
    
    /*
     Function: makeTips
     Private method
     
     Create tips boxes
     */
    makeTips: function(txt){
        var table = new Element('table');
        table.cellPadding = '0';
        table.cellSpacing = '0';
        table.border = '0';
        
        var tbody = new Element('tbody').injectInside(table);
        var tr1 = new Element('tr').injectInside(tbody);
        new Element('td', {
            'class': 'tl'
        }).injectInside(tr1);
        new Element('td', {
            'class': 't'
        }).injectInside(tr1);
        new Element('td', {
            'class': 'tr'
        }).injectInside(tr1);
        var tr2 = new Element('tr').injectInside(tbody);
        new Element('td', {
            'class': 'l'
        }).injectInside(tr2);
        var cont = new Element('td', {
            'class': 'c'
        }).injectInside(tr2);
        var errors = new Element('div', {
            'class': 'err'
        }).injectInside(cont);
        txt.each(function(error){
            error.injectInside(errors);
        });
        if (this.options.display.closeTipsButton) 
            new Element('a', {
                'class': 'close'
            }).injectInside(cont);
        new Element('td', {
            'class': 'r'
        }).injectInside(tr2);
        var tr3 = new Element('tr').injectInside(tbody);
        new Element('td', {
            'class': 'bl'
        }).injectInside(tr3);
        new Element('td', {
            'class': 'b'
        }).injectInside(tr3);
        new Element('td', {
            'class': 'br'
        }).injectInside(tr3);
        return table;
    },
    
    /*
     Function: reinitialize
     Reinitialize form before submit check. You can use this also to remove all tips from a form, passing the argument "forced" ( formcheck.reinitialize('forced'); )
     */
    reinitialize: function(forced){
        this.validations.each(function(el){
            if (el.element) {
                el.errors = [];
                el.isOK = true;
                if (this.options.display.flashTips == 1 || forced == 'forced') {
                    el.element.destroy();
                    el.element = false;
                }
            }
        }, this);
        if (this.form.element) 
            this.form.element.empty();
        this.alreadyFocused = false;
        this.firstError = false;
        this.elementToRemove = this.alreadyIndicated;
        this.alreadyIndicated = false;
        this.form.isValid = true;
    },
    submitByAjax: function(){
        var url = this.form.getProperty('action');
        this.fireEvent('ajaxRequest');
        new Request({
            url: url,
            method: this.form.getProperty('method'),
            data: this.form.toQueryString(),
            evalScripts: this.options.ajaxEvalScripts,
            onFailure: function(instance){
                this.fireEvent('ajaxFailure', instance);
            }.bind(this)            ,
            onSuccess: function(result){
                this.fireEvent('ajaxSuccess', result);
                if (this.options.ajaxResponseDiv) 
                    $(this.options.ajaxResponseDiv).set('html', result);
            }.bind(this)
        }).send();
    },
    onSubmit: function(event){
        this.reinitialize();
        this.fireEvent('onSubmit');
        
        this.validations.each(function(el){
            var validation = this.manageError(el, 'submit');
            if (!validation) 
                this.form.isValid = false;
        }, this);
        
        if (this.form.isValid) {
            if (this.options.submitByAjax) {
                new Event(event).stop();
                this.submitByAjax();
            }
            else 
                if (!this.options.submit) {
                    new Event(event).stop();
                }
            this.fireEvent('validateSuccess');
            return true;
        }
        else {
            new Event(event).stop();
            if (this.elementToRemove && this.elementToRemove != this.firstError && this.options.display.indicateErrors == 1) {
                this.removeError(this.elementToRemove);
            }
            this.focusOnError(this.firstError);
            this.fireEvent('validateFailure');
            return false;
        }
    }
});



var MD5 = function (string) {
 
	function RotateLeft(lValue, iShiftBits) {
		return (lValue<<iShiftBits) | (lValue>>>(32-iShiftBits));
	}
 
	function AddUnsigned(lX,lY) {
		var lX4,lY4,lX8,lY8,lResult;
		lX8 = (lX & 0x80000000);
		lY8 = (lY & 0x80000000);
		lX4 = (lX & 0x40000000);
		lY4 = (lY & 0x40000000);
		lResult = (lX & 0x3FFFFFFF)+(lY & 0x3FFFFFFF);
		if (lX4 & lY4) {
			return (lResult ^ 0x80000000 ^ lX8 ^ lY8);
		}
		if (lX4 | lY4) {
			if (lResult & 0x40000000) {
				return (lResult ^ 0xC0000000 ^ lX8 ^ lY8);
			} else {
				return (lResult ^ 0x40000000 ^ lX8 ^ lY8);
			}
		} else {
			return (lResult ^ lX8 ^ lY8);
		}
 	}
 
 	function F(x,y,z) { return (x & y) | ((~x) & z); }
 	function G(x,y,z) { return (x & z) | (y & (~z)); }
 	function H(x,y,z) { return (x ^ y ^ z); }
	function I(x,y,z) { return (y ^ (x | (~z))); }
 
	function FF(a,b,c,d,x,s,ac) {
		a = AddUnsigned(a, AddUnsigned(AddUnsigned(F(b, c, d), x), ac));
		return AddUnsigned(RotateLeft(a, s), b);
	};
 
	function GG(a,b,c,d,x,s,ac) {
		a = AddUnsigned(a, AddUnsigned(AddUnsigned(G(b, c, d), x), ac));
		return AddUnsigned(RotateLeft(a, s), b);
	};
 
	function HH(a,b,c,d,x,s,ac) {
		a = AddUnsigned(a, AddUnsigned(AddUnsigned(H(b, c, d), x), ac));
		return AddUnsigned(RotateLeft(a, s), b);
	};
 
	function II(a,b,c,d,x,s,ac) {
		a = AddUnsigned(a, AddUnsigned(AddUnsigned(I(b, c, d), x), ac));
		return AddUnsigned(RotateLeft(a, s), b);
	};
 
	function ConvertToWordArray(string) {
		var lWordCount;
		var lMessageLength = string.length;
		var lNumberOfWords_temp1=lMessageLength + 8;
		var lNumberOfWords_temp2=(lNumberOfWords_temp1-(lNumberOfWords_temp1 % 64))/64;
		var lNumberOfWords = (lNumberOfWords_temp2+1)*16;
		var lWordArray=Array(lNumberOfWords-1);
		var lBytePosition = 0;
		var lByteCount = 0;
		while ( lByteCount < lMessageLength ) {
			lWordCount = (lByteCount-(lByteCount % 4))/4;
			lBytePosition = (lByteCount % 4)*8;
			lWordArray[lWordCount] = (lWordArray[lWordCount] | (string.charCodeAt(lByteCount)<<lBytePosition));
			lByteCount++;
		}
		lWordCount = (lByteCount-(lByteCount % 4))/4;
		lBytePosition = (lByteCount % 4)*8;
		lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80<<lBytePosition);
		lWordArray[lNumberOfWords-2] = lMessageLength<<3;
		lWordArray[lNumberOfWords-1] = lMessageLength>>>29;
		return lWordArray;
	};
 
	function WordToHex(lValue) {
		var WordToHexValue="",WordToHexValue_temp="",lByte,lCount;
		for (lCount = 0;lCount<=3;lCount++) {
			lByte = (lValue>>>(lCount*8)) & 255;
			WordToHexValue_temp = "0" + lByte.toString(16);
			WordToHexValue = WordToHexValue + WordToHexValue_temp.substr(WordToHexValue_temp.length-2,2);
		}
		return WordToHexValue;
	};
 
	function Utf8Encode(string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";
 
		for (var n = 0; n < string.length; n++) {
 
			var c = string.charCodeAt(n);
 
			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
 
		}
 
		return utftext;
	};
 
	var x=Array();
	var k,AA,BB,CC,DD,a,b,c,d;
	var S11=7, S12=12, S13=17, S14=22;
	var S21=5, S22=9 , S23=14, S24=20;
	var S31=4, S32=11, S33=16, S34=23;
	var S41=6, S42=10, S43=15, S44=21;
 
	string = Utf8Encode(string);
 
	x = ConvertToWordArray(string);
 
	a = 0x67452301; b = 0xEFCDAB89; c = 0x98BADCFE; d = 0x10325476;
 
	for (k=0;k<x.length;k+=16) {
		AA=a; BB=b; CC=c; DD=d;
		a=FF(a,b,c,d,x[k+0], S11,0xD76AA478);
		d=FF(d,a,b,c,x[k+1], S12,0xE8C7B756);
		c=FF(c,d,a,b,x[k+2], S13,0x242070DB);
		b=FF(b,c,d,a,x[k+3], S14,0xC1BDCEEE);
		a=FF(a,b,c,d,x[k+4], S11,0xF57C0FAF);
		d=FF(d,a,b,c,x[k+5], S12,0x4787C62A);
		c=FF(c,d,a,b,x[k+6], S13,0xA8304613);
		b=FF(b,c,d,a,x[k+7], S14,0xFD469501);
		a=FF(a,b,c,d,x[k+8], S11,0x698098D8);
		d=FF(d,a,b,c,x[k+9], S12,0x8B44F7AF);
		c=FF(c,d,a,b,x[k+10],S13,0xFFFF5BB1);
		b=FF(b,c,d,a,x[k+11],S14,0x895CD7BE);
		a=FF(a,b,c,d,x[k+12],S11,0x6B901122);
		d=FF(d,a,b,c,x[k+13],S12,0xFD987193);
		c=FF(c,d,a,b,x[k+14],S13,0xA679438E);
		b=FF(b,c,d,a,x[k+15],S14,0x49B40821);
		a=GG(a,b,c,d,x[k+1], S21,0xF61E2562);
		d=GG(d,a,b,c,x[k+6], S22,0xC040B340);
		c=GG(c,d,a,b,x[k+11],S23,0x265E5A51);
		b=GG(b,c,d,a,x[k+0], S24,0xE9B6C7AA);
		a=GG(a,b,c,d,x[k+5], S21,0xD62F105D);
		d=GG(d,a,b,c,x[k+10],S22,0x2441453);
		c=GG(c,d,a,b,x[k+15],S23,0xD8A1E681);
		b=GG(b,c,d,a,x[k+4], S24,0xE7D3FBC8);
		a=GG(a,b,c,d,x[k+9], S21,0x21E1CDE6);
		d=GG(d,a,b,c,x[k+14],S22,0xC33707D6);
		c=GG(c,d,a,b,x[k+3], S23,0xF4D50D87);
		b=GG(b,c,d,a,x[k+8], S24,0x455A14ED);
		a=GG(a,b,c,d,x[k+13],S21,0xA9E3E905);
		d=GG(d,a,b,c,x[k+2], S22,0xFCEFA3F8);
		c=GG(c,d,a,b,x[k+7], S23,0x676F02D9);
		b=GG(b,c,d,a,x[k+12],S24,0x8D2A4C8A);
		a=HH(a,b,c,d,x[k+5], S31,0xFFFA3942);
		d=HH(d,a,b,c,x[k+8], S32,0x8771F681);
		c=HH(c,d,a,b,x[k+11],S33,0x6D9D6122);
		b=HH(b,c,d,a,x[k+14],S34,0xFDE5380C);
		a=HH(a,b,c,d,x[k+1], S31,0xA4BEEA44);
		d=HH(d,a,b,c,x[k+4], S32,0x4BDECFA9);
		c=HH(c,d,a,b,x[k+7], S33,0xF6BB4B60);
		b=HH(b,c,d,a,x[k+10],S34,0xBEBFBC70);
		a=HH(a,b,c,d,x[k+13],S31,0x289B7EC6);
		d=HH(d,a,b,c,x[k+0], S32,0xEAA127FA);
		c=HH(c,d,a,b,x[k+3], S33,0xD4EF3085);
		b=HH(b,c,d,a,x[k+6], S34,0x4881D05);
		a=HH(a,b,c,d,x[k+9], S31,0xD9D4D039);
		d=HH(d,a,b,c,x[k+12],S32,0xE6DB99E5);
		c=HH(c,d,a,b,x[k+15],S33,0x1FA27CF8);
		b=HH(b,c,d,a,x[k+2], S34,0xC4AC5665);
		a=II(a,b,c,d,x[k+0], S41,0xF4292244);
		d=II(d,a,b,c,x[k+7], S42,0x432AFF97);
		c=II(c,d,a,b,x[k+14],S43,0xAB9423A7);
		b=II(b,c,d,a,x[k+5], S44,0xFC93A039);
		a=II(a,b,c,d,x[k+12],S41,0x655B59C3);
		d=II(d,a,b,c,x[k+3], S42,0x8F0CCC92);
		c=II(c,d,a,b,x[k+10],S43,0xFFEFF47D);
		b=II(b,c,d,a,x[k+1], S44,0x85845DD1);
		a=II(a,b,c,d,x[k+8], S41,0x6FA87E4F);
		d=II(d,a,b,c,x[k+15],S42,0xFE2CE6E0);
		c=II(c,d,a,b,x[k+6], S43,0xA3014314);
		b=II(b,c,d,a,x[k+13],S44,0x4E0811A1);
		a=II(a,b,c,d,x[k+4], S41,0xF7537E82);
		d=II(d,a,b,c,x[k+11],S42,0xBD3AF235);
		c=II(c,d,a,b,x[k+2], S43,0x2AD7D2BB);
		b=II(b,c,d,a,x[k+9], S44,0xEB86D391);
		a=AddUnsigned(a,AA);
		b=AddUnsigned(b,BB);
		c=AddUnsigned(c,CC);
		d=AddUnsigned(d,DD);
	}
 
	var temp = WordToHex(a)+WordToHex(b)+WordToHex(c)+WordToHex(d);
 
	return temp.toLowerCase();
}




var PopImages= new Class({
	clase:'popLink',
	Implements : [Options,Events],
	options:{
		fade:true,
		drag:true,
		duration:0.5,
		close:false,
		closeClass:''
	},
	_items:'',
	_container:'',
	onOpen:$empty,
	onClose:$empty,
	_isOpen:false,
	_element:'',
	_close:'',
	initialize:function(obj,options){
	
		this.setOptions(options);
		if(!obj){
			this.scan();
			return false;
		}
		
		
		this._container = new Element('div',{
			styles:{
				border:'0px solid #000000',
				opacity : 0.5,
				position : 'absolute',
				cursor:'move',
				zIndex:1200
			}
		});
		
		
		
		if(this.options.close){
			this._close= new Element('div',{
				styles:{
					position:'relative',
					border:'0px solid #000'
				},
				'class':this.options.closeClass
			}). injectInside(this._container);
			this._close.addEvent("click",this.close.bind(this))
			.setStyle("cursor","pointer")	;
		}
		
		
		$$('body').grab(this._container);
		
		document.addEvents({
            'keypress': function(e){
                if (e.key == 'esc') {
                    if (this._container) {
                        this.close();
                    }
                }
            }.bind(this)
        });
		
		
		
		this._element=obj;
		
		this._element.addEvent("click",function(el,i){
			el.stop();
				image=new Asset.image(this._element.get("href"));
			if(!this._isOpen){
				this.open(image);
			}
				
		}.bind(this));
		
	},
	
	scan:function(){
		this._items=$$('a.'+this.clase);
		
		
		this._items.each(function(el,index){
				new PopImages(el,this.options);
		}.bind(this));
		
		
	},
	open:function(image){
		var pos = window.getHeight();
        var posAncho = window.getWidth();
        sizes = window.getSize();
        scrollito = window.getScroll();
	
		this._container.set({
			"morph":{duration:this.options.duration * 1000},
			"styles":{
				backgroundImage :'url('+image.src+')'
			}
		})
		.morph({
			height:[0,image.height],
			width:[0,image.width],
			opacity:1,
			top    :  (scrollito.y + (sizes.y - image.height) / 2).toInt(),
            left   : posAncho / 2 - (image.width / 2).toInt()
            
		});
		this._isOpen=true;
		
		if(this.options.drag){
			this._container.makeDraggable();
		}
	},	
	close:function(){
		var pos = window.getHeight();
        var posAncho = window.getWidth();
        sizes = window.getSize();
        scrollito = window.getScroll();
		this._container
		.morph({
			height:[0],
			width:[0],
			opacity:0.5,
			top    :  0,
            left   : 0
		});
		this._isOpen=false;
	}
});






//****/	
new Asset.css('css/slimbox.css');
new Asset.css('css/formcheck.css');
var decor = new Decor();
var decorclub = new DecorClub();


