var path = "http://www.elitegameroom.com.br/system/application/views/";
// função para o banner home
destaque = 0
function alterna(){
	$('.bannerHome ul li a').removeClass('ativo');
	$('.bannerHome ul li a:eq('+destaque+')').addClass('ativo');
	$('.imgBanner img:not(:eq('+destaque+'))').hide();
	$('.imgBanner img:eq('+destaque+')').fadeIn();
	destaque = destaque == 2 ? 0 : destaque += 1;
}
/////////////
// No Label //
//////////////
noLabel = {
	init: function(){
		$(".noLabel").each(function(){
			$(this).addClass("vazio");
			noLabel.buffer[$(this).attr("id")] = $(this).val();
			$(this).unbind('focus',noLabel.foco).unbind('blur',noLabel.desfoco).bind('focus',noLabel.foco).bind('blur',noLabel.desfoco);
		}).parents("form:eq(0)").unbind('submit',noLabel.formulario).bind('submit',noLabel.formulario);
	},
	
	buffer: {},
	
	foco: function(obj){
		obj = typeof($(obj).attr("id")) == "undefined" ? this : obj;
		if($(obj).hasClass("vazio")){
			if($(obj).is("textarea")){
				$(obj).html("");
			}else{
				$(obj).val("");
			}
			$(obj).removeClass("vazio");
		}
	},
	
	desfoco: function(){
		if($.trim($(this).val()) == ""){
			if($(this).is("textarea")){
				$(this).html(noLabel.buffer[$(this).attr("id")]);
			}else{
				$(this).val(noLabel.buffer[$(this).attr("id")]);
			}
			$(this).addClass("vazio");
		}
	},
	
	formulario: function(){
		$(".vazio",this).each(function(){
			noLabel.foco(this);
		});
		return true;
	}
}



/////////////////////////
// galeria de Imagens //
///////////////////////

$.extend({
	scrollPages: {
		version: 2.5,
		defaults: {
			elementSize: 50,
			elements: 3,
			speed: "slow",
			direction: "up"
		}
	}
});
$.fn.extend({
	scrollPages: function(options){
		options = $.extend({}, $.scrollPages.defaults, options);
		return this.each(function(){
			
			// Definições de variáveis
			var total = $(".scrollMask li",this).length;
			var mask = options.elementSize * options.elements;
			var area = options.elementSize * total;
			var animation = false;
			var obj = this;
			var dimension = options.direction == "left" ? "width" : "height";
			var side = new Array();
			side[0] = options.direction;
			side[1] = options.direction == "up" ? "down" : "right";
			
			$(".scrollButtom",this).css("visibility","visible");
			if(options.elements >= total){
				$(".scrollButtom",this).css("visibility","visible");
				mask = area;
			}else{
				$(".scrollButtom[rel*='"+options.direction+"']",obj).css("visibility","hidden");
			}
			
			// Aplicação de estilos
			if(options.direction == "up"){
				//$(".scrollMask",this).css({"height": mask + "px", overflow: "hidden"}); // M?scara
				$(".scrollMask ul",this).css({"height": area + "px", marginTop: 0}); // UL
				$(".scrollMask li",this).css({"height": options.elementSize + "px", display: "block"}); // LI
			}else{
				//$(".scrollMask",this).css({"width": mask + "px", overflow: "hidden"}); // M?scara
				$(".scrollMask ul",this).css({"width": area + "px", marginTop: 0}); // UL
				$(".scrollMask li",this).css({"width": options.elementSize + "px", display: "block"}); // LI
			}
			if (area <= mask) $(".scrollButtom",obj).css("visibility","hidden");
			//if (area <= mask + 596) $(".buttom2",obj).css("visibility","hidden");

			// Função que execulta a rolagem
			var rolagem = function(direction){

				// Variáveis
				var margem = -parseInt($(".scrollMask ul",obj).css("margin-"+(options.direction == "up" ? "top" : "left")));

				var intervalo = direction == side[1]
					? ( margem + ( mask * 2 ) ) < area
						? mask
						: area - (margem + mask)
					: ( margem - mask ) < 0
						? margem
						: mask
				;
				direction = direction == side[1]
					? -margem - intervalo
					: -margem + intervalo
				;
				
				$(".scrollButtom",obj).css("visibility","visible");
				var rel = -direction == 0 ? side[0] : (-direction + mask) == area ? side[1] : null;
				if(rel != null) $(".scrollButtom[rel*='"+rel+"']",obj).css("visibility","hidden");
				
				
				//Condição especial para galeria com degrade
				//var rel2 = -direction == 0 ? side[0] : (-direction + mask + 596) == area ? side[1] : null;
				//if(rel2 != null) $(".scrollButtom[rel*='"+rel2+"']",obj).css("visibility","hidden");
				
				// Animação
				animation = true;
				if(options.direction == "up"){
					$(".scrollMask ul",obj).animate({marginTop: direction + "px"},options.speed,function(){ animation = false; });
				}else{
					$(".scrollMask ul",obj).animate({marginLeft: direction + "px"},options.speed,function(){ animation = false; });
				}
			}
			
			// Aplicação de eventos
			$(".scrollButtom",this).unbind("click").click(function(){
				if(!animation){
					var direction = $(this).attr("rel");
					rolagem(direction);
				}
			});
		});
	}
});



