﻿/* passo a passo */

jQuery(function() {
    Jw._init();
});

var Jw = {
	_init: function(){
		try {
			
		} 
		catch (e) {
			//console.log('Error: ' + e.description);
		}
	},
	
	_trocaConteudo: function() {
		$('div#step1').show();
		$('ul#steps li a').click(function() {
			$('ul#steps li a').removeClass('selected');
			$('div.content_step').hide();
			$(this).addClass('selected');
			
			var classe = $(this).attr('class').split(' ')[0];
			$('#'+classe).show();
			return false;
		});
	}
}


//ADD TOLLTIP SCRIPT IN ALL PAGES
//var ttp = document.createElement('script'), ttpref = document.getElementsByTagName('script')[0], path = ttpref.getAttribute('src').split('/');
//	path.pop();
//	ttp.type = 'text/javascript';
//	ttp.async = true;
//	ttp.src = path.join('/') + '/jquery.tooltip.min.js';
//	ttpref.parentNode.insertBefore(ttp, ttpref);

/* ACESSIBILIDADE */
function fontSize(action, container) {
	container = typeof(container) != 'undefined' ? container : "" 
    baseSize = parseInt($(container).css("font-size"))
 
    $els = $(container)
 
    $els.each(function(){
        $fs = parseInt($(this).css("font-size"))
        if(action=="plus" && baseSize<12) $fs+=1
        else if(action=="minus" && baseSize>10) $fs-=1
        $(this).css("font-size", $fs)
    })
}

function slShowHide(){
    var active = $(this).val();
		
    $('option',this).each(function(){
        var opt = $(this).val();
		
        if (opt != active) 
			$('#' + opt).hide();
		else
			$('#' + active).show();
    })
};

function stepsShowHide(e){
	e.preventDefault();
			
    var active = $(this).attr('href');
		
    $('li a',$(this).parent().parent()).each(function(){
        var opt = $(this).attr('href');
		
        if (opt != active) {
			$(opt).hide();
			$(this).removeClass('selected');
		}
		else {
			$(active).show();
			$(this).addClass('selected');
		}
    })
};	
	

$(document).ready(function() {
		var myWidth = $(window).width();
		if(myWidth <= 1008){
			$('#bg').addClass('bgSize1');
		}else{
			$('#bg').removeClass('bgSize1');
			}
	
});

/* ACCORDION */
$(document).ready(function() {

	//select show hide divs
	$('select.slShowHide').change(slShowHide);
	$('select.slShowHide').each(slShowHide);


	//passo a passo
	$('ul.steps li a, ul.dicionario_indice li a').click(stepsShowHide);
	$('ul.steps, ul.dicionario_indice').each(function(){
		$('li:eq(0) a',this).trigger('click');
	});

	if($.fn.tooltip)
	$('a.tooltip, em.tooltip, u.tooltip, i.tooltip, strong.tooltip, cite.tooltip').tooltip({
		showURL: false,
		loadURL: true
	});

	/* accordion 640 internas */	
	$("#accordion").accordion({
		collapsible: true,
		autoHeight: false,
		change: function(e,o){
			var nowAccordion = o.newContent;
			$("#result").show();
			if($.fn.jcarousel)
			$('.carousel-produtos',nowAccordion).jcarousel({
				scroll:1,
				initCallback: function(){
					$('.carousel-produtos',nowAccordion).css('visibility','visible');
					//Cufon.now();		
				}
			});
			
			$("#result").hide();
		}
	});

	if($.fn.jcarousel)
	$('#accordion div.ui-accordion-content-active .carousel-produtos').jcarousel({
		scroll:1,
		initCallback: function(){
			$('#accordion div.ui-accordion-content-active .carousel-produtos').css('visibility','visible');
		}
	});

/* fim */
})

var modalWindow = {  
    parent:"body",  
    windowId:null,  
    content:null,  
    width:null,  
    height:null,
	title:"",
    close:function()  
    {  
        $(".modal-window").remove();  
        $(".modal-overlay").remove();  
    },  
    open:function()  
    {  
        var modal = "";  
        modal += "<div class=\"modal-overlay\"></div>";  
        modal += "<div id=\"" + this.windowId + "\" class=\"modal-window\" style=\"width:" + this.width + "px; height:" + this.height + "px; margin-top:-" + (this.height / 2) + "px; margin-left:-" + (this.width / 2) + "px;\">";  
        modal += "<div class=\"modal-top\"><h5 class=\"modal-title\">"+this.title+"</h5></div>";
		modal += "<div class=\"modal-content\">";
		modal += this.content;
		modal += "</div>";
		modal += "<div class=\"modal-bottom\"></div>";
        modal += "</div>";      
  
        $(this.parent).append(modal);  
  
        $(".modal-top").append("<a class=\"close-window\"></a>");  
        $(".close-window").click(function(){modalWindow.close();});  
        $(".modal-overlay").click(function(){modalWindow.close();});  
    }  
};


/* CUFON REPLACE */
Cufon.set('fontFamily', 'serifa_bt');
	Cufon.replace('#col-1 h3');
	Cufon.replace('#content h2');
	Cufon.replace('#content h4');
	Cufon.replace('.main_content h4');
	Cufon.replace('.main_content h3');
	//Cufon.replace('.accordion_content_miolo ul li h5');
	Cufon.replace('.sidebar a.destaque strong');
	Cufon.replace('div.sidebar label');
	Cufon.replace('#col-2 a.destaque strong');
	Cufon.replace('.cols3 label');
	Cufon.replace('.main_content ul.linklist li a span.linklist_title');
	Cufon.replace('div.cols1 h3.h3_big');
	Cufon.replace('div#content.mapaSite h3');
		
Cufon.set('fontFamily', 'serifa');
	Cufon.replace('.cols3 #col-1 h2');
	Cufon.replace('span.h2_sub');
	Cufon.replace('div.sidebar h5');
	Cufon.replace('div.sidebar p');	
	Cufon.replace('div#header ul.headerGrupo li');
	Cufon.replace('.cols3 h5');
	Cufon.replace('.cols3 h3 a');
	Cufon.replace('.cols3 #col-2 p');
	Cufon.replace('.cols3 #col-3 p');
	Cufon.replace('.cols3 li a');
	Cufon.replace('div.sidebar ul li');
	Cufon.replace('.cols2 h5.titleForm');
	//Cufon.replace('div.main_content ul li h5');
	Cufon.replace('div#content.mapaSite div.session ul li a');
	
	
	
Cufon.set('fontFamily', 'serifa_bt');
	Cufon.replace('div.sidebar h6');		
	
		/*Cufon.replace('#footer ul li');*/

var openInModal = function(w,h)  
{  
	modalWindow.title = nid = this.title;
    modalWindow.windowId = "Modal_"+nid.replace(/[^a-zA-Z0-9]+/g,'');
    modalWindow.width = w;  
    modalWindow.height = h+42; 
    modalWindow.content = "<iframe width='100%' height='100%' frameborder='0' scrolling='no' allowtransparency='true' src='" + $(this).attr('href') + "'></iframe>";  
    modalWindow.open();  
};

$(function()
{
	$(".diminuir").click(function(){ fontSize("minus","div.main_content"); return false; })
    $(".aumentar").click(function(){ fontSize("plus","div.main_content"); return false; })
	
	$('input[type=text], input[type=textarea]').each(function(){
		$(this).data('initValue',$(this).val());
	}).focusin(function(){
		if($(this).val() == $(this).data('initValue'))
			$(this).val('');
	}).focusout(function(){
		if($(this).val() == '')
			$(this).val($(this).data('initValue'));
	})
	
	$('a.enviarEmail').click(function(e){
		e.preventDefault();
		
		$(this).attr('name','Enviar por e-mail');
		$(this).attr('href','../envieEmail.htm');
		openInModal.apply(this,[440,405]);
		
		Cufon.replace('.modal-window .modal-top h5');
	});
	
	$('a.bt_chatOnline').click(function(e){
		e.preventDefault();
		
		$(this).attr('name','Chat Online');
		$(this).attr('title','Chat Online');
		$(this).attr('href','/chatOnline.htm');
		openInModal.apply(this,[441,140]);
		
		Cufon.replace('.modal-window .modal-top h5');
		$('.modal-window').css('zoom','1');
	});
});	


/* google analytics */


var _gaq = _gaq || [];

var historyPush = [];
_gaq.push = function(i){
	historyPush[historyPush.length] = i;
	this[this.length] = i;
}

_gaq.push(['_setAccount', 'UA-3257253-14']);   /* ID NOVO - hittando desde 04/03/2011 */
_gaq.push(['b._setAccount', 'UA-3257253-1']);  /* ID VELHO */


function populaDicionario() {
   $("p.loading").show();
   $("div.resultados").hide();
   $("div.resultados div.erro").hide();
	//$.getJSON('http://'+document.location.host+'/_vti_bin/ListData.svc/DicionarioSeguros', function(data) {
   	//	$.each(data.d.results, function (i, result) {
   	$().SPServices({
		async: false,
        operation: "GetListItems",
        listName: "DicionarioSeguros",
        //CAMLQuery: "<Query><Where><Eq><FieldRef Name='Title'/><Value Type='Text'>" + chave + "</Value></Eq></Where></Query>",
        CAMLQueryOptions: "<QueryOptions></QueryOptions>", 
        CAMLViewFields: "<ViewFields><FieldRef Name='Title'/><FieldRef Name='Description1'/></ViewFields>",
        CAMLRowLimit: 0,

        completefunc: function (xData, Status) {
            $(xData.responseXML).find("[nodeName=z:row]").each(function () {
                var title = $(this).attr("ows_Title");
                var description = $(this).attr("ows_Description1");
		          
		        var content = "<div class='dicionario_termo letra_"+title.substr(0,1)+"'><h3>"+title+"</h3><p class='content'>"+description+"</p></div>";
		               
		        $("div.resultados").append(content);
            })
        }
    });
  
   $('div.dicionario_termo').hide();
   $('div.dicionario_termo.letra_A').show();	   
   $("p.loading").hide();
   $("div.resultados").show();
}

