var slide_inicio_colecciones = 'off';
var type_i = 0;
var type_length = 0;
var paramlang = '';

$.fn.clearField = function() {
    return this.focus(function() {
        if( this.value == this.defaultValue ) {
            this.value = "";
        }
    }).blur(function() {
        if( !this.value.length ) {
            this.value = this.defaultValue;
        }
    });
};

var Home = {
	
	start: function(){
		var music_player = $(parent.document.getElementById('music_player'));
		//var fx_elements = $('#lang_bar, #header, /*#flash,*/ #footer');
		var fx_elements = $('#lang_bar, #header, #footer');
		if((!$.browser.msie)||($.browser.version!='6.0')){
			fx_elements.add(music_player);	
		}
		//$('#flash').show();
		fx_elements.css({
			opacity: 0
		});
		setTimeout(function(){
			fx_elements.animate({
				opacity: 1
			}, 2000, function(){
				//$('#content').css('backgroundImage', 'none');
			});
		},2000);
	}
	
}

var Empresa = {
	
	start: function(){
		Utiles.poner_scroll('#scroll_left');
		Utiles.pngFix();
	}
	
}

var Colecciones = {
	
	start: function(){
		//ricardo - ocultar el flash e iniciar secuencia
		$('#secuencia_ambientes').hide();
		var elementoide = $('##colecciones_left a').eq(0);
		elementoide.addClass('active');
		Utiles.toggle(elementoide);
                //cantidad de enlaces, necesario para hacer el bucle infinito
                type_length = $('#colecciones_left a').length -1; //no incluir aparadores
				//setTimeout(function(){$('#secuencia_inicio').cycle('resume');}, 1000);
				//$('#secuencia_inicio').cycle('resume');
				//slideshow de inicio
				$('#secuencia_inicio').cycle({
					fx: 'scrollLeft',
					duration: 6000,
					before: function(){
						//cambiamos el rollover de los enlaces con el slideshow
						elementoide = $('#colecciones_left a.active'); 
						elementoide.removeClass('active');
						Utiles.toggle(elementoide);
						elementoide = $('#colecciones_left a').eq(type_i) 
						elementoide.addClass('active');
						Utiles.toggle(elementoide);
						type_i++;
						if(type_i>=type_length)
							type_i = 0;
					}
				});
		//ricardo - fin
		Utiles.pngFix();
		Colecciones.my_over();
		//ricardo - fin
		$('#colecciones_mid').css('width', 20).children('ul').hide();
		$('#colecciones_left a').not('.ambientes').click(function(){
			$('#secuencia_ambientes').hide();
			//indice del elemento que se ha activado
			type_i = $('#colecciones_left a').index($(this));
			/**
			 * IMPORTANTE, ELIMINAR LO SIGUIENTE UNA VEZ SE HAYAN CREADO EN EL HTML TODAS LAS CAPAS "DETALLE" DE LAS COLECCIONES
			 */
			//forzamos el elemento a 0 porque solo hay una capa
			//type_i = 0;
			/*****************************************************************************/
			//ricardo - coger la categoría
			var thisString = "" + this;
			var categoria = thisString.substring(thisString.indexOf("#") + 1);
			//var imagen = $('#secuencia_inicio img').eq(type_i).clone();
			//alert(imagen.attr('src'));
			//var enlace = $('<a></a>');
			//alert(enlace.html());
			//enlace.attr('rel', 'aparadores').attr('href', imagen.attr('src'));
			//imagen.attr('style', '');
			//alert(enlace.attr('href'));
			//enlace.append(imagen);
			//alert(enlace.html());
			//cambio el fondo para que coincida con el de la categoría seleccionada
			//$('#secuencia_aparadores').empty();
			//$('#secuencia_aparadores').append(enlace);
			//ricardo - fin
	
			slide_inicio_colecciones = 'on';
			//paramos las secuencias
			$('#colecciones_right .secuencia').cycle('stop').hide();
			$('#nav').fadeOut('slow');
			//tamaño de la caja de colecciones determinado por el número de columnas
			var num_detalles = 0;
			//alert(num_detalles);
			//alert($('#aparadores').html());
			var colecciones_mid_tam = 40 + ( 75 * num_detalles );
			//ultima hora - la flechita
			$('#abre_detalles').css('cursor', 'pointer');
			$('#abre_detalles').click(function(){
				$('#colecciones_mid .detalles').css('display', 'block');
				var num_detalles2 = $('#colecciones_mid').children('.detalles').eq(0).children('ul').length;
				var colecciones_mid_tam2 = 40 + ( 75 * num_detalles2 );
				$('#colecciones_mid').animate({
					width: colecciones_mid_tam2
				}, 1000);
				//Colecciones.menuMuebles();
			});
			//fin ultima hora
			if(parseInt($('#colecciones_mid').css('width')) > 20){
				$('#colecciones_mid').animate({
					width: 20
				}, 1000, function(){
					//ricardo - llamada ajax - la hago antes porque necesito el número de muebles para saber el ancho al que desplegar
					//$('#colecciones_mid').load("/baltus/MuebleIndice.xhtml?test");
				    jQuery.ajax({
				         url:    '/baltus/MuebleIndice.xhtml?' + paramlang+ 'id=' +  categoria,
				         //url:    '/baltus/MuebleIndice.html',
				         success: function(result) {
				                      if(result.isOk == false) {
				                          alert(result.message);
				                      }
				                      else {
				                    	  //alert(result);
				                    	  //$('#aparadores').empty();
				                    	  //$('#aparadores').append(result);
				                    	  $('#aparadores').empty().append(result);
				                  		  Colecciones.my_over();
				                      }
				                  },
				         async:   false
				    }); 
					num_detalles = $('#colecciones_mid').children('.detalles').eq(0).children('ul').length;
					colecciones_mid_tam = 40 + ( 75 * num_detalles );
					//ricardo - fin llamada ajax

					$('#colecciones_mid').animate({
						width: colecciones_mid_tam
					}, 1000).children('ul').fadeIn('slow');
					Colecciones.menuMuebles();
				}).children('ul').fadeOut('slow');
			}else{
				//ricardo - llamada ajax - la hago antes porque necesito el número de muebles para saber el ancho al que desplegar
				//$('#colecciones_mid').load("/baltus/MuebleIndice.xhtml?test");
			    jQuery.ajax({
			         url:    '/baltus/MuebleIndice.xhtml?' + paramlang+ 'id=' +  categoria,
			         //url:    '/baltus/MuebleIndice.html',
			         success: function(result) {
			                      if(result.isOk == false) {
			                          alert(result.message);
			                      }
			                      else {
			                    	  //alert(result);
			                    	  //$('#aparadores').empty();
			                    	  //$('#aparadores').append(result);
			                    	  $('#aparadores').empty().append(result);
			                  		  Colecciones.my_over();
			                      }
			                  },
			         async:   false
			    }); 
				num_detalles = $('#colecciones_mid').children('.detalles').eq(0).children('ul').length;
				colecciones_mid_tam = 40 + ( 75 * num_detalles );
				//ricardo - fin llamada ajax
				$('#colecciones_mid').css('width', 20).animate({
					width: colecciones_mid_tam
				}, 1000, function(){
				}).children('ul').fadeIn('slow');	
				Colecciones.menuMuebles();
			}
			$('#secuencia_inicio').show().cycle(type_i).cycle('pause');
			elementoide = $('#colecciones_left a.active');
			elementoide.removeClass('active');
			Utiles.toggle(elementoide);
			$(this).addClass('active');
			Utiles.toggle($(this));
			return false;
		}).children('ul').hide();
		$('#colecciones_left a.ambientes').click(function(){
			//paramos las secuencias
			if(parseInt($('#colecciones_mid').css('width')) > 20){
				$('#colecciones_mid').animate({
					width: 20
				}, 1000, function(){
					$('#aparadores').empty();
					$('#colecciones_mid').css('width', 20);
					/*
					if (Utiles.isIE6()) {
						alert('ie6');
						$('#colecciones_mid').css('width', 0);
					}
					*/
				});
			}
			$('#secuencia_inicio').show().cycle(type_i).cycle('pause');
			elementoide = $('#colecciones_left a.active'); 
			elementoide.removeClass('active');
			$(this).addClass('active');
			Utiles.toggle($(this));
			$('#colecciones_right .secuencia').cycle('stop').hide();
			$('#secuencia_ambientes').show();
			$('#nav').empty();
			$('#nav').fadeIn('slow');
			$('#secuencia_inicio').hide();

			$('#secuencia_ambientes').cycle({
				fx: 'scrollLeft',
				pager: '#nav',
				duration: 6000
			});	

			$("#colecciones_right a[rel='ambientedetalle']").colorbox({
				slideshow:false,
				title:'AMBIENTES',
				cbox_cleanup: function(){
					$('#cboxClose').click(function(){
						$('#nav').empty();
						$('#secuencia_ambientes').cycle({
							fx: 'scrollLeft',
							pager: '#nav'
						})	
					})
				}
			}).click(function(){
				$('#secuencia_ambientes').cycle('stop');
			});

			return false;
		})
	},
	
	menuMuebles: function(){
		$('#colecciones_mid .detalles').css('display', 'block');
		$('#colecciones_mid li').css('cursor', 'pointer');
		$('#colecciones_mid li').click(function(){
			type_i = 0; //forzamos el elemento a 0
			$('#secuencia_inicio').hide();
			//ricardo - llamada ajax para cargar las imágenes del mueble
			var literal = $(this).attr('rel');
			var titulo = $(this).attr('title') + '.';
			//alert('cargando fotos mueble');
		    jQuery.ajax({
		    	 url:    '/baltus/MuebleFotos.xhtml?' + paramlang+ 'id=' +  literal,
		         success: function(result) {
		                      if(result.isOk == false) {
		                          alert(result.message);
		                      }
		                      else {
		                    	  //alert(result);
		                    	  $('#colecciones_right .secuencia').empty();
		                    	  $('#colecciones_right .secuencia').append(result);
		                    	  $('#colecciones_right .secuencia').show();
		                      }
		                  },
		         async:   false
		    });
			//ricardo - fin
			//alert('cerrando div detalles');
			$('#colecciones_mid').animate({
				width: 20
			}, 1000, function(){
				//alert('div detalles cerrado');
				$('#colecciones_mid .detalles').hide();
			});
			$('#nav').empty().fadeIn('slow');
			
			$('#secuencia_aparadores').animate({
				opacity: 1 //ricardo - esta animacion es un fix para que el cycle funcione tambien la primera vez
			}, 200, function(){
				$('#colecciones_right .secuencia').cycle({
					fx: 'scrollLeft',
					pager: '#nav',
					duration: 6000
				});	
			});
			
			/*$('#colecciones_right .secuencia').eq(type_i).show().cycle({
				fx: 'scrollLeft',
				pager: '#nav',
				duration: 6000
			});	*/
			$("#colecciones_right a[rel='fotodetalle']").colorbox({
				slideshow:false,
				title:titulo,
				cbox_cleanup: function(){
					$('#cboxClose').click(function(){
						$('#nav').empty();
						$('#colecciones_right .secuencia').eq(type_i).cycle({
							fx: 'scrollLeft',
							pager: '#nav'
						})	
					})
				},
				cbox_load: function(){
					//$("#music_player", top.document).hide();
					//alert($(top.frames[0]).css('height'));
					//alert(top.frames[0].style.height);
					//alert(top.frames[0].height);
					//$("iframe_principal", top.document).css('height', 1000);
					//alert($("iframe_principal", top.document).height);
					//alert(top.document.getElementById('iframe_principal').height);
					//top.document.getElementById('iframe_principal').height = 1000;
					//top.window.resizeIframe('iframe_principal');
				}
			}).click(function(){
				$('#colecciones_right .secuencia').cycle('stop');
			});
		});
	},
	
	my_over: function(){
		$('#colecciones_mid .detalles img').each(function(){
			$('<img>').attr('src', $(this).attr('src').replace(/.jpg/gi,'_over.jpg').replace(/.png/gi,'_over.png'));
		}).mouseover(function(){
			//$(this).attr('src', $(this).attr('src').replace(/.jpg/gi,'_over.jpg').replace('/.png/gi', '_over.png'));
			var elsrc = $(this).attr('src');
			var elrel = $(this).attr('rel');
			$(this).attr('rel', elsrc);
			$(this).attr('src', elrel);
		}).mouseout(function(){
			//$(this).attr('src', $(this).attr('src').replace(/_over.jpg/gi,'.jpg').replace('/_over.png/gi', '.png'));
			var elsrc = $(this).attr('src');
			var elrel = $(this).attr('rel');
			$(this).attr('rel', elsrc);
			$(this).attr('src', elrel);
		});
	}
	
}

