$.ajaxSetup({
    type: "POST",
	beforeSend:function(){
			//$('#fade').show();
	},
	success:function(){
//		$('#fade').hide();
	},
    error:function(x,e){
        if(x.status==0){
            alert('You are offline!!\n Please Check Your Network.');
        }else if(x.status==404){
            alert('URL não encontrada.');
        }else if(x.status==500){
            trata_erro(x.responseText,'','');
        }else if(e=='parsererror'){
            alert('Erro.\nVocê pode não estar conectado, reconecte-se.');
        }else if(e=='timeout'){
            alert('Servidor demorou para responder.');
        }else {
            alert('Erro desconhecido.\n'+x.responseText);
        }
    }
});




function adiciona_carrinho(qtd, id){
	var fechar = "<h3 align=right><a href='#' onclick=\"$('#fade').hide();$('#detalhes').hide();\">Fechar[x]</a></h3>";

	alert(qtd);
		$.ajax({
	  type: "post",
	  dataType:'html',
	  async:false,
	  data: {id_promocao:id,qtd: qtd }, // assuming this == the form
	  url: 'pagseguro/adiciona_carrinho.php',
	  success: function(x){
			if (x){
				$.post('pagseguro/carrinho.php',{},function(x){
					$('#fade').show();
					$('#detalhes').html(fechar+x);
					$('#detalhes').show();
				})
			}	
	  } // end success
	}); // fim ajax

}
function ver_detalhes(id, tabela){
	$.post('index.php',{detalhes:'promocoes',id:id},function(x){
														   $('#fade').show();
														   $('#detalhes').html(x);
														   $('#detalhes').css('width','640px');
														   $('#detalhes').show();
														   });
}


var acProcurar = {	        minChars: 1,
		delay:1500,
		max: 100,
		width: 600,
		dataType: 'json', // this parameter is currently unused
		extraParams: {
			format: 'json', //pass the required context to the Zend Controller,
			filtro: 'texto',
			municipio: function(){return $('#municipio option:selected').val();},
			chave: function(){return $(this).val();}
		},
		queryParam: "nome",
		parse: function(data) {
			var parsed = null;
			if (data['QTDE']>0){
				data = data['LISTA'];
				parsed = [];
				

				for (var i = 0; i < data.length; i++) {
					parsed[parsed.length] = {
						data: data[i],
						value: data[i].nome,
						result: $('<textarea/>').html(data[i].nome + '-' + data[i].fone).val()
					};
				}
				return parsed;
			}else{
				$('#fone').val('');
				$('#nome').val('');	                
				return [];
			}
		},
		formatItem: function(item) {
			if (item.imagem != null) item.nome = "<img src='http://www.bignegocios.com.br/patrocinadores/"+item.imagem+"'/>";
			$('#fade').hide();
			return  item.nome+ ' (' +item.fone+ ')';

		}
	};

var acPatrocinador = {	        minChars: 1,
		delay:1500,
		max: 100,
		width: 600,
		dataType: 'json', // this parameter is currently unused
		extraParams: {
			format: 'json', //pass the required context to the Zend Controller,
			filtro: 'texto',
			municipio: function(){return $('#municipio option:selected').val();},
			chave: function(){return $(this).val();}
		},
		queryParam: "nome",
		parse: function(data) {
			var parsed = null;
			if (data['QTDE']>0){
				data = data['LISTA'];
				parsed = [];
				

				for (var i = 0; i < data.length; i++) {
					parsed[parsed.length] = {
						data: data[i],
						value: data[i].nome,
						result: $('<textarea/>').html(data[i].nome + '-' + data[i].fone).val()
					};
				}
				return parsed;
			}else{
				$('#patrocinador_lista').val('');	                
				$('#id_lista').val('');	                
				return [];
			}
		},
		formatItem: function(item) {
			if (item.imagem != null) item.nome = "<img src='http://www.bignegocios.com.br/patrocinadores/"+item.imagem+"'/>";
			$('#fade').hide();
			return  item.nome+ ' (' +item.fone+ ')';

		}
	};

