var flagClose = true;

if(navigator.userAgent.match(/AppleWebKit/i) && navigator.userAgent.match(/Mobile/i)) {
	window.location.replace('iphone/');
}

$(window).load(function(){        
    $(".btFechar").click(function(){
        closeBox($(this).parents("#boxModal"));
        return false;
    });
    $("#mnHome").click(function(){
        if($("#boxModal").css("display") == "block"){
            closeBox($("#boxModal"), true);
            flagClose = false;
        }
        return false;
    });
    
    initDisplay();

	$(".menu_bottom li a").not(".btTestDrive").click(function(){
		$(".menu_bottom").find("li a").removeClass("ativo");
		$(this).addClass('ativo');	
	});

});

function closeBox(objClose, statusHome){
    if(timeSlideShow) clearTimeout(timeSlideShow); 
    $(objClose).animate({
        opacity: 0
        },200, function(){
            flagClose = true;
            $("#auxBoxModal").html("");
            $("#boxModal").css("display","none");
            if(statusHome)
                $("#home").animate({opacity: 1},200);
        }
    );
}

function openFlashCambio(){
    $("#home").animate({
        opacity: 0
        },200, function(){
			var divBan = document.createElement("div");
			$(divBan).attr({id:"bannerHome"});
			$(divBan).insertBefore("#content");

			var so = new SWFObject("/swf/simulator/main.swf", "", "100%", "100%", "8", "#000000", true);
			so.addParam("pluginspage", "http://www.macromedia.com/go/getflashplayer");
			so.write("bannerHome");  

			$('#bannerHome object').focus();
			mute();
        }
    );
    return false;
}

function closeFlashCambio(){
	$("#bannerHome").remove();
	unmute();
	pageTracker._trackPageview('/cambio/sairdosimulador');
}

function initDisplay(place){
	if(!place) {
		place = $("body");
	}
	$(place).find(".menuDisplay a").not(".btTestDrive, .btImpressas").click(openSection);

//	$(place).find(".menuDisplay a").not(".btImpressas").click(openSection);
	
	$(place).find('.btMenu').click(function(){
		openMenu();
		return false;
	});
}

function openSection(e, context) {
	//removendo box de imagem
	$(".boxImg").remove();

	var url = $(context != null ? context : this).attr("href");
	$("#home").animate({
		opacity: 0
		},100, function(){
			menuDisplay(url);
			openHTML();
			if (url != null && url.indexOf('/campanha/campanha_tv') > -1) {
				mute();	 
			} else {
				halfVolume();
			}
		}
	);
	return false;
}

function menuDisplay(url){
    if(url == null || url == "home"){
        if($("#boxModal").css("display") == "block") closeBox($("#boxModal"));
    }else{    
        $("#boxModal").css("display","block");
        if(flagClose){
            $("#boxModal").animate({
                opacity: 1
                },100, function(){
                    var divLoader = loader(true);
                    $(divLoader).insertBefore("#auxBoxModal");
                    
                    executeAjax({type:"GET" ,url:url, call:"responseNavegacao"});
                }
            );
            flagClose = false;
        }else{
            $("#auxBoxModal").animate({
                opacity: 0
                },100, function(){
                    $("#auxBoxModal").html("");
                    var divLoader = loader(true);
                    $(divLoader).insertBefore("#auxBoxModal");
                       
                    executeAjax({type:"GET" ,url:url, call:"responseNavegacao"});
                }
            );
        }
    }

	if(url == ''){
		url = '/entrada';
	}
	pageTracker._trackPageview(url);
}

var responseAjax = null;
function executeAjax(options){
    $.ajax({
		type: options.type,
   		url: options.url,
        data: options.data,
   		success: function(response){
            responseAjax = response;
            eval(options.call + "('" + options.url + "')");
		}
	});
}

function responseNavegacao(url){
    loader(false);
    $("#auxBoxModal").html(responseAjax);
    $("#auxBoxModal").animate({
        opacity: 1
        },200
    );
    inits(url);
}

