var isOpen = false, isIE78 = false;

$(document).ready(function(){
	if ($.browser.msie&&$.browser.version < 9) isIE78 = true;
	
	$('#txtPesquisar').focus(function (){ 
		$(this).addClass("has-focus"); 
	}) ;
	$('#txtPesquisar').blur(function (){ 
		$(this).removeClass("has-focus"); 
	});
	$(window).keyup(function(e) {
		if(e.keyCode == 13) {
			if($('#txtPesquisar').is(".has-focus")) SearchGeral();
		}
	});
	
	/* header */
	var headMenuBigDiv = $(".header-menu > ul.big > li > div"), headTopoDiv = $(".header-topo > ul > li > div");
	if (isIE78){
		/* header topo */
		$("#siteNewsletter").mouseenter(function(){
			headTopoDiv.not('#headTopSiteNews').hide();
			$(this).next().css({'z-index': 100000, 'display': 'block'});
			headMenuBigDiv.hide();
		});
		$("#siteRecomenda").mouseenter(function(){
			headTopoDiv.not('#headTopSiteRecom').hide();
			$(this).next().css({'z-index': 99990, 'display': 'block'});
			headMenuBigDiv.hide();
		});
		$(".header-menu, .header-topo li, .sub-channels, .body, .flash, .header-topo > .search").not('#headTopSiteNews,#headTopSiteRecom').mouseenter(function(){
			headTopoDiv.hide();
		});
		$(".container-top").mouseleave(function(){
			headTopoDiv.hide();
			headMenuBigDiv.hide();
		});
		/* header menu */
		$(".header-menu > ul.big > li > a").mouseenter(function() {
			headMenuBigDiv.hide();
			headTopoDiv.hide();
			if($(this).next().children("ul").children("li").length > 0) $(this).next().show();
		});
		$(".header-menu > a, .header-topo, .sub-channels, .body, .flash").mouseenter(function(){
			headMenuBigDiv.hide();
		});			
	} else {
		/* header topo */
		$("#siteNewsletter").mouseenter(function(){
			headTopoDiv.not('#headTopSiteNews').stop().fadeOut();
			$(this).next().css('z-index', 100000).stop().fadeIn(function(){$(this).css({opacity:1});});
			headMenuBigDiv.stop().fadeOut();
		});
		$("#siteRecomenda").mouseenter(function(){
			headTopoDiv.not('#headTopSiteRecom').stop().fadeOut();
			$(this).next().css('z-index', 99990).stop().fadeIn(function(){$(this).css({opacity:1});});
			headMenuBigDiv.stop().fadeOut();
		});
		$(".header-menu, .header-topo li, .sub-channels, .body, .flash, .header-topo > .search").not('#headTopSiteNews,#headTopSiteRecom').mouseenter(function(){
			headTopoDiv.stop().fadeOut();
		});
		$(".container-top").mouseleave(function(){
			headTopoDiv.stop().fadeOut();
			headMenuBigDiv.stop().fadeOut();
		});
		/* header menu */
		$(".header-menu > ul.big > li > a").mouseenter(function() {
			headMenuBigDiv.stop().fadeOut();
			headTopoDiv.stop().fadeOut();
			if($(this).next().children("ul").children("li").length > 0) $(this).next().stop().fadeIn(function(){$(this).css({opacity:1});});
		});
		$(".header-menu > a, .header-topo, .sub-channels, .body, .flash").mouseenter(function(){
			headMenuBigDiv.stop().fadeOut();
		});		
	}

	/* scroll init */
	ScrollInit();
});
/* ie9 drag fix */
(function($){var a=$.ui.mouse.prototype._mouseMove;$.ui.mouse.prototype._mouseMove=function(b){if($.browser.msie&&document.documentMode>=9){b.button=1};a.apply(this,[b]);}}(jQuery));
/* function to fix the -10000 pixel limit of jquery.animate */
$.fx.prototype.cur = function(){
    if ( this.elem[this.prop] != null && (!this.elem.style || this.elem.style[this.prop] == null) ) {
      return this.elem[ this.prop ];
    }
    var r = parseFloat( jQuery.css( this.elem, this.prop ) );
    return typeof r == 'undefined' ? 0 : r;
}
function ScrollInit() {
	var scrollElem = $('#scroll'), scrollCont = $('#scroll').find('.container'),
		ScrollApply = function(){
			if(scrollElem.hasClass('tabular-data')){
				scrollElem.mCustomScrollbar("vertical",600,"easeOutCirc",0,"fixed","yes","no",0);		
				setTimeout(function(){
					if($('.dragger_container').is(':hidden')){
						scrollCont.addClass('wide');
					}
				},200);
			} else {
				scrollElem.mCustomScrollbar("vertical",600,"easeOutCirc",1.1,"fixed","yes","no",0);
			}		
		};
	ScrollApply();
	scrollCont.resize(function(e){
		setTimeout(ScrollApply,500);
	});
}
function SearchGeral() {
	var text = $('.txtPesquisarspecial').val();
	if(text.length > 0 )//&& text!= 'Pesquisar'
	{
		window.location = '/pesquisa-geral/' + text;
	}
}