var Diseno = {
    start: function(){
        Utiles.poner_scroll('#scroll_left');
        $('#listado_disenadores a, #listado_disenadores img').css('cursor', 'pointer').click(function(){
            element_type = this.tagName.toLowerCase()
            var indice_el = $('#listado_disenadores ' + element_type).index($(this));
            $('#detalles_disenadores').fadeIn('slow');
            $('#detalles_disenadores .jScrollPaneContainer').hide().eq(indice_el).show();
            $('#detalles_disenadores .detalle').hide().eq(indice_el).show();
            $('#detalles_disenadores li').css('opacity', 0.3).eq(indice_el).css('opacity', 1);
            Utiles.poner_scroll($('#detalles_disenadores .detalle').eq(indice_el));
            return false;
        });
        Utiles.pngFix();
    }
    
}

var Noticias = {
	    start: function(){
	        Utiles.poner_scrollIzquierdo('#scroll_listado_noticias');
	        if (($.browser.msie)) {
	        	$('#listado_noticias li').css('margin-bottom', '13px');
	        }
	        $('#listado_noticias a, #listado_noticias img').css('cursor', 'pointer').click(function(){
	            element_type = this.tagName.toLowerCase()
	            var indice_el = $('#listado_noticias ' + element_type).index($(this));
	            $('#detalles_noticias').fadeIn('slow');
	            $('#detalles_noticias .jScrollPaneContainer').hide().eq(indice_el).show();
	            $('#detalles_noticias .detalle').hide().eq(indice_el).show();
	            $('#detalles_noticias .fotos').hide().eq(indice_el).show();
	            //$('#detalles_noticias li').css('opacity', 0.3).eq(indice_el).css('opacity', 1);
	            Utiles.poner_scroll($('#detalles_noticias .detalle').eq(indice_el));
				$("#detalles_noticias .fotos:eq(" + indice_el + ") a[rel='fotodetalle" + indice_el + "']").colorbox({
					slideshow:false,
					next: '<img src="img/flechaderecha.gif"/>',
					previous: '<img src="img/flechaizquierda.gif"/>'
				});
	            return false;
	        });
	        Utiles.pngFix();
	    }
	    
}