function responseImagens(){
    loader(false);
    $(".boxImg").html(responseAjax);
    var img = document.createElement("img");
    $(img).attr({src:$(".boxImg")[0].urlImg, width:612, height:242});
    $("#auxImgModal").append(img);
    
    $(".boxImg .btFechar").click(function(){
        $(".boxImg").remove();
        return false;
    });
}

function inits(url){
    initDisplay($("#boxModal"));
    initMenu();
    //initToolTip();
    //initFotos();
    initIndique();
    initGaleria();
    initCampanha(url);
}

function loader(status){
    if(status){
        var loader = document.createElement("img");
        var divLoader = document.createElement("div");
        $(loader).attr({src:"/dualogic/img/loader.gif"});
        $(divLoader).addClass("loader").append(loader);
        
        return divLoader;
    }else{
        $(".loader").remove();
    }
}

function initFotos(){
    $(".btFotos").click(function(){
        $(".boxImg").remove();
        
        var divImg = document.createElement("div");        
        var divLoader = loader(true);
        
        divImg.urlImg = $(this).attr("href");
        $(divImg).addClass("boxImg").append(divLoader);
        $("body").append(divImg);
        
        executeAjax({url:"/popFotos", type:"GET", call:"responseImagens"});
        
        return false;
    });
    
}

function initIndique(){
    var container = $("div#messageError");

    $("#frmIndique").validate({
 		errorContainer: container,
		errorLabelContainer: $("ul", container),
		wrapper: "li",
        submitHandler: function(form) {
        	
        	var data = "";
	        $(form).find("input,textarea").each(function() {
	        	if(data != "") {
		        	data += "&";
		        }
		        var n = $(this).attr("name");
		        var v = $(this).attr("value");
		        if(n != undefined) data += n + "=" + (v == undefined ? "" : escape(v));
	        });
			executeAjax({type:"POST", url:$(form).attr("action"), call:"responseNavegacao", data:data});
			
			return false;
		},
		rules: {
			"nomeRemetente": "required",
        	"emailRemetente": {
          		required: true,
				email:true
         	},
            "nomeDestinatario1": "required",
        	"emailDestinatario1": {
          		required: true,
				email:true
         	},
        	"emailDestinatario2": {
				email:true,
                requiredIf: $("#nomeDestinatario2")
         	},
        	"emailDestinatario3": {
				email:true,
                requiredIf: $("#nomeDestinatario3")
         	}
		},
		messages: {
	   		"nomeRemetente": "Preencha o nome",
        	"emailRemetente": {
          		required: "Preencha o e-mail",
				email: "E-mail inv&aacute;lido"
         	},
            "nomeDestinatario1": "Preencha o nome do amigo",
        	"emailDestinatario1": {
          		required: "Preencha o e-mail do amigo",
				email: "E-mail do amigo inv&aacute;lido"
         	},
        	"emailDestinatario2": {
				email: "E-mail do amigo 2 inv&aacute;lido",
                requiredIf: "Preencha o e-mail do amigo 2"
         	},
        	"emailDestinatario3": {
				email: "E-mail do amigo 3 inv&aacute;lido",
                requiredIf: "Preencha o e-mail do amigo 3"
         	}
		}
	});    
}

function initCampanha(url) {
	var videoURL = null;
	if(url.indexOf("campanha_tv1") > -1) {
		videoURL = "/flv/site/campanha/homem.flv";
	} else if(url.indexOf("campanha_tv2") > -1) {
		videoURL = "/flv/site/campanha/amigo.flv";
	}
	if(videoURL != null) {
		var so = new SWFObject("/swf/site/videoplayer.swf", "", "525", "335", "8", "#000000", true);
		so.addVariable("videoURL", videoURL);
		so.addParam("pluginspage", "http://www.macromedia.com/go/getflashplayer");
		so.write("player_campanha");
	}
}