function UrlHasQuerystring(name){ 
    var hashes = window.location.href.slice('http://entreposto.itsmassive.com/').split('/');
    for(var i = 0; i < hashes.length; i++) {
		if(name==hashes[i]) return true;
    }
    return false;
}

function replaceAll(string, token, newtoken) {
		while (string.indexOf(token) != -1) {
	 		string = string.replace(token, newtoken);
		}
		return string;
}

function addFav() {
	url = location.href;
	title = document.title;
	if(UrlHasQuerystring("showroom")){
		var arr = $(".sub-channels li");
		if(arr.size()>3){
			s="";
			for(i=0; i<=arr.size(); i++){
				if(arr[i] != null){
					teste = $(arr[i]).text();
					if(teste != "Ofertas Especiais" && teste != "Viaturas de Serviço" && teste != "Usados" && teste != "Showroom"  && teste != " > " && teste != "null"){
						s+= " " + teste; //$(arr[i]).text();
					}
				}
			}
			title+=s;
		}
	}
//  getUrlVar: function(){
//    return getUrlVars()["showroom"];
//  }
//title = document.title;		    
	if (window.sidebar){
		window.sidebar.addPanel(title, url,"");
	} else if(window.opera && window.print) {
		var mbm = document.createElement('a');
		mbm.setAttribute('rel','sidebar');
		mbm.setAttribute('href',url);
		mbm.setAttribute('title',title);
		mbm.click();
	} else if(document.all)	{
		window.external.AddFavorite(url, title);
	}
}

function FlashStateShowRoom(estado) {
	var zindex = 0;
	if(estado == 'aberto'){
		zindex=100;
	}
	if(estado == 'fechado'){
		zindex=0;
	}
	$("#flashLayer").css('z-index', zindex);
}
function FlashState(estado){
	var zindex = 0;
	if(estado == 'aberto'){
		$("#flashContentwrapper").css('z-index', '1');
		zindex=1;
	}
	if(estado == 'fechado'){
		$("#flashContentwrapper").css('z-index', '0');
		zindex=0;
	}
	$("#flashLayer").css('z-index', zindex);
}

function iebugScroll(){
	$("#scroll").css("overflow","auto");	
	$("#scroll").css("width","710px");				    
}

function DoFilter(tipodevista, marcaId , servicoId, distritoId) {
	if(tipodevista=="listagem"){
		/*jQuery.each(jQuery.browser, function(i) {
  			if($.browser.msie){
			    //alert("ie");
			    $(".body.bg > .right").load("/ConcessionariosTable.ashx?Vista="+tipodevista+"&marcas="+urlencode(marcaId)+"&distritos="+distritoId+"&servicos="+servicoId, iebugScroll);		
  			} else {
			     //$("#div ul li").css("display","inline-table");
                 $(".body.bg > .right").load("/ConcessionariosTable.ashx?Vista="+tipodevista+"&marcas="+urlencode(marcaId)+"&distritos="+distritoId+"&servicos="+servicoId, function(){
					 $('#scroll').jScrollPane({scrollbarWidth:20, scrollbarMargin:1});
				});
  			}
		});*/
		$(".body.bg > .right").load("/ConcessionariosTable.ashx?Vista="+tipodevista+"&marcas="+urlencode(marcaId)+"&distritos="+distritoId+"&servicos="+servicoId, function(){
			ScrollInit();
		});
	} else {	
		$(".body.bg > .right").load("/ConcessionariosTable.ashx?Vista="+tipodevista+"&marcas="+urlencode(marcaId)+"&distritos="+distritoId+"&servicos="+servicoId);
	}
}

function ChangeMode(boolState){
	$(".pesquisa input").attr('checked', boolState);
}