function populaDicas() {
   $("p.loading").show();
   $("div.resultados").hide();
   $("div.resultados div.erro").hide();
	//$.getJSON('http://'+document.location.host+'/_vti_bin/ListData.svc/DicionarioSeguros', function(data) {
   	//	$.each(data.d.results, function (i, result) {
   	$().SPServices({
		async: false,
        operation: "GetListItems",
        listName: "DicasSeguranca",
        //CAMLQuery: "<Query><Where><Eq><FieldRef Name='Title'/><Value Type='Text'>" + chave + "</Value></Eq></Where></Query>",
        CAMLQueryOptions: "<QueryOptions></QueryOptions>", 
        CAMLViewFields: "<ViewFields><FieldRef Name='Title'/><FieldRef Name='Descricao'/></ViewFields>",
        CAMLRowLimit: 0,

        completefunc: function (xData, Status) {
            $(xData.responseXML).find("[nodeName=z:row]").each(function () {
                var title = $(this).attr("ows_Title");
                var description = $(this).attr("ows_Descricao");
		          
		        var content = "<div class='dicionario_termo letra_"+title.substr(0,1)+"'><h3>"+title+"</h3><p class='content'>"+description+"</p></div>";
		               
		        $("div.resultados").append(content);
            })
        }
    });
  
   $('div.dicionario_termo').hide();
   $('div.dicionario_termo.letra_A').show();	   
   $("p.loading").hide();
   $("div.resultados").show();
}

function createDicas(type) {
var content;
var categoria;
$().SPServices({
		async: false,
        operation: "GetListItems",
        listName: "DicasSeguranca",
        //CAMLQuery: "<Query><Where><Eq><FieldRef Name='ClassificacaoTemaFAQ'/><Value Type='Text'>" + type + "</Value></Eq></Where></Query>",
        CAMLQueryOptions: "<QueryOptions></QueryOptions>", 
        CAMLViewFields: "<ViewFields><FieldRef Name='Title'/><FieldRef Name='Descricao'/><FieldRef Name='CategoriaDica'/></ViewFields>",
        CAMLRowLimit: 0,


        completefunc: function (xData, Status) {
            $(xData.responseXML).find("[nodeName=z:row]").each(function () {
             var itemCategoria = $(this).attr("ows_CategoriaDica");
                var itemDescricao = $(this).attr("ows_Descricao");
                
             categoria = itemCategoria.replace(" ","_").replace(" ","_").replace(" ","_").replace(" ","_").toLowerCase();
             $("select.slShowHide").append("<option class='"+categoria+"' value='"+categoria+"'>"+itemCategoria+"</option>");
 
	        content = '<div class="faq_item '+categoria+'"><p>'+itemDescricao+'</p></div>';
			$("div.main_content").append(content);   
            })
        }
    });
    
    fixSelect();
   	$("p.loading").hide();
   	changeFAQ($("select.slShowHide option:eq(1)").val());
	$("select.slShowHide option:eq(1)").attr('selected',true);
}


function mostraDicionario(){
	$('div.erro a').click(function(){
     	   $("div.resultados div.erro").hide();
		   $('div.dicionario_termo').hide();
		   $('div.dicionario_termo.letra_A').show();	   
		   $("p.loading").hide();
		   $("div.resultados").show();
	});

}

function mostraDicas(){
	$('div.erro a').click(function(){
     	   $("div.resultados div.erro").hide();
		   $('div.dicionario_termo').hide();
		   $('div.dicionario_termo.letra_A').show();	   
		   $("p.loading").hide();
		   $("div.resultados").show();
	});

}


function bindDicionario(){
	$('ul.dicionario_indice li a').click(function(){
			$('ul.dicionario_indice li a').removeClass('selected');
			$(this).addClass('selected');
			var letra = $(this).attr("href");
//			console.log(letra.substring(letra.length-1));
			$('div.dicionario_termo').hide();
			
			if($('div.dicionario_termo.letra_'+letra.substring(letra.length-1)).size() > 0){
				$('div.dicionario_termo.letra_'+letra.substring(letra.length-1)).show();
				$('div.erro').hide();
			}else{
				$('div.erro h3').text(letra.substring(letra.length-1));
				$('div.erro').show();
			}
	
	});
	

}

function bindDicas(){
	$('ul.dicionario_indice li a').click(function(){
			$('ul.dicionario_indice li a').removeClass('selected');
			$(this).addClass('selected');
			var letra = $(this).attr("href");
//			console.log(letra.substring(letra.length-1));
			$('div.dicionario_termo').hide();
			
			if($('div.dicionario_termo.letra_'+letra.substring(letra.length-1)).size() > 0){
				$('div.dicionario_termo.letra_'+letra.substring(letra.length-1)).show();
				$('div.erro').hide();
			}else{
				$('div.erro h3').text(letra.substring(letra.length-1));
				$('div.erro').show();
			}
	
	});
	

}


function buscaDicionario(){
    $('a#buscaDicionario').click(function(){
        $('div.dicionario_termo').hide();

         // console.log($("input#termo_busca").val());
         var criteria = $("input#termo_busca").val();
         criteria = criteria.toUpperCase();
         
         //Search result
         var isEmptyResult = true;
       
            $("div.resultados div.dicionario_termo").each(function(){
               var content = $(this).html().toUpperCase();
           
                if(content.search(criteria) != -1)
                {
                    $("div.resultados div.erro").hide();
                    $(this).show();
                    isEmptyResult = false;
                }
            });
                       
            if(isEmptyResult)
                $("div.resultados div.erro").show();
    });
}

function buscaDicas(){
    $('a#buscaDicionario').click(function(){
        $('div.dicionario_termo').hide();

         // console.log($("input#termo_busca").val());
         var criteria = $("input#termo_busca").val();
         criteria = criteria.toUpperCase();
         
         //Search result
         var isEmptyResult = true;
       
            $("div.resultados div.dicionario_termo").each(function(){
               var content = $(this).html().toUpperCase();
           
                if(content.search(criteria) != -1)
                {
                    $("div.resultados div.erro").hide();
                    $(this).show();
                    isEmptyResult = false;
                }
            });
                       
            if(isEmptyResult)
                $("div.resultados div.erro").show();
    });
}

function changeFAQ(cat){
	if(cat != "selecione"){
		$('div.faq_item').hide();
		$('div.'+cat).show();
		$('span.resultados_tit strong').text($("select.slShowHide option."+cat).text());
	}
}

function createFAQ(type) {
	var content;
	var categoria;
	$().SPServices({
		async: false,
        operation: "GetListItems",
        listName: "FAQ",
        CAMLQuery: "<Query><Where><Eq><FieldRef Name='ClassificacaoTemaFAQ'/><Value Type='Text'>" + type + "</Value></Eq></Where></Query>",
        CAMLQueryOptions: "<QueryOptions></QueryOptions>", 
        CAMLViewFields: "<ViewFields><FieldRef Name='Title'/><FieldRef Name='ClassificacaoTemaFAQ'/><FieldRef Name='CategoriaFAQ'/><FieldRef Name='Pergunta'/><FieldRef Name='Resposta'/></ViewFields>",
        CAMLRowLimit: 0,

        completefunc: function (xData, Status) {
            $(xData.responseXML).find("[nodeName=z:row]").each(function () {
            	var itemCategoria = $(this).attr("ows_CategoriaFAQ");
                var itemPergunta = $(this).attr("ows_Pergunta");
                var itemResposta = $(this).attr("ows_Resposta");
                
            	categoria = itemCategoria.replace(" ","_").replace(" ","_").replace(" ","_").replace(" ","_").toLowerCase();
            	$("select.slShowHide").append("<option class='"+categoria+"' value='"+categoria+"'>"+itemCategoria+"</option>");
			
	        	content = '<div class="faq_item '+categoria+'"><p class="question">'+itemPergunta+'<p><p>'+itemResposta+'</p></div>';
				$("div.main_content").append(content);   
            })
        }
    });
    
    fixSelect();
   $("p.loading").hide();
   changeFAQ($("select.slShowHide option:eq(1)").val());
	$("select.slShowHide option:eq(1)").attr('selected',true);
}

function createSimpleFAQ(type) {
	var content;

	$().SPServices({
		async: false,
        operation: "GetListItems",
        listName: "FAQ",
        CAMLQuery: "<Query><Where><Eq><FieldRef Name='ClassificacaoTemaFAQ'/><Value Type='Text'>" + type + "</Value></Eq></Where></Query>",
        CAMLQueryOptions: "<QueryOptions></QueryOptions>", 
        CAMLViewFields: "<ViewFields><FieldRef Name='Title'/><FieldRef Name='ClassificacaoTemaFAQ'/><FieldRef Name='CategoriaFAQ'/><FieldRef Name='Pergunta'/><FieldRef Name='Resposta'/></ViewFields>",
        CAMLRowLimit: 0,

        completefunc: function (xData, Status) {
            $(xData.responseXML).find("[nodeName=z:row]").each(function () {
            	var itemCategoria = $(this).attr("ows_CategoriaFAQ");
                var itemPergunta = $(this).attr("ows_Pergunta");
                var itemResposta = $(this).attr("ows_Resposta");
                
            	content = '<div class="faq_item"><p class="question">'+itemPergunta+'<p><p>'+itemResposta+'</p></div>';
			    $("div.main_content").append(content);   
            })
        }
    }) 
             
	//fixSelect();
    $("p.loading").hide();
   // changeFAQ($("select.slShowHide option:eq(1)").val());
}

function fixSelect(){
var a = new Array();
        $("select.slShowHide").children("option").each(function(x){
                test = false;
                b = a[x] = $(this).val();
                for (i=0;i<a.length-1;i++){
                        if (b ==a[i]) test =true;
                }
                if (test) $(this).remove();
        });
}


function getClipping(){
   var i = 0;
   $("p.loading").show();
   $('ul.clipping').hide();
   
   $().SPServices({
		async: false,
        operation: "GetListItems",
        listName: "Clipping",
        CAMLQuery: "<Query><OrderBy><FieldRef Name='Created' Ascending='False' /></OrderBy></Query>",
        CAMLQueryOptions: "<QueryOptions></QueryOptions>", 
		CAMLRowLimit: 2,

        completefunc: function (xData, Status) {
            $(xData.responseXML).find("[nodeName=z:row]").each(function () {
                var itemTitle = $(this).attr("ows_Title");
                var itemMateria = $(this).attr("ows_Materia");
                var itemResumo = $(this).attr("ows_Resumo");
                var itemId = $(this).attr("ows_ID");
                
                $('ul.clipping').append(
						'<li><p class="noticia_title">'+itemTitle+'</p>'+
						'<div style="display:none;" class="materia">'+itemMateria+'</div>'+
						'<p class="resumo">'+itemResumo.replace("<div>","").replace("</div>","")+'</p><a href="#lerMais" onclick="moreInfo('+itemId+');" class="btLerMais spt more" title="Ler Mais">Ler Mais</a>');   
            })
        }
    });
    
    $("p.loading").hide();		
	$('ul.clipping').show();    
}