function initToolTip(){    
    $(".destaqueTecnologia a").mouseover(function(){
        var divToolTip = document.createElement("div");      
        var top = this.offsetTop;
        var left = this.offsetLeft + this.offsetWidth;
        
        $(divToolTip).addClass("toolTip").css({top:top, left:left}).html($(this).html());
        $(this).parents(".destaqueTecnologia").append(divToolTip);
       
        $(divToolTip).show("fast");
        this.objTool = divToolTip;
    });
    $(".destaqueTecnologia a").mouseout(function(){
        $(this.objTool).remove();          
    });
}

function initMenu(){
    //MENU
    $(".alternaItens .itemMenu:eq(0)").show();    
    $(".menuAlternaItem li a").each(function(index, value) {
		this.idItem = index;
	});
    
    $(".menuAlternaItem li a").click(function(){
        alternaMenu(this.idItem);
        return false;
    });
}

function alternaMenu(item){
    //removendo box de imagem
    $(".boxImg").remove();
    
    $(".alternaItens .itemMenu").hide();
    $(".menuAlternaItem").find("li a").removeClass("ativo");
    $(".menuAlternaItem li a:eq("+ item +")").addClass("ativo");
    $(".alternaItens .itemMenu:eq("+ item +")").css("display","block");
    
    // show/hide pdf button
    if(item == 0) {
    	$(".box_botoes a:eq(1)").show();
    } else {
	    $(".box_botoes a:eq(1)").hide();
    }
    
    return false;
}


var timeSlideShow = null;

function initSlideShow(listImg){
    $("#controleSlide").click(function(){
        if(this.controle) this.controle = false;
        else this.controle = true;
               
        //animate da galeria         
        if(this.controle) {
            percorreSlide();
            $(this).addClass("btControleStop");
        }else{
            clearTimeout(timeSlideShow);
            $(this).removeClass("btControleStop");
        }
        
        return false;   
    });
    
    $(".btAntSlideShow").click(function(){
       $(".alternaImg a:eq(0)").click();
       
       $(".boxGaleria").find(".boxGaleriaMascAux").animate({left:0},"fast");
       
       return false;  
    });
    
    $(".btProSlideShow").click(function(){
       $(".alternaImg a:last").click();
       
       var teste = $(".alternaImg a img:last")[0].offsetLeft / $(".boxGaleria")[0].widthAdd;
       var range = parseInt(teste) * $(".boxGaleria")[0].widthAdd;
        
       $(".boxGaleria").find(".boxGaleriaMascAux").animate({left:-range},"fast");
        
       return false;  
    });
    
    $(".alternaImg a").mouseover(function(){
        $(this).find("img").animate({opacity: 1},"fast");
    });
    
    $(".alternaImg a").mouseout(function(){
        if($("#imgGaleria")[0].imgCurrent != this.idItem){
				if($(this).attr('class') != 'on'){
					$(this).find("img").animate({opacity: 0.5}, "fast");			
				}
		  }
    });
}

function percorreSlide(){    
    indexSlide = $("#imgGaleria")[0].imgCurrent;
    $("#galeriaCurrent").html(indexSlide+1);
    
    $(".alternaImg a img").css({opacity: 0.5});    
    $(".alternaImg a img:eq("+ indexSlide +")").animate({opacity: 1},"fast");
    
    var top = $(".boxGaleria").find(".boxGaleriaMascAux").css("top");
    top = parseInt(top.substring(0,top.length-2));

    var teste = $(".alternaImg a img:eq("+ indexSlide +")")[0].offsetTop / $(".boxGaleria")[0].heightAdd;
    var range = parseInt(teste) * $(".boxGaleria")[0].heightAdd;
    
    if(range != top){
        animateProx(-range);
    }
    
    $("#imgGaleria").animate({
        opacity: 0
        },600, function(){
            $("#imgGaleria").attr("src",listImg[indexSlide].src);
            $("#imgGaleria").animate({
                opacity: 1
                },600);
            if($("#controleSlide")[0].controle)
                timeSlideShow = setTimeout("percorreSlide()",3000);      
    });
    
    if(listImg.length > (indexSlide+1)) {
		$("#imgGaleria")[0].imgCurrent = indexSlide+1;
    } else {
		$("#imgGaleria")[0].imgCurrent = 0;
    } 
}