var Showroom = {
	
	start: function(){
		$('#showroom_text .showroom_left').eq(0).show();
		Utiles.poner_scroll($('#showroom_text .showroom_left'));
        $('#showroom_text .jScrollPaneContainer').hide().eq(0).show();
        $('#showroom_paises li').eq(0).addClass('active');
		
		$('#showroom_pais').css('cursor', 'pointer').click(function(){
			$('#showroom_pais_seleccionado').hide();
			$('#showroom_paises').show();
		});
		
		$('#showroom_paises li').css('cursor', 'pointer').click(function(){
            var indice_el = $('#showroom_paises li').index($(this));
            $('#showroom_paises li').removeClass('active');
            $('#showroom_pais_seleccionado').html($(this).html());
			$(this).addClass('active');
			$('#showroom_paises').hide();
			$('#showroom_pais_seleccionado').show();
			
            $('#showroom_text').fadeIn('slow');
            $('#showroom_text .jScrollPaneContainer').hide().eq(indice_el).show();
            $('#showroom_text .showroom_left').hide().eq(indice_el).show();
		});
		$('.showspot').css('cursor', 'pointer').mouseenter(function(){
			var nombre = $(this).attr('id');
			nombre = "detalles" + nombre;
			$('#' + nombre).show();
		});
		$('.showspot').css('cursor', 'pointer').mouseleave(function(){
			var nombre = $(this).attr('id');
			nombre = "detalles" + nombre;
			$('#' + nombre).hide();
			/*setTimeout(function(){$('#' + nombre).hide();}
				, 1000);*/
		});
		
		//corrección de última hora
		Utiles.pngFix();
		
		/*Utiles.poner_scroll($('#tiendas_lista .detalle').eq(0));		
		($('#pais_lista a').eq(0)).addClass('active');
        $('#pais_lista a').css('cursor', 'pointer').click(function(){
            var indice_el = $('#pais_lista a').index($(this));
            $('#pais_lista a').removeClass('active');
			$(this).addClass('active');
            $('#tiendas_lista').fadeIn('slow');
            $('#tiendas_lista .jScrollPaneContainer').hide().eq(indice_el).show();
            $('#tiendas_lista .detalle').hide().eq(indice_el).show();
            //$('#tiendas_lista li').css('opacity', 0.3).eq(indice_el).css('opacity', 1);
            Utiles.poner_scroll($('#tiendas_lista .detalle').eq(indice_el));
            return false;
        });*/
		//Utiles.pngFix();
	}	

}