function getDetail(Id){
	
	if(Id != undefined){
		$("div.main_content").html('');
		
		$().SPServices({
			async: false,
	        operation: "GetListItems",
	        listName: "Clipping",
	        CAMLQuery: "<Query><Where><Eq><FieldRef Name='ID'/><Value Type='Text'>" + Id + "</Value></Eq></Where></Query>",
	        CAMLQueryOptions: "<QueryOptions></QueryOptions>", 
	        CAMLViewFields: "<ViewFields><FieldRef Name='Title'/><FieldRef Name='Materia'/></ViewFields>",
	        CAMLRowLimit: 0,
	
	        completefunc: function (xData, Status) {
	            $(xData.responseXML).find("[nodeName=z:row]").each(function () {
	                var itemTitle = $(this).attr("ows_Title");
	                var itemMateria = $(this).attr("ows_Materia");
	                
	            	$("div.main_content").append("<p class='noticia_title'>"+itemTitle+"</p><div class='materia'>"+itemMateria+"</div>");				
	            })
	        }
	    });
	    
	    $("div.main_content").show();			
		$("p.loading").hide();  
	}else{
		$("div.main_content").show();			
		$("p.loading").hide();
	}

}

function moreInfo(lista){
	var url = 'http://' + document.location.host + '/institucional/institucional_imprensa_clippings_detalhe.aspx#id='+lista;
	$(location).attr('href',url);
}

function getReleases(){
   var i = 0;
   $("p.loading").show();
   $("ul.releases").hide();
   
   $().SPServices({
		async: false,
        operation: "GetListItems",
        listName: "Releases",
        CAMLQuery: "<Query><OrderBy><FieldRef Name='Created' Ascending='False' /></OrderBy></Query>",
        CAMLQueryOptions: "<QueryOptions></QueryOptions>", 
        CAMLViewFields: "<ViewFields><FieldRef Name='ServerUrl'/><FieldRef Name='LinkFilename'/><FieldRef Name='FileSizeDisplay'/></ViewFields>",
        CAMLRowLimit: 3,

        completefunc: function (xData, Status) {
            $(xData.responseXML).find("[nodeName=z:row]").each(function () {
                var itemUrl = $(this).attr("ows_ServerUrl");
                var itemName = $(this).attr("ows_LinkFilename");
                var itemSize = $(this).attr("ows_FileSizeDisplay");
                
                $('ul.releases').append(
						'<li><p class="noticia_title" ><a style="font-size:11px; text-decoration:underline" target="_blank" href="'+itemUrl+'">'+itemName+'</a></p>'+
						'<p>( Arquivo PDF, '+ Math.round(itemSize/1024)+'KB )</p>');   
            })
        }
    });
    
    $("p.loading").hide();
	$("ul.releases").show();
}


function searchCustom(){
	if($("input#searchCampo").val().length > 0){
		var url = 'http://' + document.location.host + '/_layouts/LibertyPortalSearchResults.aspx?k='+$("input#searchCampo").val();
		$(location).attr('href',url);
	}
}


function clearSearch(){
	 $("input#searchCampo").val("");
}

function getReleasesdataTable(){
   $("table#releases").hide();
   
   $().SPServices({
		async: false,
        operation: "GetListItems",
        listName: "Releases",
        CAMLQueryOptions: "<QueryOptions></QueryOptions>", 
        CAMLViewFields: "<ViewFields><FieldRef Name='ID'/><FieldRef Name='ServerUrl'/><FieldRef Name='LinkFilename'/><FieldRef Name='FileSizeDisplay'/></ViewFields>",
        CAMLRowLimit: 0,

        completefunc: function (xData, Status) {
            $(xData.responseXML).find("[nodeName=z:row]").each(function () {
                var itemUrl = $(this).attr("ows_ServerUrl");
                var itemName = $(this).attr("ows_LinkFilename");
                var itemSize = $(this).attr("ows_FileSizeDisplay");
                var itemId = $(this).attr("ows_ID");
                
                $('table#releases tbody').append(
						'<tr><td style="display:none;">'+itemId+'</td><td><p class="noticia_title"><a target="_blank" href="'+itemUrl+'">'+itemName+'</a></p>'+
						'<p>(Arquivo PDF, '+Math.round(itemSize/1024)+' Kb)</p></td></tr>');   
            })
        }
    });

	$("table#releases").dataTable({"bFilter": false,"sPaginationType": "full_numbers","bInfo": false, "bLengthChange": false, "aoColumns": [{"asSorting": ["desc"]}, null]});
	$("table#releases").show();    
}


function getClippingdataTable(){
   $("p.loading").show();
   $("table#clipping").hide();

	$().SPServices({
		async: false,
        operation: "GetListItems",
        listName: "Clipping",
        CAMLQueryOptions: "<QueryOptions></QueryOptions>", 
        CAMLRowLimit: 0,

        completefunc: function (xData, Status) {
            $(xData.responseXML).find("[nodeName=z:row]").each(function () {
                var itemTitle = $(this).attr("ows_Title");
                var itemMateria = $(this).attr("ows_Materia");
                var itemResumo = $(this).attr("ows_Resumo");
                var itemId = $(this).attr("ows_ID");
                
                $('table#clipping tbody').append(
						'<tr><td style="display:none;">'+itemId+'</td><td><p class="noticia_title">'+itemTitle+'</p>'+
						'<div style="display:none;" class="materia">'+itemMateria+'</div>'+
						'<p class="resumo">'+itemResumo.replace("<div>","").replace("</div>","")+'</p></td><td style="vertical-align:middle"><a href="#lerMais" onclick="moreInfo('+itemId+');" class="btLerMais spt more" title="Ler Mais">Ler Mais</a></td></tr>');   
            })
        }
    });
    
    $("p.loading").hide();
	$("table#clipping").dataTable({"bFilter": false,"sPaginationType": "full_numbers","bInfo": false, "bLengthChange": false, "aoColumns": [{"asSorting": ["desc"]}, null]});
	$("table#clipping").show(); 
}

function switchSteps(passo){
	
	$('div#steps ul').hide();
	$('div#steps ul.'+passo).show();
	$('div#steps ul.'+passo+' li a').removeClass('selected');
	$('div#steps ul.'+passo+' li a:eq(0)').addClass('selected');
	
	$('div.content_steps').hide();
	
	switch(passo){
		case "steps_automovel":
			
			$('div.content_automovel').show();
			$('div#steps_automovel_g1').show();		
		break;

		case "steps_pessoas":

			$('div.content_pessoas').show();
			$('div#steps_pessoas_g1').show();	
		break;

		case "steps_transporte":

			$('div.content_transporte').show();
			$('div#steps_transporte_g1').show();
		break;

		case "steps_propriedade":

			$('div.content_propriedade').show();
			$('div#steps_propriedade_g1').show();		
		break;
	}	
}



function createGuia(){
	var ind;
	
	$().SPServices({
		async: false,
        operation: "GetListItems",
        listName: "GuiaPassoaPasso",
        CAMLQueryOptions: "<QueryOptions></QueryOptions>", 
        CAMLViewFields: "<ViewFields><FieldRef Name='Description1'/><FieldRef Name='Guia'/></ViewFields>",
        CAMLRowLimit: 0,

        completefunc: function (xData, Status) {
            $(xData.responseXML).find("[nodeName=z:row]").each(function () {
                ind = $(this).attr("ows_Title").split(" ")[1].split(":")[0];
                var title = $(this).attr("ows_Title");
                var description = $(this).attr("ows_Description1");
                var guia = $(this).attr("ows_Guia");

				switch(guia){
					case "Autom\u00f3vel":
						if($('div#steps ul.steps_automovel').length != 0){
							$('ul.steps_automovel').append(
								"<li class='step"+ind+"'><a onclick='getPos(this);' href='javascript:void(0);' name='#steps_automovel_g"+ind+"'>"+title+"</a></li>"
							);					
						}else{
							$('div#steps').append("<ul class='steps steps_automovel'><li class='step"+ind+"'><a href='javascript:void(0);' class='selected' onclick='getPos(this);' name='#steps_automovel_g"+ind+"'>"+title+"</a></li></ul>");
						}
	
						if($('div#steps_content div.content_automovel').length != 0){
							$('div.content_automovel').append(
								"<div style='display:none' id='steps_automovel_g"+ind+"'><p class='huge'><strong>"+title+"</strong></p><p>"+description+"</p></div>"
							);					
						}else{
							$('div#steps_content').append(
								"<div class='content_automovel content_steps'><div id='steps_automovel_g"+ind+"'><p class='huge'><strong>"+title+"</strong></p><p>"+description+"</p></div></div>");
						}					
		
					break;
					
					case "Pessoas":
						if($('div#steps ul.steps_pessoas').length != 0){
							$('ul.steps_pessoas').append(
								"<li class='step"+ind+"'><a onclick='getPos(this);' name='#steps_pessoas_g"+ind+"' href='javascript:void(0);'>"+title+"</a></li>"
							);						
						}else{
							$('div#steps').append("<ul class='steps steps_pessoas'><li class='step"+ind+"'><a class='selected' href='javascript:void(0);' onclick='getPos(this);' name='#steps_pessoas_g"+ind+"'>"+title+"</a></li></ul>");
						}
	
						if($('div#steps_content div.content_pessoas').length != 0){
							$('div.content_pessoas').append(
								"<div style='display:none' id='steps_pessoas_g"+ind+"'><p class='huge'><strong>"+title+"</strong></p><p>"+description+"</p></div>"
							);					
						}else{
							$('div#steps_content').append(
								"<div class='content_pessoas content_steps'><div id='steps_pessoas_g"+ind+"'><p class='huge'><strong>"+title+"</strong></p><p>"+description+"</p></div></div>");
						}	
				
					break;
	
					case "Transporte":
						if($('div#steps ul.steps_transporte').length != 0){
							$('ul.steps_transporte').append(
								"<li class='step"+ind+"'><a onclick='getPos(this);' name='#steps_transporte_g"+ind+"' href='javascript:void(0);'>"+title+"</a></li>"
							);						
						}else{
							$('div#steps').append("<ul class='steps steps_transporte'><li class='step"+ind+"'><a class='selected' onclick='getPos(this);' href='javascript:void(0);' name='#steps_transporte_g"+ind+"'>"+title+"</a></li></ul>");
						}
						
						if($('div#steps_content div.content_transporte').length != 0){
							$('div.content_transporte').append(
								"<div style='display:none' id='steps_transporte_g"+ind+"'><p class='huge'><strong>"+title+"</strong></p><p>"+description+"</p></div>"
							);					
						}else{
							$('div#steps_content').append(
								"<div class='content_transporte content_steps'><div id='steps_transporte_g"+ind+"'><p class='huge'><strong>"+title+"</strong></p><p>"+description+"</p></div></div>");
						}	
						
					break;
	
					case "Propriedade":
						if($('div#steps ul.steps_propriedade').length != 0){
							$('ul.steps_propriedade').append(
								"<li class='step"+ind+"'><a onclick='getPos(this);' href='javascript:void(0);' name='#steps_propriedade_g"+ind+"'>"+title+"</a></li>"
							);						
						}else{
							$('div#steps').append("<ul class='steps steps_propriedade'><li class='step"+ind+"'><a class='selected'  name='#steps_propriedade_g"+ind+"' onclick='getPos(this);' href='javascript:void(0);'>"+title+"</a></li></ul>");
						}
	
						if($('div#steps_content div.content_propriedade').length != 0){
							$('div.content_propriedade').append(
								"<div style='display:none' id='steps_propriedade_g"+ind+"'><p class='huge'><strong>"+title+"</strong></p><p>"+description+"</p></div>"
							);					
						}else{
							$('div#steps_content').append(
								"<div class='content_propriedade content_steps'><div id='steps_propriedade_g"+ind+"'><p class='huge'><strong>"+title+"</strong></p><p>"+description+"</p></div></div>");
						}	
					
					break;
								
				}
	
	            $("select.slShowHide").append("<option value='steps_"+guia.toLowerCase().replace("ó","o")+"'>"+guia+"</option>");
		   
            })
        }
    });
    
    fixSelect();
	switchSteps('steps_automovel');

	$("p.loading").hide();
    $("div.main_content").show();
}