function initGaleria(){
    $("#galeriaTotal").html($(".alternaImg a").size());
    if($("#imgGaleria").length > 0) {
    	$("#imgGaleria")[0].imgCurrent = 0;
    }
    //Carrega Imagens
    listImg = new Array();    
    $(".alternaImg a").each(function(index, value) {
        this.idItem = index;
        
        var imgGal = document.createElement("img");
        $(imgGal).attr({src:$(this).attr("href"), width:$("#imgGaleria").attr("width"), height:$("#imgGaleria").attr("height")});
           
        listImg.push(imgGal);
	});
    
	initSlideShow(listImg);
    
    // ALTERNA IMAGENS
    $(".alternaImg a").click(function(){         
        var urlImg = $(this).attr("href");

  		  $(".alternaImg a").removeClass('on');
		  $(".alternaImg a img").css('opacity', '0.5');
		  
        if($(".boxGaleria").size() == 0){
            var imgClone = $(listImg[this.idItem]).clone();
            
            $($(listImg[this.idItem]).attr({id:"imgGaleriaClone"})).insertBefore("#imgGaleria");
            listImg[this.idItem] = imgClone;
            
            $("#imgGaleria").animate({
                    opacity: 0
                },600, function(){
                $("#imgGaleria").remove();
                $("#imgGaleriaClone").attr({id:"imgGaleria"});   
            });

				$(this).addClass('on');
				$(this).find("img").css('opacity', '1');

        }else{
            //animate da galeria
            $("#imgGaleria")[0].imgCurrent = this.idItem;
            $("#galeriaCurrent").html(this.idItem+1);
            $(".alternaImg a img").animate({opacity: 0.5},"fast");
            $(this).find("img").animate({opacity: 1},"fast");
            

				
            $("#imgGaleria").animate({
                opacity: 0
                },600, function(){
                    $("#imgGaleria").attr("src",urlImg)
                    $("#imgGaleria").animate({
                        opacity: 1
                        },600);        
            });
        }
        
        infoGaleria(this);   
        return false;
    });
    
    $(".alternaImg a img").css({position:"relative"});
    galeriaHor();
}

function infoGaleria(objA) {
    if($(".infoDestaqueGaleria").size() != 0){
        $(".infoDestaqueGaleria").html("");
        var h3 = document.createElement("h3");
        $(h3).html($(objA).find("img").attr("title"));
        
        var divT = document.createElement("div");
        $(divT).html($(objA).find("img").attr("alt"));
        
        $(".infoDestaqueGaleria").append(h3);
        $(".infoDestaqueGaleria").append(divT);            
    }
}

function galeriaHor(){
    // GALERIA DE IMAGENS
    if($(".boxGaleria").size() != 0){
        $(".boxGaleria")[0].heightAdd = $(".boxGaleria").find(".boxGaleriaMasc")[0].offsetHeight;
        $(".boxGaleria")[0].height = $(".boxGaleria").find(".boxGaleriaMascAux .boxGaleriaAux")[0].offsetHeight;
        $(".boxGaleria")[0].controle = true;
    }
    
	$(".btProximo").click(function() {
		var heightAdd = $(this).parents(".boxGaleria")[0].heightAdd;
		var height = $(this).parents(".boxGaleria")[0].height;
        
		var top = $(this).parents(".boxGaleria").find(".boxGaleriaMascAux").css("top");
		top = parseInt(top.substring(0,top.length-2));        
        
		if(height - heightAdd > (top *(-1))){            
            animateProx(top - heightAdd);
		}
		return false;
	});
	
	$(".btAnterior").click(function() {
		var heightAdd = $(this).parents(".boxGaleria")[0].heightAdd;
        
		var top = $(this).parents(".boxGaleria").find(".boxGaleriaMascAux").css("top");
		top = parseInt(top.substring(0,top.length-2));
        
		if(top != 0){
			$(this).parents(".boxGaleria").find(".boxGaleriaMascAux").animate({
				top: top + heightAdd
				},"slow"
			);
		}
		return false;
	});
}