var Aviso_legal = {
	
	start: function(){
		Utiles.poner_scroll('#scroll_text');
	}
	
}

var Contacto = {
		
		start: function(){
			/* nada de autocompleter finalmente
			//Change this to the ID of the country input you want to be autocompleted
			//make sure to update the CSS for this ID as well
			var ac_country = "#pais";
		
			//options are the same as the JQuery Autocomplete plugin
			$(ac_country).autocomplete(countries, {
				minChars: 2,
				width: 320,
				matchContains: true,
				scroll: true,
				max:0,
				formatItem: function(row, i, max, term) {
					return "<img src='js/autocomplete/images/flags/" + row.code.toLowerCase() + ".gif'/> " + row.name;
				},
				formatResult: function(row) {
					return row.name;
				},
				formatMatch: function(row, i, max) {
					return row.name;
				}
			});
			
			$(ac_country).after($(ac_country).clone().attr('value','').attr('id', $(ac_country).attr('id') + '_hidden'));
			$(ac_country).removeAttr('name', '').clearField();
			$(ac_country).result(function(event, data, formatted) {
				if(data) {
					$(ac_country + '_hidden').val(data.code.toLowerCase());
				}
				var src = 'js/autocomplete/images/flags/' + data.code.toLowerCase() + '.gif';
				$(ac_country).css('backgroundImage', 'url(' + src + ')');
				$("#prefijo").attr('value', data.code);
			});
			*/
			$("#pais").css('cursor', 'pointer').click(function(){
				if ($("#marcopaises").is(":visible")) {
					$("#marcopaises").hide();
				}
				else {
					$("#marcopaises").show();
					Utiles.poner_scroll("#scrollpaises");
				}
			});
			$('#scrollpaises div').css('cursor', 'pointer').click(function(){
	            var indice_el = $('#scrollpaises div').index($(this));
	            $('#scrollpaises div').removeClass('active');
				$(this).addClass('active');
				$("#pais").attr("value", $(this).text());
				$("#prefijo").attr("value", $(this).attr("rel"));
				$("#marcopaises").hide();
			});
		}
		
	}