function getPos(element){
	id = $(element).attr("name");
	
	$('div.content_steps > div').hide();
	$('div'+id).show();
	
	$('div#steps li a').removeClass("selected")
	$(element).addClass("selected");
}


function buscaResultado(k,scope){
	var url = 'http://' + document.location.host + '/busca/buscaresultado.aspx#k='+k+'#scope='+scope;
	$(location).attr('href',url);
}

function ConsultaManualAntigo(pageName, htmlContainerId){
	GetMateriaisAntigosByPage(pageName, htmlContainerId);
	//$("#linkAntigo").hide();
	//$("#linkNovo").show();
}

function ConsultaManualNovo(pageName, htmlContainerId){
	GetMateriaisByPage(pageName, htmlContainerId);
	$("#linkAntigo").show();
	$("#linkNovo").hide();
	$("p#fileOldLink").hide;
}

function GetMateriaisByPage(pageName, htmlContainerId){
	$("p.loading").show();
	
	$(htmlContainerId).hide();
	
	var categoria = "Atual";
	
	$().SPServices({
		async: false,
        operation: "GetListItems",
        listName: "Materiais",
        CAMLQuery: "<Query><Where><And><Eq><FieldRef Name='NomeTela'/><Value Type='Text'>" + pageName + "</Value></Eq><Eq><FieldRef Name='Categoria'/><Value Type='Text'>" + categoria + "</Value></Eq></And></Where><OrderBy><FieldRef Name='InicioVigencia' Ascending='TRUE'/></OrderBy></Query>",
		CAMLQueryOptions: "<QueryOptions></QueryOptions>", 
		CAMLViewFields: "<ViewFields><FieldRef Name='ServerUrl'/><FieldRef Name='Title'/><FieldRef Name='FileSizeDisplay'/></ViewFields>",
		CAMLRowLimit: 0,

        completefunc: function (xData, Status) {
			switch(htmlContainerId){
				case "p#fileLink" :
					$('p#fileLink').html("");
					break;
				case "ul#materiais" :
					$('ul#materiais').html("");
					break;
			}

            $(xData.responseXML).find("[nodeName=z:row]").each(function () {
                var itemUrl = $(this).attr("ows_ServerUrl");
                var itemName = $(this).attr("ows_Title");
                var itemSize = $(this).attr("ows_FileSizeDisplay");
                
                switch(htmlContainerId){
					case "p#fileLink" :
						$('p#fileLink').prepend("<a href='" + itemUrl + "' target='_blank' title='" + itemName + "'>" + itemName + "</a><br />");
						break;
					case "ul#materiais" :
						$('ul#materiais').append("<li><a href='" + itemUrl + "' target='_blank' title='Baixar arquivo'>" + itemName + "</a><p>(Arquivo PDF, " + Math.round(itemSize/1024) + "kb)</p></li>");
						break;
				}
            })
        }
    });

	$("p.loading").hide();
	$(htmlContainerId).show();   
}

function GetMateriaisAntigosByPage(pageName, htmlContainerId){
   $("p.loading").show();
  
   $(htmlContainerId).hide();
   
   var categoria = "Antigo";
   
   $().SPServices({
		async: false,
        operation: "GetListItems",
        listName: "Materiais",
        CAMLQuery: "<Query><Where><And><Eq><FieldRef Name='NomeTela'/><Value Type='Text'>" + pageName + "</Value></Eq><Eq><FieldRef Name='Categoria'/><Value Type='Text'>" + categoria + "</Value></Eq></And></Where><OrderBy><FieldRef Name='InicioVigencia' Ascending='TRUE'/></OrderBy></Query>",
	    CAMLQueryOptions: "<QueryOptions></QueryOptions>", 
        CAMLViewFields: "<ViewFields><FieldRef Name='ServerUrl'/><FieldRef Name='Title'/><FieldRef Name='FileSizeDisplay'/></ViewFields>",
        CAMLRowLimit: 0,

        completefunc: function (xData, Status) {
            switch(htmlContainerId){
					case "p#fileOldLink" :
						$('p#fileOldLink').html("");
					break;
					case "ul#materiais" :
						$('ul#materiais').html("");
					break;
				}

            $(xData.responseXML).find("[nodeName=z:row]").each(function () {
                var itemUrl = $(this).attr("ows_ServerUrl");
                var itemName = $(this).attr("ows_Title");
                var itemSize = $(this).attr("ows_FileSizeDisplay");
                
                switch(htmlContainerId){
					case "p#fileOldLink" :
						$('p#fileOldLink').prepend("<a href='" + itemUrl + "' target='_blank' title='" + itemName + "'>" + itemName + "</a><br />");
					break;
					case "ul#materiais" :
						$('ul#materiais').append("<li><a href='" + itemUrl + "' target='_blank' title='Baixar arquivo'>" + itemName + "</a><p>(Arquivo PDF, " + Math.round(itemSize/1024) + "kb)</p></li>");
					break;
				}   
            })
        }
    });

	$("p.loading").hide();
	$(htmlContainerId).show();   
}


function checkMail(mail){
    var er = new RegExp(/^[A-Za-z0-9_\-\.]+@[A-Za-z0-9_\-\.]{2,}\.[A-Za-z0-9]{2,}(\.[A-Za-z0-9])?/);
    if(typeof(mail) == "string")
    {
    	if(er.test(mail))
    	{
    		return true;
    	}
    } else if(typeof(mail) == "object")
    {
    	if(er.test(mail.value))
    	{
    		return true; 
        }
    } else 
    {
        return false;
    }
}

function limpa_string(S){
	// Deixa so' os digitos no numero
	var Digitos = "0123456789";
	var temp = "";
	var digito = "";
    for (var i=0; i<S.length; i++){
      digito = S.charAt(i);
      if (Digitos.indexOf(digito)>=0){temp=temp+digito}
    }
    return temp
}

function valida_CNPJ(s)
{
        var i;
        s = limpa_string(s);
        var c = s.substr(0,12);
        var dv = s.substr(12,2);
        var d1 = 0;
        for (i = 0; i < 12; i++)
        {
                d1 += c.charAt(11-i)*(2+(i % 8));
        }
        if (d1 == 0) return false;
        d1 = 11 - (d1 % 11);
        if (d1 > 9) d1 = 0;
        if (dv.charAt(0) != d1)
        {
                return false;
        }

        d1 *= 2;
        for (i = 0; i < 12; i++)
        {
                d1 += c.charAt(11-i)*(2+((i+1) % 8));
        }
        d1 = 11 - (d1 % 11);
        if (d1 > 9) d1 = 0;
        if (dv.charAt(1) != d1)
        {
                return false;
        }
        return true;
}

function closeModalWindow()
{
	$(".modal-overlay", top.document).remove();
	$(".modal-window", top.document).remove();  
}

//////////////////////////////////////////////////////////////////

//array onde ficam armazenados os seguros que serao exibidos ao usuario
var segurosOferecidos = new Array();

function GetWizardResult(answerIdade, answerSexo, answerProfissao, answerVeiculo,
						 answerValorVeiculo, answerRenda, answerCasa)
{
	
	var podeOferecerVida = false;
	var podeOferecerAPI = false;
	
	if (answerIdade >= 18 && answerIdade <= 65)
	{
		//Idade OK para oferecer Seguros de Vida
		podeOferecerVida = true;
	}
	
	if (answerIdade >= 18 && answerIdade <= 70)
	{
		//Idade OK para oferecer Seguros de Acidentes Pessoais
		podeOferecerAPI = true;
	}

	
	var resultAnswerProfissao = GetResultOfProfissao(answerProfissao);
	if (resultAnswerProfissao.length > 0)
	{
		var oferecerVida = resultAnswerProfissao[0];
		var oferecerAP = resultAnswerProfissao[1];
		var seguroOutros = resultAnswerProfissao[2];
		
		if (oferecerVida == 0)
		{
			podeOferecerVida = false;
		}
		
		if (oferecerAP == 1 && podeOferecerAPI)
		{
			segurosOferecidos[segurosOferecidos.length] = "liberty_api";
		}
		
		if (seguroOutros != "" && seguroOutros != "undefined")
		{
			segurosOferecidos[segurosOferecidos.length] = seguroOutros;
		}
	}
	
	if (answerVeiculo == "carro")
	{
		segurosOferecidos[segurosOferecidos.length] = GetResultOfQuestoes("carro", answerValorVeiculo);
	} 
	else if (answerVeiculo == "caminhao")
	{
		segurosOferecidos[segurosOferecidos.length] = GetResultOfQuestoes("caminhao", answerValorVeiculo);
	}
	
	if (podeOferecerVida)
	{
		segurosOferecidos[segurosOferecidos.length] = GetResultOfQuestoes("renda", answerRenda);
	}
	
	segurosOferecidos[segurosOferecidos.length] =  "residencia";
	
	$("#carouselPlaceHolder").empty();

	if (segurosOferecidos.length > 0)

	{

		var htmlResult = '<ul id="carousel-result" class="carousel-produtos jcarousel-skin">';

		//for each (var seguro in segurosOferecidos)

		for (var i = 0; i < segurosOferecidos.length; i++)

		{

			var seguroArray = GetSeguroByKey(segurosOferecidos[i]);
			if (seguroArray[0] != undefined)
			{
				htmlResult = htmlResult + '<li>' +
			                              '      <h5>' + seguroArray[0] + '</h5>' +
			                              '      <img src="' + seguroArray[1] + '" width="164" height="108" alt="' + seguroArray[0] + '" />' +
			                              '      <br /><br /> ' + 
			                              '		 <a class="btConheca spt" title="Conheça" href="' + seguroArray[2].split(",")[0] + '">Conheça</a>' + 
			                              '  </li>';
			}
		}
		htmlResult = htmlResult + "</ul>";
		$("#carouselPlaceHolder").append(htmlResult);

	}
	
}