$(document).ready(function(){
						   
						   
						   
	$('#tabs').tabs();

	$('#dialog').dialog('close');
	
				$('#dialog').dialog({

					autoOpen: false,

					width: 600,
					modal: true,

					buttons: {

						"Ok": function() { 

							$(this).dialog("close"); 

						}
//						, 

/*						"Fechar": function() { 

							$(this).dialog("close"); 

						} 
*/
					}

				});
	
	
	
	$('#contato_enviar').click(function(){
		contato();										
	});
	
	$('.anuncios_esquerda').cycle(
				{ fx:   'all',
				  timeout: 4000}
				  );

	$('.anuncios_direita').cycle(
				{ fx:   'all',timeout: 10000});
	//fx: 'scrollLeft'
	$('#temas').change(function(){
		$.post('temas.php',{tema: $('#temas option:selected').val()},function(x){$('#fade').hide(); window.location.href="http://www.bignegocios.com.br";});
								});

	$('.lista').each(function (){
		$(this).autocomplete('vemnimin.php',acProcurar).result(function(e,data){$('#fone').val(data.fone);$('#nome').val(data.nome);$('#fade').hide();});
	});
	
	$('.patrocinador').each(function (){
		$(this).autocomplete('vemnimin.php',acPadrocinador).result(function(e,data){$('#id_lista').val(data.id_lista);$('liga_patrocinador').val(data.nome);$('#fade').hide();});
	});
	


	function enableSpecificDates(date) {
		var month = date.getMonth();
		var day = date.getDate();
		var year = date.getFullYear();
		var daysToEnable = date;
		for (i = 0; i < daysToEnable.length; i++) {
			if ($.inArray((month + 1) + '-' + day + '-' + year, daysToEnable) != -1) {
				return [true];
			}
		}
		return [false];
	}
	
	$( "#calendario_agenda" ).datepicker({numberOfMonths: 1, 

								//			beforeShowDay: enableSpecificDates,
//										dateFormat: 'mm-dd-yy',
										 showOptions: {direction: 'up' }});
	$.post('cadastros/patrocinador.php',{'listar':'sim'},function(x){$('#dentro').html(x)});	
	
//	$("#calendario_agenda").datepicker($.datepicker.regional['pt-BR']);	

/*
	$("#lista").flexigrid({
		url: 'patrocinadores.php',
		dataType: 'json',
		colModel : [
			{display: 'Lista', name : 'id_lista', width : 40, sortable : true, align: 'center'},
			{display: 'Nome', name : 'nome', width : 180, sortable : true, align: 'left'},
			{display: 'Website', name : 'website', width : 120, sortable : true, align: 'left'},
			{display: 'Fone', name : 'fone', width : 130, sortable : true, align: 'left', hide: true},
			{display: 'Logo', name : 'logo', width : 80, sortable : true, align: 'right'}
			],
		buttons : [
			{name: 'Add', bclass: 'add', onpress : false},
			{name: 'Delete', bclass: 'delete', onpress : false},
			{separator: true}
			],
		searchitems : [
			{display: 'Lista', name : 'id_lista'},
			{display: 'Nome', name : 'nome', isdefault: true}
			],
		sortname: "iso",
		sortorder: "asc",
		usepager: true,
		title: 'Patrocinadores',
		useRp: true,
		rp: 15,
		showTableToggleBtn: true,
		width: 700,
		height: 200
	});   					     
*/

});


var cpfOK = false;

function hide_panels(n){
	for (var x = 0; x < 20 ; x++){
		if ($('#painel_'+x) != null)
			$('#painel_'+x).hide();
	}
}


 function desabilitarAlgunsDias(date) {
      var m = date.getMonth(), d = date.getDate(), y = date.getFullYear();
      if ( $.inArray( y+'-'+(m+1)+'-'+d, datasCalendario) == -1) {
        return [true];
      }
      return [false];
    }





function somente_numeros(campo){
          var digits=",.0123456789"
          var campo_temp
          for (var i=0;i<campo.val().length;i++)
            {
              campo_temp=campo.val().substring(i,i+1)    
              if (digits.indexOf(campo_temp)==-1)
                {
                  campo.val = campo.val().substring(0,i);
                  break;
                }
            }
}
function carrega_captcha(){
	
	$('#div_captcha').html("<img src='images/ajax.gif' />");
	$('#div_captcha').load('captcha.php',$('input[id=nome]').focus());
	
}
function login(login, senha){
 var pwEncrypt;

	pwEncrypt = $().crypt( {
		method: 'md5',
		source: senha
	});
	
		$.post('login.php',{login: login, senha: pwEncrypt},function(x){
																						 alert(x);
																						 window.location.reload();

																						 });
}

function limpar_carrinho(){
  		$.post('pagseguro/carrinho.php',{action:'limpar'},function(x){ if (x == 'ok') window.location.reload();});
}
function logoff(){
 		$.post('login.php',{action:'logoff'},function(x){ if (x == 'ok') window.location.reload();});
}