////////
//ImageBox
////////////////
imB = function(){
	jQuery.ImageBox.init({loaderSRC:'imagens/carregando.gif', overlayOpacity: 0.8});
}

$(document).ready( function(){
	noLabel.init();
	imB();
	
///////////////////////////////////////////////	

/////////////////////////////
// Validar Form
///////////////////////////

	$('form').submit(function(){
		return validar.form($(this))
	});


//////////////////////////////////////
// Troca imagem detalhe do produto
/////////////////////////////////////////////
	
	/*$('.detalheThumbs li a').live('click',function(){
		var src = $(this).attr("rel");
		var title = $(this).attr("title");
		var ampliada = src.split('.jpg');
		
		$('.ampliar').attr('href',ampliada[0] + ".jpg")
		$('.ampliar img').attr('src',src).attr('alt',title).attr('title',title);
		
	});*/
	
	$('.detalheThumbs a').click(function(){
		var ampliar = $(this).attr('rel');
		//var imgGrande = url_site + ampliar.split("file=")[1]
		$('.carregando').show();
		imagem = new Image();
		imagem.onload = function(){
			$('.detalheProduto .ampliar img').attr('src',ampliar);
			$('.detalheProduto .ampliar').attr('href',ampliar);
			$('.carregando').hide();
			
			//var altura  = parseInt($('.vitrinePrincipal img').height());
//			var largura = parseInt($('.vitrinePrincipal img').width());		
//			var larguraMax = 378;
//			var alturaMax  = 256;
//			var calc = largura / altura
//			
//			if (calc < larguraMax / alturaMax && altura > alturaMax){
//				$('.vitrinePrincipal img').removeAttr('style').css({height:alturaMax})
//			}else if (largura > larguraMax){
//				$('.vitrinePrincipal img').removeAttr('style').css({width:larguraMax})
//			}
//
//			var margemEsq = (larguraMax - parseInt($('.vitrinePrincipal img').width())) / 2;
//			var margemTop = (alturaMax - parseInt($('.vitrinePrincipal img').height())) / 2;
			
	//		$('.vitrinePrincipal img').css({marginTop:margemTop,marginLeft:margemEsq}).fadeIn();
		}
		imagem.src = ampliar;
		return false;
	});
	//$('.detalheThumbs a:eq(0)').click()



///////////////////////
// Flash Home
/////////////////////
	
	$(".teaser").addFlash({src: path+"swf/teaser_working.swf", width: 980, height: 350, title: "Elite Game Room"});
//	$(".teaserHistorico").addFlash({src: "swf/flash-historico.swf", width: 952, height: 300, title: "Tabacow - História"});
//	$(".unico").addFlash({src: "swf/apresentacao-unico.swf", width: 952, height: 600, title: "Tabacow"});

///////////////////////

// slider Simulador
////////////////////////

	//$('.sliderMod').scrollPages({elementSize:98, elements:9, direction:'left'});
	

////////////////////////////////////////
// select estilizado
/////////////////////////////////////////
	/*$('#myselectbox').selectbox({
        	onChangeCallback: myFunction
    	});
    
	function myFunction(args)
	{
		$('span.change').append(args.selectedVal);
	}
	
	
	$('#myselectbox1').selectbox({
		inputClass: 'selectbox1'
	});
	
	
	$('#myselectbox2').change(function(){
      		switch($('#myselectbox2').val()){
      			case 'opt1':
      			case 'opt2':
      			case 'opt3':
      			$('#texttochange').html('Group 1');
      			break;
      			case 'opt4':
      			case 'opt5':
      			case 'opt6':
      			$('#texttochange').html('Group 2');
      			break;
      			case 'opt7':
      			case 'opt8':
      			case 'opt9':
      			case 'opt10':
      			$('#texttochange').html('Group 3');
      			break;
      		}
      	});
	$('#myselectbox2').selectbox({
		inputType: 'span',
		inputClass: 'selectbox2',
		containerClass: 'selectbox2-wrapper',
		loopnoStep: true
	});*/

////////////
// Select //
////////////
estiloSelect = {
	init: function(){
		var primeiro = 0;
		$("select.select").each(function(){
			var html =  '<div id="' + $(this).attr("id") + '" class="' + $(this).attr("class") + '">';
				html += '	<div class="ativo"></div>';
				html += '	<input id="' + $(this).attr("id") + '_select" name="' + $(this).attr("name") + '" type="hidden" value="" />';
				html += '	<div class="options">';
				html += '	<ul>';
				for(i=0;i<$("option",this).length;i++){
					html += '<li>	<a href="javascript:void(0);" title="' + $("option:eq(" + i + ")",this).text() + '" rel="' + $("option:eq(" + i + ")",this).attr("value")+ '">' + $("option:eq(" + i + ")",this).text() + '</a></li>';
				}
				html += '</ul>';
				html += '</div>';
				html += '</div>';
			
			$("option",this).each(function(i){
				primeiro = this.selected ? i : primeiro;
			});
			
			$(this).replaceWith(html);
			
		});
		//ESCONDE A PRIMEIRA LI QUE REPETIA E EXIBIA O TEXTO CLICADO
		$('.options > ul').each(function(){
			$(this).children('li:first').hide();
		});
		
		$("div.select").css("visibility","visible").each(function(){
			var altura = $("a",this).length -1;
			altura = altura > 5 ? 5 : altura;
			alturaOpt = isNaN($("a:first",this).css("height")) ? 18 : $("a:first",this).css("height");
			altura = alturaOpt * altura
			$(".options",this).css({height:altura + "px", visibility:"visible", display:"none"});
			estiloSelect.change(this,primeiro);
		})
		$("div.select").each(function(){
			$("a", this).each(function(i){
				$(this).unbind().click(function(){
					estiloSelect.change($(this).parents("div.selector:eq(0)"),i);
				});
			});
		});
		$("div.select .ativo").click(function(){estiloSelect.abre(this);});
	},
	abre: function(obj){
		$(obj).parent().parent().parent().css("z-index","3");
		$(obj).unbind('click').siblings(".options").slideDown('fast',function(){
			$("html").unbind('click').bind('click',estiloSelect.fecha);
			$("div.select .ativo").unbind('click');
		});
	},
	change: function(obj,option){
		$("a.optionAtivo",obj).removeClass("optionAtivo");
		$("a:eq(" + option + ")",obj).addClass("optionAtivo");
		var texto = $("a:eq(" + option + ")",obj).text();
		var valor = $("a:eq(" + option + ")",obj).attr("rel");
		$(".ativo",obj).html(texto);
		$("input[name!='url']",obj).val(valor);
		estiloSelect.fecha();
	},
	
	fecha: function(){
		$("div.select .options:visible").slideUp('fast',function(){$(this).parent().parent().parent().css("z-index","2")});
		$("html").unbind('click', estiloSelect.fecha);
		$("div.select .ativo").unbind('click').click(function(){estiloSelect.abre(this)});
	}
}



$(document).ready( function(){
	noLabel.init();
	estiloSelect.init();

	/* Valida os formulários */
        $(".btn_enviar, .btn_enviarOrcamento").click(function(){
            var f = new Array();
            var i = 0;
			var e = false;
            $("#frmContato input:text,textarea").each(function(){
                if($.trim($(this).val()) === ''){
                    f[i] = $(this).attr('name');
					e = true;
                }
                i++;
            });
            var n = f.join(', ');
            if(e === true){
				alert('Preencha os campos: '+n+'.');
				return false;
			}
        })
        
        
/////////////////////////////////////	
// Centraliza Menu Footer
/////////////////////////////
	$('#footer ul').each(function(){
		var larguraDiv = $(this).parent().width();
		var larguraUl = $(this).width();
		
		var margem = larguraDiv / 2 - larguraUl / 2;
		$(this).css('margin-left',margem+'px');
	})


/////////////////////////
// abre box flutuante //
///////////////////////

	//abre box flutuante
	$(".detalheProduto a.abreBox").click(function(){
		var src=$(this).children("img").attr('src');
		$("#boxGranImg").attr('src',src);
		bloqueia({ speed: "fast", bgColor: "#000" });
		$(".boxApresentaProd").absoluteCenter({animation:false}).absoluteCenter().show();
		var alturaEle = $('.imgPrimario').children('img').height();
		var alturaUl = $('.imgPrimario').height();
		var margem = alturaUl / 2 - alturaEle / 2;
		$('.imgPrimario').children('img').css('margin-top',margem+'px');
	});
	//fecha box flutuante 
	$(".fechaBloqueio, .imgPrimario, #bloqueio").click(function(){
		$(".boxApresentaProd").hide();
		bloqueia({ speed: "slow", evento: "fim" });
		$(window).unbind("scroll");
		$(window).unbind("resize");
	});
	
	$(".thumbFoto").click(function(){
		var src=$(this).attr('src');
		$('.imgPrimario img').fadeOut('fast',function(){
			$("#boxGranImg").attr('src',src);
			var alturaEle = $('.imgPrimario').children('img').height();
			var alturaUl = $('.imgPrimario').height();
			var margem = alturaUl / 2 - alturaEle / 2;
			$('.imgPrimario').children('img').css('margin-top',margem+'px');
			$('.imgPrimario img').fadeIn('fast');
		});
	});
	
///////////////////////////////
// abas Simulador
/////////////////////////////

	$('.sliderMod .scrollMask a').click(function(){
		$('.sliderMod .scrollMask a').removeClass('ativo');
		$(this).addClass('ativo');
		var mod = '';
		if($(this).attr('rel') == 'mod1'){
			mod = 'simulador-mod1.php'
		}
		if($(this).attr('rel') == 'mod2'){
			mod = 'simulador-mod2.php'
		}
		if($(this).attr('rel') == 'mod3'){
			mod = 'simulador-mod3.php'
		}
		if($(this).attr('rel') == 'mod4'){
			mod = 'simulador-mod4.php'
		}
		if($(this).attr('rel') == 'mod5'){
			mod = 'simulador-mod5.php'
		}
		if($(this).attr('rel') == 'mod6'){
			mod = 'simulador-mod6.php'
		}
		if($(this).attr('rel') == 'mod7'){
			mod = 'simulador-mod7.php'
		}
		if($(this).attr('rel') == 'mod8'){
			mod = 'simulador-mod8.php'
		}
		
		$.ajax({
			url: 'includes/'+mod
			,success:function(ret){
				$('.conteudoSimulador').html(ret);
				
				$('.escolheCor table a').click(function(){
					
					if($(this).parents('td').siblings('td').children('a').attr('class') == 'ativo'){
						return false;
					}
					if($(this).attr('name') == 'col1'){
						$('.escolheCor table a[name="col1"]').removeClass('ativo')	
					}
					if($(this).attr('name') == 'col2'){
						$('.escolheCor table a[name="col2"]').removeClass('ativo')	
					}
					if($(this).attr('name') == 'col3'){
						$('.escolheCor table a[name="col3"]').removeClass('ativo')	
					}
					$(this).addClass('ativo');
					var cod1 = $('.escolheCor table a.ativo[name="col1"]').attr('rel');
					var cod2 = $('.escolheCor table a.ativo[name="col2"]').attr('rel');
					var cod3 = $('.escolheCor table a.ativo[name="col3"]').attr('rel');
					
					$('.mostraFoto img').attr('src',"images/simulador/fotos/unico-"+cod1+"-"+cod2+".jpg");
					if ($('.escolheCor table a.ativo[name="col3"]').is('a')){
						$('.mostraFoto img').attr('src',"images/simulador/fotos/unico-"+cod1+"-"+cod2+"-"+cod3+".jpg");
					}
				});
			}	
		});	
	});
	
///////////////////////////////////
// Troca Foto Simulador
//////////////////////////////////

	$('.escolheCor table a').click(function(){
		
		if($(this).parents('td').siblings('td').children('a').attr('class') == 'ativo'){
			return false;
		}
		if($(this).attr('name') == 'col1'){
			$('.escolheCor table a[name="col1"]').removeClass('ativo')	
		}
		if($(this).attr('name') == 'col2'){
			$('.escolheCor table a[name="col2"]').removeClass('ativo')	
		}
		if($(this).attr('name') == 'col3'){
			$('.escolheCor table a[name="col3"]').removeClass('ativo')	
		}
		$(this).addClass('ativo');
		var cod1 = $('.escolheCor table a.ativo[name="col1"]').attr('rel');
		var cod2 = $('.escolheCor table a.ativo[name="col2"]').attr('rel');
		var cod3 = $('.escolheCor table a.ativo[name="col3"]').attr('rel');
					
		$('.mostraFoto img').attr('src',"images/simulador/fotos/unico-"+cod1+"-"+cod2+".jpg");
		if ($('.escolheCor table a.ativo[name="col3"]').is('a')){
			$('.mostraFoto img').attr('src',"images/simulador/fotos/unico-"+cod1+"-"+cod2+"-"+cod3+".jpg");
		}
	});

	});
	
});