function GetResultOfQuestoes(chaveQuestao, answerValue)
{
	var resultAnswer = "";
	
	$().SPServices({
		async: false,
        operation: "GetListItems",
        listName: "Questoes",
        CAMLQuery: "<Query><Where><Eq><FieldRef Name='Title'/><Value Type='Text'>" + chaveQuestao + "</Value></Eq></Where></Query>",
        CAMLQueryOptions: '<QueryOptions></QueryOptions>', 
        CAMLRowLimit: 0,

        completefunc: function (xData, Status) {
            $(xData.responseXML).find("[nodeName=z:row]").each(function () {
                var valorMin = $(this).attr("ows_Valor_x0020_1");
            	var valorMax = $(this).attr("ows_Valor_x0020_2");
            	
            	if (parseFloat(valorMin) <= parseFloat(answerValue) &&
            		parseFloat(answerValue) <= parseFloat(valorMax))
            	{
            		var seguroOferecido = $(this).attr("ows_Seguro_x0020_Oferecido");
            		if (seguroOferecido != undefined)
            		{
            			resultAnswer = seguroOferecido.split("#")[1];
            		}
              	}
            })
        }
    });
    
    return resultAnswer;
}

function GetResultOfProfissao(chaveProfissao)
{
	var resultAnswer = new Array(3);
	
	$().SPServices({
		async: false,
        operation: "GetListItems",
        listName: "Profissao",
        CAMLQuery: "<Query><Where><Eq><FieldRef Name='Title'/><Value Type='Text'>" + chaveProfissao + "</Value></Eq></Where></Query>",
        CAMLQueryOptions: '<QueryOptions></QueryOptions>', 
        CAMLRowLimit: 0,

        completefunc: function (xData, Status) {
            $(xData.responseXML).find("[nodeName=z:row]").each(function () {
                resultAnswer[0] = $(this).attr("ows_Oferecer_x0020_Vida");
                resultAnswer[1] = $(this).attr("ows_Oferecer_x0020_AP");
                
                var seguroOferecido = $(this).attr("ows_Oferecer_x0020_Property");
                if (seguroOferecido != undefined)
        		{
        			resultAnswer[2] = seguroOferecido.split("#")[1];
        		}
            })
        }
    });
    return resultAnswer;
}

function GetSeguroByKey(chave)
{
	var resultSeg = new Array(3);
	
	$().SPServices({
		async: false,
        operation: "GetListItems",
        listName: "Seguros",
        CAMLQuery: "<Query><Where><Eq><FieldRef Name='Title'/><Value Type='Text'>" + chave + "</Value></Eq></Where></Query>",
        CAMLQueryOptions: '<QueryOptions></QueryOptions>', 
        CAMLRowLimit: 0,

        completefunc: function (xData, Status) {
            $(xData.responseXML).find("[nodeName=z:row]").each(function () {
                resultSeg[0] = $(this).attr("ows_Seguro");
                resultSeg[1] = $(this).attr("ows_Image_x0020_URL");
                resultSeg[2] = $(this).attr("ows_Link");
            })
        }
    });
    return resultSeg;
}

function MontaDropDownProfissoes()
{
	$().SPServices({
        operation: "GetListItems",  // OperaÁ„o padr„o, sempre usar essa em consultas
        listName: "Profissao",         // Nome da lista que vocÍ vai pesquisar, È o nome da lista que aparece no Sharepoint
        //CAMLQuery: "<Query><Where><Eq><FieldRef Name='Title'/><Value Type='Text'>" + chaveProfissao + "</Value></Eq></Where></Query>",  // Aqui dentro vocÍ coloca a consulta caso exista, no meu caso n„o tenho consulta, apenas um ORDER BY
        CAMLQueryOptions: '<QueryOptions></QueryOptions>',  // OpÁıes de consulta 
        CAMLRowLimit: 0,    // Zero È o default, este par‚metro È usado em caso de paginaÁ„o

        // FunÁ„o callback
        completefunc: function (xData, Status) {
            $(xData.responseXML).find("[nodeName=z:row]").each(function () {
                $("#selQuestion3").append("<option title=\"" + $(this).attr("ows_Profissao").substring(0,60) + "\" value=\"" + $(this).attr("ows_Title").substring(0,60) + "\">" + $(this).attr("ows_Profissao").substring(0,60) + "</option>");
            })
        }
    });
}

function IsNumeric(sText)
{
	var ValidChars = "0123456789.";
	var IsNumber=true;
	var Char;
	
	
	for (i = 0; i < sText.length && IsNumber == true; i++) 
	  { 
	  Char = sText.charAt(i); 
	  if (ValidChars.indexOf(Char) == -1) 
	     {
	     IsNumber = false;
	     }
	  }
	return IsNumber;
}

/*
function ShowMessage(title, message)
{
	var modalWindow = {  
	    parent:"body",  
	    windowId:"modalWindowMessage",  
	    width:"auto",  
	    height:"auto",
		title:title,
	    close:function()  
	    {  
	        $(".modal-window").remove();  
	        $(".modal-overlay").remove();  
	    },  
	    open:function()  
	    {  
	        var modal = "";  
	        modal += "<div class=\"modal-overlay\"></div>";  
	        modal += "<div id=\"" + this.windowId + "\" class=\"modal-window\" style=\"width:auto; height:auto; margin: -91px 0 0 -221px;\">";  
	        modal += "<div class=\"modal-top\"><h5 class=\"modal-title\">"+this.title+"</h5></div>";
			modal += "<div class=\"modal-content\" style=\"height: 80px;\">";
			modal += "<p style=\"clear: both; font-size: 14px; margin-top: 20px; text-align: center;\">" + message + "<br /><br /><a id=\"fechar\" href=\"javascript:;\" onclick=\"javascript:modalWindow.close();;\">Fechar</a></p>";
			modal += "</div>";
			modal += "<div class=\"modal-bottom\"></div>";
	        modal += "</div>";      
	  
	        $(this.parent).append(modal);  
	  
	        $(".modal-top").append("<a class=\"close-window\"></a>");  
	        $(".close-window").click(function(){modalWindow.close();});  
	        $(".modal-overlay").click(function(){modalWindow.close();});  
	    }  
	};
	
	modalWindow.open(); 
}
*/

function ValidaFormBeforePost()
{
	var errorList = new Array();
	
	if (!$("input[title='Nome']").val()){
		errorList[errorList.length] = "Campo Nome é obrigatório";
	}

	if (!$("input[title='CPF']").val()){
		errorList[errorList.length] = "Campo CPF é obrigatório";
	}

	if (!$("input[title='Endereco']").val()){
		errorList[errorList.length] = "Campo Endereço é obrigatório";
	}

	if (!$("input[title='Cidade']").val()){
		errorList[errorList.length] = "Campo Cidade é obrigatório";
	}

	if (!$("input[title='CEP']").val()){
		errorList[errorList.length] = "Campo CEP é obrigatório";
	}

	if (!$("input[title='Telefone Fixo + DDD']").val()){
		errorList[errorList.length] = "Campo Telefone Fixo + DDD é obrigatório";
	}
	
	if (!$("input[title='Email']").val()){
		errorList[errorList.length] = "Campo E-mail é obrigatório";
	}
	
	if (!$("input[title='Email Confirmacao']").val()){
		errorList[errorList.length] = "Campo E-mail Confirmação é obrigatório";
	}
	
	if (!$("input[title='Assunto']").val()){
		errorList[errorList.length] = "Campo Assunto é obrigatório";
	}
	
	if (!$("textarea[title='Mensagem']").val()){
		errorList[errorList.length] = "Campo Mensagem é obrigatório";
	}

	if (errorList.length > 0)
	{
		var errorStr = "<ul>";
		
		for (var i = 0; i < errorList.length; i++)
		{
			errorStr = errorStr + "<li>" + errorList[i] + "</li>";
		}
		
		errorStr = errorStr + "</ul>";
		$("#errorMsg").html(errorStr);
		
		return false;
	} else {
		if ($("input[title='Email']").val() != $("input[title='Email Confirmacao']").val())
		{
			var errorStr = "<ul>";
			errorStr = errorStr + "<li>E-mail e E-mail Confirmação são diferentes</li>";
			errorStr = errorStr + "</ul>";
			$("#errorMsg").html(errorStr);
			
			return false;
		}
		
		if (!checkMail($("input[title='Email']").val()))
		{
			var errorStr = "<ul>";
			errorStr = errorStr + "<li>E-mail inválido</li>";
			errorStr = errorStr + "</ul>";
			$("#errorMsg").html(errorStr);
			
			return false;
		}
	}
	
	return true;
}