function logar(){
	$.post('login.php',{},function(x){
	$('#fade').show();
	$('#div_resultados').html(x);		
	$('#div_resultados').show();	

								   });
}

function cadastra_usuario(){
	$('#fade').show();
	$('#div_resultados').load('cadastro_usuarios.php').show();
}
function gravar_usuario(){

	if ($('#cad_login').val() != ''){	
		if ($('#cad_login').val() != ''){			//if ($('#cpf').val() != ''){
			if (($('input[id=cad_senha]') != null)||($('input[id=cad_senha]').val() == $('#conf_senha').val())){
				var senha = '';
				if ($('input[id=senha]') == null) {senha = '';}else{senha = $('input[id=senha]').val();}	
		//		begin_transaction();
				$('#div_gravar_usuario').load('cadastro_usuarios.php?acao=gravar',{
									cad_senha : senha,
									cad_login : $('input[id=cad_login]').val(),
									nome : $('input[id=nome]').val(),
									endereco : $('input[id=endereco]').val(),
									cpf : $('input[id=cpf]').val(),							
									email : $('input[id=email]').val(),
									cep : $('input[id=cep]').val(),
									bairro : $('input[id=bairro]').val(),
									municipio : $('input[id=municipio]').val(),
									uf : $('input[id=uf]').val(),
									fone1 : $('input[id=fone1]').val(),
									fone2 : $('input[id=fone2]').val(),
									celular : $('input[id=celular]').val()
						},function(transport){
							var ok = transport;
		//					var ok = r.substring(0, (i = r.indexOf(';')));r = r.substring(++i);	
		
							if (ok == "OK"){
										$('#div_gravar_usuario').html('Gravado com sucesso!!!');		
		//						end_transaction();						
							}else{
								$('#div_gravar_usuario').html(ok);		
							}
						});
							
			}else{
				$('#div_gravar_usuario').html('Senha incorreta !!!');		
			}
		}else{
			$('#div_gravar_usuario').html('CPF incorreto');				
		}
	}else{
		$('#div_gravar_usuario').html('Login incorreto');				
	}
		

}

function pesquisar(tabela){

switch (tabela){
	case 'classificados':
		var valores = function (){ return $('#descricao').val()+';'+$('#cidade option:selected').val()+';'+$('#tipo option:selected').val();};
		var campos = 'descricao;cidade;tipo';
	break;
	case 'promocoes':
		var valores = function (){ return $('#descricao').val()+';'+$('#cidade option:selected').val();};
		var campos = 'descricao;cidade';		
	break;	
}
$('#table_promocoes').children().remove();
	$.ajax({
	  type: "post",
	  dataType:'json',
	  data: {acao: 'pesquisar', valores : valores, campos : campos}, // assuming this == the form
	  url: 'cadastros/'+tabela+'.php',
	  success: function(data){
		  var qtd = data['qtde'];
		  var dados = data['itens'];
		  if (qtd > 0 ){
			  for (var x = 0; x < qtd; x++){

				  var linha = dados[x];
			  		$('#table_promocoes').append("<tr  class='ui-corner-all'>"+
					"<td class='' style='border:0px;padding-bottom:1px; '>"+
					"<div style='width:580px; overflow=x:hidden'>"+
					"<a style='float:right' href='#' onClick=\"ver_detalhes("+linha['id']+",'promocoes')\">"+
					"<img src='promocoes/"+linha['id']+"/"+linha['imagem']+"' title='"+linha['titulo']+"' width='580' ></a></div></td></tr>");
		  } // fim for
		  } // fim if
	

/*
('<tr><td>'+$(this).titulo+'</td>'+'<td>'+$(this).descricao+'</td>'+'<td>'+$(this).termos+'</td>'+'<td>'+$(this).inicio+'</td>'+'<td>'+$(this).fim+'</td>'+'<td>'+$(this).limite+'</td>'+'<td>'+$(this).municipio+'</td>'+'<td>'+$(this).imagem+'</td>'+'<td>'+$(this).limite_usuario+'</td><td>'+$(this).valor+'</td>'+'</tr>');
*/
		  } // end success
	}); // fim ajax
} // fum function pesquisar
						




function excluir(id,tabela, tab){
  if (confirm('Deseja excluir este registro ?'))
	$.ajax({
	  type: "post",
	  data: {id:id, tabela : tabela, div: tab}, // assuming this == the form
	  url: 'cadastros/delete.php',
	  success: function(txt){
		window.location.href="index.php#"+tab;
		window.location.reload();
	  }
	});
}
						