var Utiles = {
	
	poner_scroll: function(elemento){
		if(typeof(elemento) == 'string'){
			var elem = $(elemento);
		}else{
			var elem = elemento;
		}
		$(elem).jScrollPane({
			scrollbarWidth: 5,
			dragMinHeight: 10,
			dragMaxHeight: 10
		});
	},
	
	poner_scrollIzquierdo: function(elemento){
		if(typeof(elemento) == 'string'){
			var elem = $(elemento);
		}else{
			var elem = elemento;
		}
		$(elem).jScrollPane({
			scrollbarWidth: 5,
			dragMinHeight: 10,
			dragMaxHeight: 10,
			scrollbarOnLeft: true
		});
	},
	
	isIE6: function(){
		if (($.browser.msie) && ($.browser.version == '6.0')) {
			return true;
		}else{
			return false;
		}
	},
	
	pngFix: function(){
		if(Utiles.isIE6()){
			$('#content').not('.colecciones').pngFix();
		}
	},

	transfiereMusica: function(){
		if (top.window.frames[0]) {
			$('#toggleMusica').click(function(){
				if (top.window.frames[0].window.hayMusica) {
					top.window.frames[0].window.hayMusica = false;
					top.window.frames[0].window.musicaOff();
					$('#toggleMusica').css({
						'background-image': 'url(img/ecualizador.jpg)'
					})
				}
				else {
					top.window.frames[0].window.hayMusica = true;
					top.window.frames[0].window.musicaOn();
					$('#toggleMusica').css({
						'background-image': 'url(img/ecualizador.gif)'
					})
				}
			});
			if (top.window.frames[0].window.hayMusica) {
				$('#toggleMusica').css({
					'background-image': 'url(img/ecualizador.gif)'
				});
				top.window.frames[0].window.musicaOn();
			}
			/*
			else {
				$('#toggleMusica').css({
					'background-image': 'url(img/ecualizador.jpg)'
				});
			}*/
		}
	},
	
	musicaNo: function(){
		$('#player_volume_bar_value').css({
			width: 0
		})
		if (top.window.frames[0]) {
			top.window.frames[0].window.musicaOff();
		}
	},
	
	toggle: function(elementoJquery) {
		var elementoide = elementoJquery.children('img'); 
		var temp = elementoide.attr('rel');
		elementoide.attr('rel', elementoide.attr('src'));
		elementoide.attr('src', temp);
	}
}

$(function(){
	Utiles.transfiereMusica();
	if($('#main').hasClass('index')){
		Home.start();
	}else if($('#main').hasClass('empresa')){
		Empresa.start();
	}else if($('#main').hasClass('colecciones')){
		Colecciones.start();
	}else if($('#main').hasClass('avisolegal')){
		Aviso_legal.start();
	}else if($('#main').hasClass('diseno')){
		Diseno.start();
	}else if($('#main').hasClass('noticias')){
		Noticias.start();
	}else if($('#main').hasClass('showroom')){
		Showroom.start();
	}else if($('#main').hasClass('contacto')){
		Contacto.start();
	}
});