function ValidaFaleConoscoBeforePost()
{
	var errorList = new Array();
	
	if (!$("input[title='Nome']").val()){
		errorList[errorList.length] = "Campo Nome é obrigatório";
	}

	if (!$("input[title='CPF']").val()){
		errorList[errorList.length] = "Campo CPF é obrigatório";
	}

	if (!$("input[title='Email']").val()){
		errorList[errorList.length] = "Campo E-mail é obrigatório";
	}
	
	if (!$("input[title='Email Confirmacao']").val()){
		errorList[errorList.length] = "Campo E-mail Confirmação é obrigatório";
	}
	
	if (!$("input[title='Telefone']").val()){
		errorList[errorList.length] = "Campo Telefone é obrigatório";
	}
	
	if (!$("select[title='Identificacao']").val()){
		errorList[errorList.length] = "Campo Identificação é obrigatório";
	}
	
	if (!$("textarea[title='Mensagem']").val()){
		errorList[errorList.length] = "Campo Mensagem é obrigatório";
	}

	if (errorList.length > 0)
	{
		var errorStr = "<ul>";
		
		for (var i = 0; i < errorList.length; i++)
		{
			errorStr = errorStr + "<li>" + errorList[i] + "</li>";
		}
		
		errorStr = errorStr + "</ul>";
		$("#errorMsg").html(errorStr);
		
		return false;
	} else {
		if ($("input[title='Email']").val() != $("input[title='Email Confirmacao']").val())
		{
			var errorStr = "<ul>";
			errorStr = errorStr + "<li>E-mail e E-mail Confirmação são diferentes</li>";
			errorStr = errorStr + "</ul>";
			$("#errorMsg").html(errorStr);
			
			return false;
		}
		
		if (!checkMail($("input[title='Email']").val()))
		{
			var errorStr = "<ul>";
			errorStr = errorStr + "<li>E-mail inválido</li>";
			errorStr = errorStr + "</ul>";
			$("#errorMsg").html(errorStr);
			
			return false;
		}
	}
	
	return true;
}

function ValidaSejaParceiroBeforePost()
{
	var errorList = new Array();
	
	if (!$("input[title='Nome Empresa']").val())
	{
		errorList[errorList.length] = "Campo Nome da Empresa é obrigatório";
	}
	
	if (!$("input[title='Contato']").val())
	{
		errorList[errorList.length] = "Campo Contato é obrigatório";
	}
	
	if (!$("input[title='Endereco']").val())
	{
		errorList[errorList.length] = "Campo Endereço é obrigatório";
	}
	
	if (!$("input[title='Cidade']").val())
	{
		errorList[errorList.length] = "Campo Cidade é obrigatório";
	}
	
	if ($("select[title='Estado']").attr("selectedIndex") <= 0)
	{
		errorList[errorList.length] = "Campo Estado é obrigatório";
	}
	
	if (!$("input[title='CEP']").val())
	{
		errorList[errorList.length] = "Campo CEP é obrigatório";
	}
	
	if (!$("input[title='Telefone']").val())
	{
		errorList[errorList.length] = "Campo Telefone é obrigatório";
	}
	
	if (!$("input[title='Email']").val())
	{
		errorList[errorList.length] = "Campo E-mail é obrigatório";
	}

	if (errorList.length > 0)
	{
		var errorStr = "<ul>";
		
		for (var i = 0; i < errorList.length; i++)
		{
			errorStr = errorStr + "<li>" + errorList[i] + "</li>";
		}
		
		errorStr = errorStr + "</ul>";
		$("#errorMsg").html(errorStr);
		
		return false;
	} else {
		if (!checkMail($("input[title='Email']").val()))
		{
			var errorStr = "<ul>";
			errorStr = errorStr + "<li>E-mail inválido</li>";
			errorStr = errorStr + "</ul>";
			$("#errorMsg").html(errorStr);
			
			return false;
		}
	}


	return true;
}



function chatOnline(){
	$('.bt_chatOnline').click();
}

function ValidarCPFCNPJ(theCPF) 
{ 
  if (theCPF.value == "") 
  { 
    return (false); 
  } 
  if (((theCPF.value.length == 11) && (theCPF.value == 11111111111) || (theCPF.value == 22222222222) || (theCPF.value == 33333333333) || (theCPF.value == 44444444444) || (theCPF.value == 55555555555) || (theCPF.value == 66666666666) || (theCPF.value == 77777777777) || (theCPF.value == 88888888888) || (theCPF.value == 99999999999) || (theCPF.value == 00000000000))) 
  { 
    return (false); 
  } 


  if (!((theCPF.value.length == 11) || (theCPF.value.length == 14))) 
  { 
    return (false); 
  } 

  var checkOK = "0123456789"; 
  var checkStr = theCPF.value; 
  var allValid = true; 
  var allNum = ""; 
  for (i = 0;  i < checkStr.length;  i++) 
  { 
    ch = checkStr.charAt(i); 
    for (j = 0;  j < checkOK.length;  j++) 
      if (ch == checkOK.charAt(j)) 
        break; 
    if (j == checkOK.length) 
    { 
      allValid = false; 
      break; 
    } 
    allNum += ch; 
  } 
  if (!allValid) 
  { 
    return (false); 
  } 

  var chkVal = allNum; 
  var prsVal = parseFloat(allNum); 
  if (chkVal != "" && !(prsVal > "0")) 
  { 
    return (false); 
  } 

if (theCPF.value.length == 11) 
{ 
  var tot = 0; 

  for (i = 2;  i <= 10;  i++) 
    tot += i * parseInt(checkStr.charAt(10 - i)); 

  if ((tot * 10 % 11 % 10) != parseInt(checkStr.charAt(9))) 
  { 
    return (false); 
  } 
  
  tot = 0; 
  
  for (i = 2;  i <= 11;  i++) 
    tot += i * parseInt(checkStr.charAt(11 - i)); 

  if ((tot * 10 % 11 % 10) != parseInt(checkStr.charAt(10))) 
  { 
    return (false); 
  } 
} 
else 
{ 
  var tot  = 0; 
  var peso = 2; 
  
  for (i = 0;  i <= 11;  i++) 
  { 
    tot += peso * parseInt(checkStr.charAt(11 - i)); 
    peso++; 
    if (peso == 10) 
    { 
        peso = 2; 
    } 
  } 

  if ((tot * 10 % 11 % 10) != parseInt(checkStr.charAt(12))) 
  { 
    return (false); 
  } 
  
  tot  = 0; 
  peso = 2; 
  
  for (i = 0;  i <= 12;  i++) 
  { 
    tot += peso * parseInt(checkStr.charAt(12 - i)); 
    peso++; 
    if (peso == 10) 
    { 
        peso = 2; 
    } 
  } 

  if ((tot * 10 % 11 % 10) != parseInt(checkStr.charAt(13))) 
  { 
    return (false); 
  } 
} 
  return(true); 
} 

