var tabActual;

$(document).ready(init);

function init(){
	
	// ENLACES EXTERNOS
	$(".aExterno").attr("target", "_blank");
	
	// MENU PRINCIPAL
	$("#mainMenu ul li:last-child").addClass("item-bottom");
	$("#mainMenu ul li:first").find("ul").css("top", "0px");
	$("#mainMenu .mGroup").hover(showSubmenu, hideSubmenu);
		
	// SEPARADOR DE ENLACES FIJOS EN EL SLIDESHOW DE LA HOME
	var cssSepLinks = {
	    'background-image': 'url(img/sprite.png)',
	    'background-position': '-385px -135px',
	    'width': '295px',
	    'height': '29px',
	    'display': 'block'
	};
	$("#home #slide #sideLink1").append("<span></span>");
	$("#home #slide #sideLink1 span").css(cssSepLinks);
	$("#home #slide #sideLink1 a span").css("display", "none");
		
	// TABS ESPECIFICACIONES DETALLE PRODUCTO
	var cssMask = {
	 'min-height' : '116px',
	 'width' : '100%',
	 'overflow' : 'hidden'
    };   
	$('.detalle #prodSpecs h4').addClass("oculto");
	$('.detalle #prodSpecs #mask').css(cssMask).before('<ul id="blocks"><li><a href="#desc">' + $('.detalle #prodSpecs #mask #desc h4').text() + '</a></li><li><a href="#designer">' + $('.detalle #prodSpecs #mask #designer h4').text() + '</a></li><li><a href="#sizes">' + $('.detalle #prodSpecs #mask #sizes h4').text() + '</a></li></ul>');
	$(".detalle #prodSpecs #mask div").hide();
	$(".detalle #prodSpecs #mask div:first").show();
	$(".detalle #prodSpecs #blocks li a").removeClass("actual").css("cursor", "pointer").click(cambiaBloque);
	$(".detalle #prodSpecs #blocks li a:first").addClass("actual").css("cursor", "text");
	
	// BOTONES COMPRA
	$(".detalle #buyBox form input").hover(buyBtnOver, buyBtnOut);
	
 	// Tabs
	$(".tab_content").hide(); //Esconde todo el contenido  
	$("ul.tabs li:first").addClass("active").show(); //Activa la primera tab    
	$(".tab_content:first").show(); //Muestra el contenido de la primera tab    
	//On Click Event    
	$("ul.tabs li").click(function() {    
		$("ul.tabs li").removeClass("active"); //Elimina las clases activas  
  		$(this).addClass("active"); //Agrega la clase activa a la tab seleccionada    
		$(".tab_content").hide(); //Esconde todo el contenido de la tab    
		var activeTab = $(this).find("a").attr("href"); //Encuentra el valor del atributo href para identificar la tab activa + el contenido    
		$(activeTab).fadeIn(); //Agrega efecto de transición (fade) en el contenido activo    
		return false;    
	});

	// FORMULARIOS HEADER
	validarForms("");

	//$(".elemProvincia").css("display", "none");	
	
    $("#frmRegistro #id_pais").change(function() {
        if ($("#frmRegistro #id_pais option:selected").val() != "73") {
            $("#frmRegistro .elemProvincia").css("display", "none");
            $("#frmRegistro #id_provincia").removeClass("required");
        } else {
            $("#frmRegistro .elemProvincia").css("display", "inline");
            $("#frmRegistro #id_provincia").addClass("required");
        }
    });

    // FORMULARIOS PASO 0
    validarForms("0");

    $("#frmRegistro0 #id_pais").change(function() {
        if ($("#frmRegistro0 #id_pais option:selected").val() != "73") {
            $("#frmRegistro0 .elemProvincia").css("display", "none");
            $("#frmRegistro0 #id_provincia").removeClass("required");            
        } else {
            $("#frmRegistro0 .elemProvincia").css("display", "inline");
            $("#frmRegistro0 #id_provincia").addClass("required");
        }
    });
    

    // FORMULARIOS PASO 1
    $("#frmPaso1").validate({
		rules: {		
		    e_id_provincia: {
				required: function(){
					//SI ES ESPAÑA SE REQUIERE PROVINCIA...
					if ($("#e_id_pais").val()=="73") {
						return true;
					}
					else {
						return false;
					}
				} 
			},
			f_id_provincia: {
				required: function(){
					//SI ES ESPAÑA SE REQUIERE PROVINCIA...
					if ($("#f_id_pais").val()=="73") {
						return true;
					}
					else {
						return false;
					}
				} 
			}
		}
    });

    // NAVEGACION DE LA COMPRA
    menuSlider.init('steps', 'slide');
    
    // PASO 3 <FORMA DE PAGO>
    $(".radio").dgStyle();
    $(".checkbox").dgStyle();


    // wrap as a jQuery plugin and pass jQuery in to our anoymous function
    $.fn.cross = function(options) {
        return this.each(function(i) {
            // cache the copy of jQuery(this) - the start image
            var $$ = $(this);

            // get the target from the backgroundImage + regexp
            var target = $$.css('backgroundImage').replace(/^url|[\(\)'"]/g, '');

            // nice long chain: wrap img element in span
            $$.wrap('<span style="position: relative;"></span>')
            // change selector to parent - i.e. newly created span
                .parent()
            // prepend a new image inside the span
                .prepend('<img>')
            // change the selector to the newly created image
                .find(':first-child')
            // set the image to the target
                .attr('src', target);

            // the CSS styling of the start image needs to be handled
            // differently for different browsers
            if ($.browser.msie || $.browser.mozilla) {
                $$.css({
                    'position': 'absolute',
                    'left': 0,
                    'background': ''                    
                });
            } else if ($.browser.opera && $.browser.version < 9.5) {
                // Browser sniffing is bad - however opera < 9.5 has a render bug 
                // so this is required to get around it we can't apply the 'top' : 0 
                // separately because Mozilla strips the style set originally somehow...                    
                $$.css({
                    'position': 'absolute',
                    'left': 0,
                    'background': '',
                    'top': "0"
                });
            } else { // Safari
                $$.css({
                    'position': 'absolute',
                    'left': 0,
                    'background': ''
                });
            }

            // similar effect as single image technique, except using .animate 
            // which will handle the fading up from the right opacity for us
            $$.hover(function() {
                $$.stop().animate({
                    opacity: 0
                }, 250);
            }, function() {
                $$.stop().animate({
                    opacity: 1
                }, 250);
            });
        });
    };      
}

function validarForms(num) {
    $("#formComments").validate();
    $("#frmLogin" + num).validate();
    $("#frmPass" + num).validate();
    $("#frmRegistro" + num).validate({
        rules: {
            password_again2: {
                required: true,
                equalTo: "#password2"
            }
        }
    });
}

// FUNCIONES ADDTOCART (Fly to Basket)
function addToCart() {
   
    var buy = 0;
    var rent = 0;
    
    if ($("#buy:checked").val() == undefined && $("#rent:checked").val() == undefined) {
        $("#msg_cart").html(errorFormaArticulo);
        return false;
    }
    else {
        if ($("#buy:checked").val() == "1") { buy = 1; } else { rent = 1; }
        if ($("#id_article").val() == "") {
            $("#msg_cart").html(errorTallaArticulo);
            return false;
        }
    }
	
	//25-abr-2010 (ANP) - Deshabilitamos la opción de alquiler mostrando un mensaje.
	if (rent == 1) {
		$("#msg_cart").html(errorNoAlquiler);
		return false;
	}

    var productIDVal = $("#id_article").val();

    var productX = $("#tallas").offset().left;
    var productY = $("#tallas").offset().top;

    var basketX = $("#secMenu #cart").offset().left;
    var basketY = $("#secMenu #cart").offset().top;

    var gotoX = basketX - productX;
    var gotoY = basketY - productY;

    var newImageWidth = $("#id_article").width() / 1;
    var newImageHeight = $("#id_article").height() / 1;

    $("#tallas").clone().prependTo("#tallas").css({ 'position': 'absolute' }).animate({ opacity: 0.4 }, 100).animate({ opacity: 0.1, marginLeft: gotoX, marginTop: gotoY, width: newImageWidth, height: newImageHeight }, 1200, function() {

	    $(this).remove();

	    $("#msg_cart").html(anadeArticulo);

	    $.ajax({
	        type: "POST",
	        url: strDirURL+"/ajax.carrito.asp",
	        data: { productID: productIDVal, action: "addToBasket", buy: buy, rent: rent, amount: 1 },
	        success: function(theResponse) {
	            $("#secMenu #cart div").html(theResponse);
	            $("#secMenu #cart").fadeOut();
	            $("#secMenu #cart").fadeIn("slow");
	            $("#msg_cart").html(successArticulo);
	            $("#add_to_cart").html("");
	        },
	        error: function() {
	            $("#msg_cart").html(errorAnadeArticulo);
	        }
	    });

	});		
}

// FUNCIONES MENU PRINCIPAL
function showSubmenu(){
	$(this).find("p").addClass("selected");
	$(this).find("ul:first").stop().removeClass("oculto");
	$(this).children('.second').stop().removeClass("oculto");
}
function hideSubmenu(){
	$(this).find("p").removeClass("selected");
	$(this).find("ul").stop().addClass("oculto");
}
function buyBtnOver() {
    $(this).addClass("btnOver");
}
function buyBtnOut() {
    $(this).removeClass("btnOver");
}


// FUNCIONES TABS ESPECIFICACIONES DETALLE PRODUCTO
function cambiaBloque(){
	tabActual =  $(".detalle #prodSpecs #blocks li a").index($(this));
	$(".detalle #prodSpecs #blocks li a").removeClass("actual").css("cursor", "pointer");
	$(this).addClass("actual").css("cursor", "text");
	$(".detalle #prodSpecs #mask div").hide();
	$(".detalle #prodSpecs #mask div:eq("+tabActual+")").show();
	return false;
}

// FUNCIONES PAGINACION
function paginacion(pag) {
	$("#p5").attr("value", pag);
	$("#frmPaginado").submit();
}



// FUNCIONES FILTROS
function toggleOpenClosedById(id) {
    var elem = document.getElementById(id);
    if (elem) {
        // See if the element has a class of 'closed'
        if ((' ' + elem.className + ' ').indexOf(' closed ') != -1) {
            // Replace the 'closed' part of the class with 'open'
            elem.className = elem.className.replace('closed', 'open');
        } else {
            // Replace the 'open' part of the class with 'closed'
            elem.className = elem.className.replace('open', 'closed');
        }
    }
}
function toggleDisplay(id) {
    var elem = document.getElementById(id);
    var disp = elem.style.display;
    if('none' != disp)
    {
        elem.style.display = 'none';
    }
    else
    {
        elem.style.display = 'block'
    }
}
function toggleArrowClass(src) {
    var elem = document.getElementById(src);
    var elemclass = elem.getAttributeNode('class').value;
    //alert(elemclass);
    if('productnav-toggle-rightarrow' == elemclass)
    {
        elem.setAttribute('class','productnav-toggle-downarrow');
        elem.className = 'productnav-toggle-downarrow';
    }
    else if('productnav-toggle-downarrow' == elemclass)
    {
        elem.setAttribute('class','productnav-toggle-rightarrow');
        elem.className = 'productnav-toggle-rightarrow';
    }
}


// FUNCIONES ARTICULOS
function dameInfoArticulo() {

   //$("#infoArticulo").html("<div id='msg_cart'><span class='success'>" + cargaArticulo + "</span></div>");
    $("#listSizes").html("<div id='msg_cart'><span class='success'>" + cargaArticulo + "</span></div>");

    $.ajax({
        type: "POST",
        url: strDirURL+"/ajax.articulo_descuento.asp",
        data: { productID: $("#id_article").val(), precio: $("#precio_compra").val(), precio_desc: $("#precio_descuento").val() },
        success: function(theResponse) {
            $("#oferta").html(theResponse);
        },
        error: function() {
            $("#oferta").html("<div id='msg_cart'><span class='error'>" + errorCargaArticulo + "</span></div>");
        }
    });
    $.ajax({
        type: "POST",
        url: strDirURL+"/ajax.articulo.asp",
        data: { productID: $("#id_article").val() },
        success: function(theResponse) {
            $("#infoArticulo").html(theResponse);
        },
        error: function() {
            $("#infoArticulo").html("<div id='msg_cart'><span class='error'>" + errorCargaArticulo + "</span></div>");
        }
    });

    $.ajax({
        type: "POST",
        url: strDirURL+"/ajax.articulo_medidas.asp",
        data: { productID: $("#id_article").val() },
        success: function(theResponse) {
            $("#listSizes").html(theResponse);
        },
        error: function() {
            $("#listSizes").html("<div id='msg_cart'><span class='error'>" + errorCargaArticulo + "</span></div>");
        }
    });                     
}

var menuSlider = function() {
    var m, e, g, s, q, i; e = []; q = 8; i = 8;
    return {
        init: function(j, k) {
            if (document.getElementById(j) != null) {
                m = document.getElementById(j);
                e = m.getElementsByTagName('li');
                var i, l, w, p; i = 0; l = e.length;
                for (i; i < l; i++) {
                    var c, v; c = e[i]; v = c.value; if (v == 1) { s = c; w = c.offsetWidth; p = c.offsetLeft }
                    c.onmouseover = function() { menuSlider.mo(this) }; c.onmouseout = function() { menuSlider.mo(s) };
                }
                g = document.getElementById(k);
                g.style.width = w + 'px'; g.style.left = p + 'px';
            }
        },
        mo: function(d) {
            clearInterval(m.tm);
            var el, ew; el = parseInt(d.offsetLeft); ew = parseInt(d.offsetWidth);
            m.tm = setInterval(function() { menuSlider.mv(el, ew) }, i);
        },
        mv: function(el, ew) {
            var l, w; l = parseInt(g.offsetLeft); w = parseInt(g.offsetWidth);
            if (l != el || w != ew) {
                if (l != el) { var ld, lr, li; ld = (l > el) ? -1 : 1; lr = Math.abs(el - l); li = (lr < q) ? ld * lr : ld * q; g.style.left = (l + li) + 'px' }
                if (w != ew) { var wd, wr, wi; wd = (w > ew) ? -1 : 1; wr = Math.abs(ew - w); wi = (wr < q) ? wd * wr : wd * q; g.style.width = (w + wi) + 'px' }
            } else { clearInterval(m.tm) }
        }
    };
} ();

function openOverlay(modal) {
    $(modal).overlay({
        effect: 'apple',
        fixed: false,
        top: 30
    }).load();
}

// note that this uses the .bind('load') on the window object, rather than $(document).ready() 
// because .ready() fires before the images have loaded, but we need to fire *after* because
// our code relies on the dimensions of the images already in place.
$(window).bind('load', function() {
    $('img.fade').cross();
});