function SlugService(modelo, subModelo, versao, marca){
    // alert(Modelo);   // alert(SubModelo);    // alert(Versao);        
	$.get("/SlugService.ashx?what=resuldata",
                { 'Modelo': modelo, 'SubModelo': subModelo, 'Versao': versao },
         function(result) {

            var oResultData = result; //eval('(' + result + ')');
            var sModelo= oResultData.modelo_Sluged;
 		    var sSubModelo= oResultData.submodelo_Sluged;
		    var sVersao= oResultData.versao_Sluged;
		    //alert("resposta "+sModelo+"/"+sSubModelo+"/"+sVersao);			    
	    	//BreadCrumbs
			var lisFinal = "<li><a href=\"/showroom/viaturas-novas/\">Showroom</a></li>";
			var infos = "";
			var lisSeparator = "<li> > </li>";
                if (marca.length > 0) {
                    lisFinal += lisSeparator
					lisFinal += '<li><a href="/showroom/viaturas-novas/detalhe/' + marca + '">' + marca + '</a></li>';
					infos += "Marca: " + marca+ ";";
                }
                if (modelo.length > 0) {
                    lisFinal += lisSeparator
                    lisFinal += '<li><a href="/showroom/viaturas-novas/detalhe/' + marca + '/' + sModelo + '">' + modelo + '</a></li>';
		   infos += "Modelo: " + modelo+ ";";
                }
                if (subModelo.length > 0) {
                    lisFinal += lisSeparator
					lisFinal += '<li><a href="/showroom/viaturas-novas/detalhe/' + marca + '/' + sModelo + '/' + sSubModelo + '">' + subModelo + '</a></li>';
					infos += "SubModelo: " + subModelo+ ";";
                }
                if (versao.length > 0){
                    lisFinal += lisSeparator
                    lisFinal += '<li><a href="/showroom/viaturas-novas/detalhe/' + marca + '/' + sModelo + '/' + sSubModelo + '/' + sVersao + '">' + versao + '</a></li>';
				    infos += "Versão: " + versao + ";";
                }
				ChangeBreadCrumbHTML(lisFinal);

				//alert(sModelo);
				if(marca != null || marca != '') $(".changeLinkTesteDrive").attr("href","/servicos/test-drive/"+marca);
				if(sModelo !=null || sModelo !='' ) $(".changeLinkTesteDrive").attr("href","/servicos/test-drive/"+marca+"/"+sModelo);
				//end breadcrumbs 	
				
				$("#outrasInfosForm").val(infos);
				
				var linkTD = "/servicos/test-drive/";
				if(marca.length > 0){
					linkTD = linkTD + marca;
				}
				if(modelo.length > 0) {
					linkTD = linkTD + "/" + sModelo ;
				}
				
				$("#ctl00_ctl00_ctl00_ctl00_ContentPlaceHolderDefault_ContentPlaceHolderSiteContent_ContentPlaceHolderSiteContent_ShowroomDetalhe_6_linkTestDrive").attr('href', linkTD);
				
				var query = "Marca="+ marca + "&Modelo="+ urlencode(modelo) + "&SubModelo="+ urlencode(subModelo) + "&Versao="+ urlencode(versao);
				 $(".buttons-block .header").load("/DetalheShowroom.ashx", query); //{ "Marca": marca, "Modelo": modelo, "SubModelo": subModelo, "Versao": versao});
				GetImage(marca, modelo);
				GetBrochura(marca, modelo);				
                    
            }
        );
	//alert("ver se sincrono");
}

function ShowRoomFilter(marca, modelo, subModelo, versao){
	SlugService(modelo, subModelo, versao, marca);
}

function GetImage(marca, modelo){
	var query = "Marca="+ marca + "&Modelo="+ urlencode(modelo) + "&Tipo=imagem";
	$(".body .center").load("/ShowRoomImage.ashx", query); 
}
function GetBrochura(marca, modelo){
	var query = "Marca="+ marca + "&Modelo="+ urlencode(modelo) + "&Tipo=brochura";
	$("#liBrochura").load("/ShowRoomImage.ashx", query, function(responseText, textStatus, XMLHttpRequest){
		if(responseText.length>0) {
			$("#liBrochura").show();
		} else {
			$("#liBrochura").hide();
		}
	}); 
}

function ScroolBarSearch(){
	/*jQuery.each(jQuery.browser, function(i) {
		if($.browser.msie){
			$(".jScrollPaneContainer").css("overflow","auto");
			$(".jScrollPaneTrack").css("display","none");
		} else {
			$('#scroll').jScrollPane({scrollbarWidth:20, scrollbarMargin:1});
			$('.jScrollPaneDrag').css('margin-left','1px');
		}
	});*/
	ScrollInit();
}
function SearchShowRoom(marca, precoBaixo, precoAlto){
	var query = "Marca="+ marca + "&PrecoBottom="+ precoBaixo+ "&PrecoTop="+ precoAlto;
	$(".tabular.content.scroll").load("/showroompesquisa.ashx", query, ScroolBarSearch ) 
}
function GoSearch(){
	var values ='';
	$(".latest .pesquisa input[type=checkbox]:checked").each(function() {var currentValue= $(this).attr('Value'); if(currentValue != '') values += currentValue + ",";});
	window.location="/showroom/viaturas-novas/pesquisa/?Marca=" + values+ "&PrecoBottom="+ $('#fromPrice').val() + "&PrecoTop="+ $('#toPrice').val()
}

function ChangeBreadCrumb(texto) {
	$('#litoChange').text(texto);
}
function ChangeBreadCrumbHTML(texto) {
	$('.sub-channels > ul').html(texto);
}

function CheckValueNumber(inputField) {
	var numberValue = '';
	var xpto = $(inputField).val();
	for(i=0;i<xpto.length;i++){
		if(!isNaN(Number(xpto[i]))){
			numberValue += 	xpto[i];
		}
	}
	$(inputField).val(numberValue);
}

function PopupCenter(pageURL, title,w,h) {
	var left = (screen.width/2)-(w/2);
	var top = (screen.height/2)-(h/2);
	var targetWin = window.open (pageURL, title, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width='+w+', height='+h+', top='+top+', left='+left);
} 