function ProcurarManuaisPorApoliceCPFCNPJ(){
	$("div.loading").show();
	$("#listacontratos").empty();
	
	var tagId = "";
	if ($("input[name='optTipoDoc']:checked").val() == 0) {
 		tagId = "CPF";
 	} else {								 		
 		tagId = "CNPJ";
 	}
 	
 	var apolice = $("#txtApolice").val();
 	
	var xmlRequest = "<ObterDadosConsolidadosEmissaoRequest><" + tagId + ">" + $("#txtCPF").val() + "</" + tagId + "><NumeroApolice>" + apolice + "</NumeroApolice></ObterDadosConsolidadosEmissaoRequest>";
	
 	$.ajax({
        type: "POST",
        url: "http://" + document.location.host + "/WSPortalInstitucionalLiberty/ControllerUI/wssegurado.asmx/ObterApolicesDoClienteLiberty",
        contentType: "application/json; charset=utf-8",
        data: "{idUsuario:'INSTITUCIONALLIBERTY', ativarTrace:false, XMLRequest:'" + xmlRequest + "'}",
        dataType: "json",

        success: function (msg) {
        	var x = msg.d.replace(" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"","");
            var ot = xml2json.parser(x);
            var th = '';
            var td = '';
            var lista = '<h5 style="margin-left: -19px;">Resultado da pesquisa</h5>';

			if (ot.obterdadosconsolidadosemissaoresult.contratoscol!=null){
				if(!$.isArray(ot.obterdadosconsolidadosemissaoresult.contratoscol.contrato)){
					ot.obterdadosconsolidadosemissaoresult.contratoscol.contrato = [ot.obterdadosconsolidadosemissaoresult.contratoscol.contrato];
				}
			
				var map = ot.obterdadosconsolidadosemissaoresult.contratoscol.contrato;
				var dominio = document.location.host;
				var _linkCG = "";
				var _linkSC = "";
				
				$.each(map, function(key, value) { 
					debugger;
					if (value!=null){
						
						if (value.linkdoccondicaogeral.length!=null) 
						{
							_linkCG = "<a target='_blank' href='" + "http://" + dominio + value.linkdoccondicaogeral + "'>"+ value.nomedoccondicaogeral +"</a><br />"
						} else 
						{
							_linkCG = "Manual do Segurado não disponível, por favor entre em contato com a Central de Atendimento.</br>";
						}
						
						if (value.linkdocservicoscomplementares.length!=null) 
						{
							_linkSC = "<a target='_blank' href='" + "http://" + dominio + value.linkdocservicoscomplementares + "'>"+ value.nomedocservicoscomplementares+"</a><br />"
						} else 
						{
							_linkSC = "Manual de Serviços Complementares não disponível, por favor entre em contato com a Central de Atendimento.";
						}
										
						lista += "<div>" + 
						             "<b>Produto: </b>" + value.codigoproduto + "&nbsp;&nbsp;&nbsp;" +
						             "<b>Apólice: </b>" + value.numeroapolice + "<br />" +
						             "<b>Vigência: </b>" + value.datainiciovigenciaapolice + "<b> à </b>" + value.dataterminiovigenciaapolice + "<br />" +
							         _linkCG +
							         _linkSC +    
						         "</div><br />";
					         
						if (apolice == value.numeroapolice && apolice > 0){
							lista = "<h5 style='margin-left: -19px;'>Resultado da pesquisa</h5>";
							lista += "<div>" +
							             "<b>Produto: </b>" + value.codigoproduto + "&nbsp;&nbsp;&nbsp;" +
							             "<b>Apólice: </b>" + value.numeroapolice + "<br />" +
							             "<b>Vigência: </b>" + value.datainiciovigenciaapolice + "<b> à </b>" + value.dataterminiovigenciaapolice + "<br />" +
									         _linkCG +
									         _linkSC +    
							         "</div><br />";
							return false;
						} 

					} else {
						lista = "<h5>Sua pesquisa não encontrou nenhum documento correspondente. Verifique se os dados informados estão corretos.</h5>";
					}
				});
            
        		if (lista != "") {
        	 		$(lista).appendTo("#listacontratos");
        	 	}

            } else {
        		$("<h5>Sua pesquisa não encontrou nenhum documento correspondente. Verifique se os dados informados estão corretos.</h5>").appendTo("#listacontratos");
        	}
									                
			$("div.loading").hide();
																                    
        },
        error: function (e) {
            $("Ocorreu um erro ao processar a consulta, por favor tente novamente mais tarde.").appendTo("#listacontratos");
        }

    });
}

function ProcurarManuaisPorApoliceCPFCNPJDuvidasApoio(){
	$("#listacontratos").empty();
	
	var errorMsg = "";
			
	var tagId = "";
	
	if ($("input[name='optTipoDoc']:checked").val() == 0) {
			tagId = "CPF";
	} else {								 		
	 		tagId = "CNPJ";
	}
	
	if ($("#txtApolice").val() == ""){
		errorMsg += "<span>O campo Número da Apólice deve ser preenchido!</span><br/>";
		$("#txtApolice").focus();
	}
	
	if ($("#txtCPF").val() == ""){
		errorMsg += "<span>O campo CPF/CNPJ deve ser preenchido!</span><br/>";
		$("#txtCPF").focus();
	}
	
	if (isNaN($("#txtApolice").val())){
		errorMsg += "<span>O campo Número da Apólice deve conter apenas números!</span><br/>";
        $("#txtApolice").focus();
    }

	if (errorMsg == "" && !ValidarCPFCNPJRadio(document.getElementById("txtCPF"),tagId)){
		errorMsg += "<span>CPF/CNPJ inválido!</span>";
		$("#txtCPF").focus();
	}
			
	if (errorMsg != ""){
		$("p#errorMsg").html(errorMsg);
		$("p#errorMsg").show();
		return false;
	}

	$("p#errorMsg").hide();
	$("p#errorMsg").html("");

	if(errorMsg == "")
	{
			$("div.loading").show();

		 	var apolice = $("#txtApolice").val();
		 	
			var xmlRequest = "<ObterDadosConsolidadosEmissaoRequest><" + tagId + ">" + $("#txtCPF").val() + "</" + tagId + "><NumeroApolice>" + apolice + "</NumeroApolice></ObterDadosConsolidadosEmissaoRequest>";
			
		 	$.ajax({
		        type: "POST",
        		url: "http://" + document.location.host + "/WSPortalInstitucionalLiberty/ControllerUI/wssegurado.asmx/ObterApolicesDoClienteLiberty",
		        contentType: "application/json; charset=utf-8",
		        data: "{idUsuario:'INSTITUCIONALLIBERTY', ativarTrace:false, XMLRequest:'" + xmlRequest + "'}",
		        dataType: "json",
		
		        success: function (msg) {
		        	var x = msg.d.replace(" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"","");
		            var ot = xml2json.parser(x);
		            var th = '';
		            var td = '';
		            var lista = '<h5 style="margin-left: -19px;">Resultado da pesquisa</h5>';
		
					if (ot.obterdadosconsolidadosemissaoresult.contratoscol!=null){
						if(!$.isArray(ot.obterdadosconsolidadosemissaoresult.contratoscol.contrato)){
							ot.obterdadosconsolidadosemissaoresult.contratoscol.contrato = [ot.obterdadosconsolidadosemissaoresult.contratoscol.contrato];
						}
					
						var map = ot.obterdadosconsolidadosemissaoresult.contratoscol.contrato;
						var dominio = document.location.host;
						var _linkCG = "";
						var _linkSC = "";
						
						$.each(map, function(key, value) { 
							debugger;
							if (value!=null){
								
								if (value.linkdoccondicaogeral.length!=null) 
								{
									_linkCG = "<a target='_blank' href='" + "http://" + dominio + value.linkdoccondicaogeral + "'>"+ value.nomedoccondicaogeral +"</a><br />"
								} else 
								{
									_linkCG = "Manual do Segurado não disponível, por favor entre em contato com a Central de Atendimento.</br>";
								}
								
								if (value.linkdocservicoscomplementares.length!=null) 
								{
									_linkSC = "<a target='_blank' href='" + "http://" + dominio + value.linkdocservicoscomplementares + "'>"+ value.nomedocservicoscomplementares+"</a><br />"
								} else 
								{
									_linkSC = "Manual de Serviços Complementares não disponível, por favor entre em contato com a Central de Atendimento.";
								}
												
								lista += "<div>" + 
								             "<b>Produto: </b>" + value.codigoproduto + "&nbsp;&nbsp;&nbsp;" +
								             "<b>Apólice: </b>" + value.numeroapolice + "<br />" +
								             "<b>Vigência: </b>" + value.datainiciovigenciaapolice + "<b> à </b>" + value.dataterminiovigenciaapolice + "<br />" +
									         _linkCG +
									         _linkSC +    
								         "</div><br />";
							         
								if (apolice == value.numeroapolice && apolice > 0){
									lista = "<h5 style='margin-left: -19px;'>Resultado da pesquisa</h5>";
									lista += "<div>" +
									             "<b>Produto: </b>" + value.codigoproduto + "&nbsp;&nbsp;&nbsp;" +
									             "<b>Apólice: </b>" + value.numeroapolice + "<br />" +
									             "<b>Vigência: </b>" + value.datainiciovigenciaapolice + "<b> à </b>" + value.dataterminiovigenciaapolice + "<br />" +
											         _linkCG +
											         _linkSC +    
									         "</div><br />";
									return false;
								} 
		
							} else {
								lista = "<h5>Sua pesquisa não encontrou nenhum documento correspondente. Verifique se os dados informados estão corretos.</h5>";
							}
						});
		            
		        		if (lista != "") {
		        	 		$(lista).appendTo("#listacontratos");
		        	 	}
		
		            } else {
		        		$("<h5>Sua pesquisa não encontrou nenhum documento correspondente. Verifique se os dados informados estão corretos.</h5>").appendTo("#listacontratos");
		        	}
											                
					$("div.loading").hide();
																		                    
		        },
		        error: function (e) {
		            $("Ocorreu um erro ao processar a consulta, por favor tente novamente mais tarde.").appendTo("#listacontratos");
		        }
		
		    });
 	}
}

/*=== script validação de CPF e CNPJ com escolha no radio buttom ==================*/
		
function ValidarCPFCNPJRadio(theCPF,tipoConsulta) 
{ 
  
  if (theCPF.value == "") 
  { 
    return (false); 
  } 
  if (((theCPF.value.length == 11) && (theCPF.value == 11111111111) || (theCPF.value == 22222222222) || (theCPF.value == 33333333333) || (theCPF.value == 44444444444) || (theCPF.value == 55555555555) || (theCPF.value == 66666666666) || (theCPF.value == 77777777777) || (theCPF.value == 88888888888) || (theCPF.value == 99999999999) || (theCPF.value == 00000000000))) 
  { 
    return (false); 
  } 


  if (!((theCPF.value.length == 11) || (theCPF.value.length == 14))) 
  { 
    return (false); 
  } 

  var checkOK = "0123456789"; 
  var checkStr = theCPF.value; 
  var allValid = true; 
  var allNum = ""; 
  for (i = 0;  i < checkStr.length;  i++) 
  { 
    ch = checkStr.charAt(i); 
    for (j = 0;  j < checkOK.length;  j++) 
      if (ch == checkOK.charAt(j)) 
        break; 
    if (j == checkOK.length) 
    { 
      allValid = false; 
      break; 
    } 
    allNum += ch; 
  } 
  if (!allValid) 
  { 
    return (false); 
  } 

  var chkVal = allNum; 
  var prsVal = parseFloat(allNum); 
  if (chkVal != "" && !(prsVal > "0")) 
  { 
    return (false); 
  } 

if (theCPF.value.length == 11 && tipoConsulta == "CPF") 
{ 
  var tot = 0; 

  for (i = 2;  i <= 10;  i++) 
    tot += i * parseInt(checkStr.charAt(10 - i)); 

  if ((tot * 10 % 11 % 10) != parseInt(checkStr.charAt(9))) 
  { 
    return (false); 
  } 
  
  tot = 0; 
  
  for (i = 2;  i <= 11;  i++) 
    tot += i * parseInt(checkStr.charAt(11 - i)); 

  if ((tot * 10 % 11 % 10) != parseInt(checkStr.charAt(10))) 
  { 
    return (false); 
  } 
} 
else 
{ 
  var tot  = 0; 
  var peso = 2; 
  
  for (i = 0;  i <= 11;  i++) 
  { 
    tot += peso * parseInt(checkStr.charAt(11 - i)); 
    peso++; 
    if (peso == 10) 
    { 
        peso = 2; 
    } 
  } 

  if ((tot * 10 % 11 % 10) != parseInt(checkStr.charAt(12))) 
  { 
    return (false); 
  } 
  
  tot  = 0; 
  peso = 2; 
  
  for (i = 0;  i <= 12;  i++) 
  { 
    tot += peso * parseInt(checkStr.charAt(12 - i)); 
    peso++; 
    if (peso == 10) 
    { 
        peso = 2; 
    } 
  } 

  if ((tot * 10 % 11 % 10) != parseInt(checkStr.charAt(13))) 
  { 
    return (false); 
  } 
} 
  return(true); 
} 
/*======================================================================================================================*/


function LSgetQueryStringValueByName(name)
{
  var match = RegExp('[?&]' + name + '=([^&]*)')
                    .exec(window.location.search);

    return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}

function LSpostToUrl(url, params, newWindow)
{
    var form = $('<form />').hide();
    form.attr('action', url)
        .attr('method', 'POST')
        .attr('enctype', 'application/x-www-form-urlencoded');

    if(newWindow)
    	form.attr('target', '_blank');

    function addParam(name, value, parent)
    {
        var fullname = (parent.length > 0 ? (parent + '[' + name + ']') : name);
        if(value instanceof Object)
        {
            for(var i in value)
            {
                addParam(i, value[i], fullname);
            }
        }
        else
        	$('<input type="hidden" />').attr({name: fullname, value: value}).appendTo(form);
    };

    addParam('', params, '');

    $('body').append(form);
    form.submit();
}

function SubmitAcesseAgora(){

	var IsFormCorrect = true;
	var m_usuario = $("#txtUsuario").val();
	var m_senha = $("#txtSenha").val();
	
	IsFormCorrect = (m_usuario == "" || m_senha == "");
	
	if(!IsFormCorrect){

		document.getElementById("errorMsg").innerHTML = "";

		LSpostToUrl('https://www.libertyweb.com.br/Login', { _usuario: m_usuario, _senha: m_senha, request:"LoginRq" }, true);

		$("#txtUsuario").val("");
		$("#txtSenha").val("");

	} else {
		document.getElementById("errorMsg").innerHTML = "<span>Os campos de Login e Senha são obrigatórios.</span>";
	}
}
/*======================================== Busca Cidade/Bairro Corretor e Oficina ========================================================*/

        $(document).ready(function () {
        	$("#UFCorretor").change(function()
        		{
        			$('#loadingCidade').show();
        			CarregaCidadesCorretor();
        			
        		}
        	);
        	
        	$("#CidadesCorretor").change(function()
        		{
        			$('#loadingBairro').show();
        			CarregaBairrosCorretor();
        		}
        	);
        	
        	$("#UFOficinas").change(function()
        		{
        			$('#loadingUFOficina').show();
        			CarregaCidadesOficina();
        		}
        	);
        	
        	$("#Servicos").change(function()
        		{
        			//$('#loadingServico').show();
        			CarregaCidadesOficina();
        		}
        	);
        	
			$.ajax({
                type: "POST",
                url: "http://" + document.location.host + "/WSPortalInstitucionalLiberty/ControllerUI/wsoficina.asmx/ConsultaClassificaoOficina",
                contentType: "application/json; charset=utf-8",
                data: "{idUsuario:'INSTITUCIONALLIBERTY', ativarTrace:false}",
                dataType: "json",
                success: function (msg) {
                	var x = msg.d.replace(" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"","");
                    myJsonObject = xml2json.parser(x);

					if (myJsonObject.obterclassificacaooficinaresult!=undefined &&
						myJsonObject.obterclassificacaooficinaresult.listaclassificacaooficina!=undefined)
	                {
						
						if (typeof(myJsonObject.obterclassificacaooficinaresult)!="undefined" ||
								typeof(myJsonObject.obterclassificacaooficinaresult.listaclassificacaooficina)!="undefined" ||
		                    	typeof(myJsonObject.obterclassificacaooficinaresult.listaclassificacaooficina.classificacaooficina)!="undefined")
		                {
	
		                    var options = '';
		                    $.each(myJsonObject.obterclassificacaooficinaresult.listaclassificacaooficina.classificacaooficina, function (index, value) {
		                    	options += '<option value="' + value.codigoclassificacao + '">' + value.descricaoclassificacao + '<\/option>';
		                    });
		                    $("#Servicos").append(options);
	                    }
	                }
                },
                error: function (e) {
                    alert("Error: " + e.d);
                }
            });

        });

        function CarregaCidadesOficina() {
        	$("#CidadesOficinas").html('<option value="">Selecione</option>');
        	if($("#UFOficinas").val()!=""){
	        	var xmlRequest = "<ObterCidadesOficinaRequest><CodigoClassificacao>"+$("#Servicos").val()+"</CodigoClassificacao><UF>"+$("#UFOficinas").val()+"</UF></ObterCidadesOficinaRequest>";
	
	            $.ajax({
	                type: "POST",
	                url: "http://" + document.location.host + "/WSPortalInstitucionalLiberty/ControllerUI/wsoficina.asmx/ConsultaCidadesOficina",
	                data: "{idUsuario:'INSTITUCIONALLIBERTY', ativarTrace:false, XMLRequest:'" + xmlRequest + "'}",
	                contentType: "application/json; charset=utf-8",
	                dataType: "json",
	                success: function (msg) {
	                	var x = msg.d.replace(" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"","");
	                    myJsonObject = xml2json.parser(x);
	                    
	                    if (typeof(myJsonObject.obtercidadesoficinaresult)=="undefined" ||
	                    	typeof(myJsonObject.obtercidadesoficinaresult.listacidade)=="undefined" ||
	                    	typeof(myJsonObject.obtercidadesoficinaresult.listacidade.cidade)=="undefined")
	                    {
	                    	$("#CidadesOficinas").hide();
	                    	$("#CidadesOficinasMessage").show();
	                    	$('#loadingUFOficina').hide();
	                    	$("#btProcurarOficinas").hide();
	                    } else {
	                    	$("#CidadesOficinas").show();
	                    	$("#CidadesOficinasMessage").hide();
	                    	$("#btProcurarOficinas").show();
	                    	
		                    var options = '';
		                    if(typeof(myJsonObject.obtercidadesoficinaresult.listacidade.cidade)!="undefined"){
			                    $.each(myJsonObject.obtercidadesoficinaresult.listacidade.cidade, function(index, value){
			                    	if(typeof(value.nomecidade)=="undefined"){
			                    		options += '<option value="' + value + '">' + value + '</option>';
			                    	}else{
			                        	options += '<option value="' + value.nomecidade + '">' + value.nomecidade + '</option>';
			                        }
			                    });
				            }
				            if(options==""){
				            	options = "<option value='selecione'>Selecione</option>";
				            	$("#CidadesOficinas").html(options);
				            }
				            else
				            {
				            	$("#CidadesOficinas").append(options);
				            	$('#loadingUFOficina').hide();
				            }
		                    
		                 }
	                },
	                error: function (e) {
	                    alert("Error: " + e.d);
	                }
	            });
	    	}
        }        

        function CarregaCidadesCorretor() {
        	if($("#UFCorretor").val()!=""){
	        	var xmlRequest = "<ObterCidadesComCorretoresCadastradosRequest><UF>"+$("#UFCorretor").val()+"</UF><Companhias><CodigoCompanhia>1</CodigoCompanhia></Companhias></ObterCidadesComCorretoresCadastradosRequest>";
	
	            $.ajax({
	                type: "POST",
	                url: "http://" + document.location.host + "/WSPortalInstitucionalLiberty/ControllerUI/wscorretor.asmx/ObterCidadesCorretoresCadastrados",
	                data: "{idUsuario:'INSTITUCIONALLIBERTY', ativarTrace:false, XMLRequest:'" + xmlRequest + "'}",
	                contentType: "application/json; charset=utf-8",
	                dataType: "json",
	                success: function (msg) {
	                	var x = msg.d.replace(" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"","");
	                    myJsonObject = xml2json.parser(x);
	                    var options = "";
	                    if(typeof(myJsonObject.obtercidadescomcorretorescadastradosresult.listacidades.cidade)!="undefined"){
		                    $.each(myJsonObject.obtercidadescomcorretorescadastradosresult.listacidades.cidade, function(index, value){
		                    	if(typeof(value.nomecidade)=="undefined"){
		                    		options += '<option value="' + value + '">' + value + '</option>';
		                    	}else{
		                        	options += '<option value="' + value.nomecidade + '">' + value.nomecidade + '</option>';
		                        }
		                    });
			            }
			            if(options != "")
			            {
			            	$("#CidadesCorretor").append(options);
			            	$('#loadingCidade').hide();
			            }
	                    

	                },
	                error: function (e) {
	                    alert("Error: " + e.d);
	                }
	            });
	    	}
        }        

        function CarregaBairrosCorretor() {
        	if($("#CidadesCorretor").val()!=""){
	        	var xmlRequest = "<ObterBairrosComCorretoresCadastradosRequest><UF>"+$("#UFCorretor").val()+"</UF><Cidade>"+$("#CidadesCorretor").val()+"</Cidade><Companhias><CodigoCompanhia>1</CodigoCompanhia></Companhias></ObterBairrosComCorretoresCadastradosRequest>";
	            $.ajax({
	                type: "POST",
   	                url: "http://" + document.location.host + "/WSPortalInstitucionalLiberty/ControllerUI/wscorretor.asmx/ObterBairrosCorretoresCadastrados",
	                data: "{idUsuario:'INSTITUCIONALLIBERTY', ativarTrace:false, XMLRequest:'" + xmlRequest + "'}",
	                contentType: "application/json; charset=utf-8",
	                dataType: "json",
	                success: function (msg) {
	                	var x = msg.d.replace(" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"","");
	                    myJsonObject = xml2json.parser(x);
	                    var options = "";
	                    if(typeof(myJsonObject.obterbairroscomcorretorescadastradosresult.listabairros.bairro)!="undefined"){
	                    	if(!$.isArray(myJsonObject.obterbairroscomcorretorescadastradosresult.listabairros.bairro)){
	                    		myJsonObject.obterbairroscomcorretorescadastradosresult.listabairros.bairro = [myJsonObject.obterbairroscomcorretorescadastradosresult.listabairros.bairro];
	                    	}
		                    $.each(myJsonObject.obterbairroscomcorretorescadastradosresult.listabairros.bairro, function(index, value){
		                    	if(typeof(value.nomebairro)!="object"){
		                        	options += '<option value="' + value.nomebairro + '">' + value.nomebairro + '</option>';
		                        }
		                    });
			            }
			            if(options != "")
			            {
	                    	$("#BairrosCorretor").append(options);
			            	$('#loadingBairro').hide();
			            }
	                    
	                },
	                error: function (e) {
	                    alert("Error: " + e.d);
	                }
	            });
	    	}
        }        


		function BuscaCorretores(){
			var state = $("#UFCorretor").val();
			var city = $("#CidadesCorretor").val();
			var neighborhood = $("#BairrosCorretor").val();
			
			var msg = "";
			if(state == "selecione" || state == ""){msg += "<span>O campo Estado é obrigatório.</span>";}
			if(city == "selecione" || city == ""){msg += "<span>O campo Cidade é obrigatório.</span>";}
			if(neighborhood == "selecione" || neighborhood == ""){msg += "<span>O campo Bairro é obrigatório.</span>";}
			if(msg!=""){
				$("#spnMsgCorretor").html(msg);
			} else {
				k="'ST=" + state + "&CT=" + city + "&NH=" + neighborhood + "'";
				scope="corretores";
				buscaResultado(k,scope);
			}

		}
		
		function BuscaOficinas(){
			var service = $("#Servicos").val();
			var state = $("#UFOficinas").val();
			var city = $("#CidadesOficinas").val();
			

			var msg = "";
			if(service == "selecione" || service == ""){msg += "<span>O campo Serviço é obrigatório.</span>";}
			if(state == "selecione" || state == ""){msg += "<span>O campo Estado é obrigatório.</span>";}
			if(city == "selecione" || city == ""){msg += "<span>O campo Cidade é obrigatório.</span>";}
			if(msg!=""){
				$("#spnMsgOficinas").html(msg);
			} else {
				k="'SE=" + service +"&ST=" + state + "&CT=" + city + "'";
				scope="oficinas";
				buscaResultado(k,scope);
			}
		}