function captcha(){
	$('#div_gravar_usuario').html("<img src='images/ajax.gif' />");
	//serial.replace('=',':'),
	var serial = $("#captcha_form").serialize();
	$.ajax({
	  type: "post",
	  data: serial, // assuming this == the form
	  url: 'captcha.php',
	  success: function(txt){
			if (txt =="OK"){
				gravar_usuario();
			}else{
				$('#div_gravar_usuario').html("");
				alert(txt);
			}
		}
	});
}


function mostra_patrocinio(e,img){
	var posx = 0;
	var posy = 0;
		
	if (!e) var e = window.event;

	if (e.pageX || e.pageY) 	{
		posx = e.pageX;
		posy = e.pageY;
	}
	else if (e.clientX || e.clientY) 	{
		posx = e.clientX ;
		posy = e.clientY ;
	}else{
		posx = e.X ;
		posy = e.Y ;
		
	}
	
	$('#hint').html("<img src='"+img.src+"' width='300px' height='150px'/>");				
	$('#hint').css({position:'absolute'});
	$('#hint').css({left:'25%'});
	$('#hint').css({top:posy+'px'});
	$('#hint').show();

	
	
}

function novo(tabela){
  var link = '';
  var title = '';
  switch (tabela){
    case 'classificados':
	link = 'cadastros/classificados.php?acao=form&altura=600&largura=800';
	title = '<h3>Anúncio Classificado</h3>';
      break;
    case 'usuarios':
	link = 'cadastros/usuarios.php?acao=form&altura=600&largura=800';
	title = '<h3>Cadastro Usuários</h3>';
      break;
    case 'promocoes':
	link = 'cadastros/promocoes.php?acao=form&altura=600&largura=800';
	title = '<h3>Promoção</h3>';		
      break;
    case 'eventos':
	link = 'cadastros/agenda.php?acao=form&altura=600&largura=800';
	title = '<h3>Agenda/Evento</h3>';
      break;
  }

    $.post(link,{},function(x){
      $.blockUI({ 
	    theme:     true,
	    draggable: true,
	    bindEvents: true,
	    showOverlay: true,
	    title: title,
	    themedCSS: {
		width: 'auto',
		height:'auto',
		left:'30%',
		fontsize:'xxx-small',
		top:'20%'
	    },
	message: x });
/*
      $.blockUI({ 
	    theme:     true,
	    draggable: true,
	    bindEvents: true,
	    showOverlay: true,
	    themedCSS: {
		width: 'auto',
		height:'auto',
		left:'30%',
		  fontsize:'xxx-small',
		top:'20%'
	    },
	  title:   title, 
	  message:  x 
	  //timeout:   2000 
	}); 
*/	
    });
  
}

function seta_data(obj,data){
    dateParts = data.match(/(\d+)/g)
    realDate = new Date(dateParts[0], dateParts[1] - 1, dateParts[2]);  
                                    // months are 0-based!

//	$('#'+obj).datepicker({ dateFormat: 'yy-mm-dd' }); // format to show
//	$('#'+obj).datepicker('setDate', realDate);	
	
//	$('#'+obj).datepicker({ dateFormat: 'dd/mm/yyyy' });	
//	$('#'+obj).datepicker('setDate', data);
}

function mostra_hint(e,oque){
	var posx = 0;
	var posy = 0;
		
	if (!e) var e = window.event;

	if (e.pageX || e.pageY) 	{
		posx = e.pageX;
		posy = e.pageY;
	}
	else if (e.clientX || e.clientY) 	{
		posx = e.clientX ;
		posy = e.clientY ;
	}else{
		posx = e.X ;
		posy = e.Y ;
	}
	
	if (oque == 'procurar_lista'){
		$('#hint').html("Clique para procurar na lista telefnica");
	}else if (oque == 'logar'){
		$('#hint').html("Clique para efetuar seu login");		
		
	}else if (oque == 'sms'){
		$('#hint').html("Clique para envisar SMS grtis para celulares claro");
	}else if (oque == 'games'){
		$('#hint').html("Clique para se divertir com diversos jogos !");
	}else{
		$('#hint').html(oque);		
	}

	$('#hint').css({position : 'absolute'});
	$('#hint').css({left : posx+'px'});
	$('#hint').css({top : posy+'px'});
	$('#hint').show();
	
	
	
}