function animateProx(range){
    $(".boxGaleria")[0].controle = false;
    $(".boxGaleria").find(".boxGaleriaMascAux").animate({
        top: range
        },"slow",function(){                    
            $(this).parents(".boxGaleria")[0].controle = true;   
        }
    );
}

function zebrarDL(obj){
	$("dl" + obj + " dd:odd").addClass("z2");
	$("dl" + obj + " dd:even").addClass("z1");
}

function versoesPrint(obj){
	pageTracker._trackPageview('/versaoimpressao/' + obj + '/' + $('.itemMenu:visible h2').attr('title'));
	print();
}

function openMenu(){
	if($("#content").css('top') == '-618px'){
		$("#content").animate({ top: -594 }, 500);
	}else{
		closeMenu();
	}
}		

function closeMenu ( skipVolumeNormalize ){
	$("#auxBoxModal").html("");
	$("#content").animate({ top: -618 }, 500);
	$(".menu_bottom").find("li a").removeClass("ativo");
	
	if ( !skipVolumeNormalize ) {
		normalVolume();
	}
}		

function openHTML(){
	if($("#content").css('top') != '0px'){
		if($('body').height() < '600'){
			$("#content").animate({ top: -90 }, 500);
		}else{
			$("#content").animate({ top: 0 }, 500);
		}
	}
}

function closeGame(){
	$("#game").remove();
	$("#container #flashSite")[0].SetVariable("js2fl_backToHome", "exec");
}

function mute() {
	$("#container #flashSite")[0].SetVariable("js2flash", "mute");
}

function unmute() {
	$("#container #flashSite")[0].SetVariable("js2flash", "unmute");
}

function halfVolume() {
	$("#container #flashSite")[0].SetVariable("js2flash", "halfVolume");
}

function normalVolume() {
	$("#container #flashSite")[0].SetVariable("js2flash", "normalVolume");
}


function fundo(status) {
	if(status){
		var elementFund = document.createElement("div");
		elementFund.className = "fundo";
		elementFund.setAttribute("id","divFundo");
		elementFund.style.width = document.body.offsetWidth + "px";
		elementFund.style.height = document.body.offsetHeight + "px";
		
		$("body").css({padding:"0px"});
		$("body").append(elementFund);
	}else{
		$("div").remove("#divFundo");
		$("body").css({padding:"50px 0 0 0"});
	} 
}	

function openGame(playerType){
	if(!$('#game').is(':visible')){
		var divBan = document.createElement('div');
		$(divBan).attr({id:'game'});
		$(divBan).insertBefore('#content');

		var so = new SWFObject("/swf/game/index.swf?v=4", "flashGame", "100%", "100%", "8", "", true);
		so.addVariable("playerTypeVar", (playerType==1 ? "angel" : "devil"));
		so.addVariable("serverVar", "rtmp://fms.fiatpunto.mobi/stilodualogic_v2");
		so.useExpressInstall("/swf/expressinstall.swf");
		so.addParam("pluginspage", "http://www.macromedia.com/go/getflashplayer");
		so.addParam("wmode", "transparent");
		so.write("game");
	}
	closeMenu( true );
}

function gameConhecaCambio() {
	openSection(null, $(".mn_cambio_dual a"));
	closeGame();
}

function trackPageview(tag) {
	pageTracker._trackPageview(tag);
}