function posiciona(e,painel){
	var posx = 0;
	var posy = 0;
		
	if (!e) var e = window.event;

	if (e.pageX || e.pageY) 	{
		posx = e.pageX;
		posy = e.pageY;
	}
	else if (e.clientX || e.clientY) 	{
		posx = e.clientX ;
		posy = e.clientY ;
	}else{
		posx = e.X ;
		posy = e.Y ;
		
	}
	
	$('#'+painel).css({position : 'absolute'});
	$('#'+painel).css({left : posx + 'px'});
	$('#'+painel).css({top : posy + 'px'});
	$('#'+painel).show();
	
	
	
}


function sair(){
	$('#detalhes').load('sair.php',function(txt){alert(txt);});
	window.location.reload();
}







function fade_imagem(src){
	$('#grande').fadeOut();
	$('#grande').attr('src',src);
	$('#grande').fadeIn();
}






	

var DateObj = new Date();
var DataHoje;
DataHoje = DateObj.getDate();
DataHoje += " de ";
switch(DateObj.getMonth())
{
	case 1: DataHoje +=	"Fevereiro"; break;
	case 2: DataHoje +=	"Maro"; break;
	case 3: DataHoje +=	"Abril"; break;
	case 4: DataHoje +=	"Maio"; break;
	case 5: DataHoje +=	"Junho"; break;
	case 6: DataHoje +=	"Julho"; break;
	case 7: DataHoje +=	"Agosto"; break;
	case 8: DataHoje +=	"Setembro"; break;
	case 9: DataHoje +=	"Outubro"; break;
	case 10: DataHoje += "Novembro"; break;
	case 11: DataHoje += "Dezembro"; break;
	default: DataHoje += "Janeiro"; break;
}
DataHoje += " de ";
DataHoje += DateObj.getYear();



function validaCPF() {

                 var cpf = $('#cpf').val();
                 var erro = new String;
                 if (cpf.length < 11) erro += "Sao necessarios 11 digitos para verificacao do CPF! \n\n";
                 var nonNumbers = /\D/;
                 if (nonNumbers.test(cpf)) erro += "A verificacao de CPF suporta apenas numeros! \n\n";
                 if (cpf == "00000000000" || cpf == "11111111111" || cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" || cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" || cpf == "88888888888" || cpf == "99999999999"){
                        erro += "Numero de CPF invalido!"
               }
               var a = [];
               var b = new Number;
               var c = 11;
               for (i=0; i<11; i++){
                       a[i] = cpf.charAt(i);
                       if (i < 9) b += (a[i] * --c);
               }
               if ((x = b % 11) < 2) { a[9] = 0 } else { a[9] = 11-x }
               b = 0;
               c = 11;
               for (y=0; y<10; y++) b += (a[y] * c--);
              if ((x = b % 11) < 2) { a[10] = 0; } else { a[10] = 11-x; }
               if ((cpf.charAt(9) != a[9]) || (cpf.charAt(10) != a[10])){
                       erro +="Digito verificador com problema!";
               }
               if (erro.length > 0){
                       alert(erro);
                       return false;
               }
               return true;
       }
       
       
function mascara(formato,objeto){
	
//onlynum(objeto);
//campo = eal (objeto);

campo = objeto;

// CEP
if (formato=='CEP'){
separador = '-';
conjunto1 = 5;
if (campo.value.length == conjunto1){
campo.value = campo.value + separador;
}
}

if (formato=='HORA'){
separador = ':';
conjunto1 = 2;
if (campo.value.length == conjunto1){
campo.value = campo.value + separador;
}
}


// DATA
if (formato=='DATA'){
separador = '/';
conjunto1 = 2;
conjunto2 = 5;
if (campo.value.length == conjunto1){
campo.value = campo.value + separador;
}
if (campo.value.length == conjunto2){
campo.value = campo.value + separador;
}
}
//CPF
if (formato=='CPF'){
separador = '.';
digito = '-';
conjunto1 = 3;
conjunto2 = 7;
conjunto3 = 11;
conjunto4 = 15;
if (campo.value.length == conjunto1){
campo.value = campo.value + separador;
}
if (campo.value.length == conjunto2){
campo.value = campo.value + separador;
}
if (campo.value.length == conjunto3){
campo.value = campo.value + digito;
}

}



// TELEFONE
if (formato=='TELEFONE'){
separador = '-';
conjunto1 = 4;
if (campo.value.length == conjunto1){
campo.value = campo.value + separador;
}
}


return campo.value;
}
       
