$(function() {
	// Váriaveis globais
	count_select = 0;
	formLoading = '';
	
	//Focus
	$(".focus").focus();
			
	// Temporario - Msg Post
	$(".msgAjax").html()?messageBox($(".msgAjax").html(),'resp_geral','h_geral',-48):'';
	
	// Rollover images
	$('.rollover').live('mouseover',function(){
        $(this).attr('src', $(this).attr('hover'));
    });
	$('.rollover').live('mouseout',function(){
        $(this).attr('src', $(this).attr('original'));
	});
		
	// Visualização de imagem	
	$(".imagem").fancybox({
		'titlePosition'  : 'inside',
		'transitionIn'	: 'elastic',
		'transitionOut'	: 'elastic'	,
		'centerOnScroll': true,
		'autoScale' : true,
		'titleShow' : true,
		'padding': 0
	});
	
	$('.ajaxForm').bind('submit', function() {
		var formId = $(this).attr('id');
		var htmlSubmit = new Array();
		
		$(this).ajaxSubmit({
			dataType: 'json',
			cache: false,
			beforeSubmit: function(){
				$('#' + formId + ' [type="submit"]').each(function(d){
					htmlSubmit[d] = $(this);
					var div = '<div class="ajaxFormLoading" style="background-color: ' + $(this).css('backgroundColor') + '; width:' + $(this).outerWidth() + 'px; height:' + $(this).outerHeight() + 'px; font-size: 1px;">&nbsp;</div>';
					$(this).replaceWith(div);
				});
			},
			complete: function(){
				$('#' + formId + ' [class="ajaxFormLoading"]').each(function(d){
					$(this).replaceWith(htmlSubmit[d]);
				});
			},
			success: respFormulario,
			error: errorAjax
		});
		return false;
	});
	
	// Carrega mapas
	if($(".googleMaps").length){
		$(".googleMaps").each(function(){
			loadGoogleMaps($(this).attr('id'));
		});
	}	
}); 

function loadGoogleMaps(identificador) {
    var endereco = $('#' + identificador + '_endereco').val();
	var utilizar = parseInt($('#' + identificador + '_utilizar_lat_lng').val())	
	
	var myOptions = {
			  zoom: 16,
		   	  scrollwheel: false,
			  mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	map = new google.maps.Map(document.getElementById(identificador), myOptions);
    
	if(utilizar){
		var latlng = new google.maps.LatLng($('#' + identificador + '_latitude').val(), $('#' + identificador + '_longitude').val());

		map.setCenter(latlng);
		  
		var marker = new google.maps.Marker({
			position: latlng,
			map: map
		});
		  
		google.maps.event.addListener(marker, 'click', function() {
			map.setZoom(16);
			map.setCenter(latlng);
		});
	}else{	
		geocoder = new google.maps.Geocoder();
   
		if(geocoder){
			geocoder.geocode( { 'address': endereco}, function(results, status) {
				if (status == google.maps.GeocoderStatus.OK) {
					  latlng = new google.maps.LatLng(-25.437425,-49.281007); //results[0].geometry.location
					  
					  map.setCenter(latlng);
					  
					  var icone = new google.maps.MarkerImage(href + '/imagens/mapas/dom_parma.png',
						  // This marker is 20 pixels wide by 32 pixels tall.
						  new google.maps.Size(38, 34),
						  // The origin for this image is 0,0.
						  new google.maps.Point(0,0),
						  // The anchor for this image is the base of the flagpole at 0,32.
						  new google.maps.Point(11, 33));
					  
					  var marker = new google.maps.Marker({
						position: latlng,
						map: map,
						icon: icone
					  });
					  
					  google.maps.event.addListener(marker, 'click', function() {
						  map.setZoom(16);
						  map.setCenter(latlng);
					  });
					  
					  var icone_e = new google.maps.MarkerImage(href + '/imagens/mapas/estacionamento.png',
						  // This marker is 20 pixels wide by 32 pixels tall.
						  new google.maps.Size(38, 34),
						  // The origin for this image is 0,0.
						  new google.maps.Point(0,0),
						  // The anchor for this image is the base of the flagpole at 0,32.
						  new google.maps.Point(11, 33));
					  
					  
					  var latlng_e = new google.maps.LatLng($('#' + identificador + '_latitude').val(), $('#' + identificador + '_longitude').val());
						  
					  var marker2 = new google.maps.Marker({
							position: latlng_e,
							map: map,
							icon: icone_e
					  });
						  
					  google.maps.event.addListener(marker2, 'click', function() {
							map.setZoom(16);
							map.setCenter(latlng_e);
					  });
				}
			});
		}
	}
}

function respFormulario(result,status) {
	if(result.alerta)
		alert(result.alerta);
	
	if(result.redirect){
		$(location).attr('href',result.redirect);
	}
	
	if(result.msg){
		if(result.msgPosition){
			messageBox(result.msg,(result.destino?result.destino:'resp_geral'),'h_geral', result.msgPosition);
		}else{
			messageBox(result.msg,(result.destino?result.destino:'resp_geral'),'h_geral', 28);
		}
	}

	// Limpa campos do formulário
	if(result.clear=='all'){
		$('.ajaxForm').resetForm();
		
	}else if(result.clear){
		var fields = result.clear.split(',');
		for(x=0;x<fields.length;x++){
			if(fields[x] == 'all'){
				$('.ajaxForm').resetForm();				
			}else{
				$("#" + fields[x]).val('');	
			}
		}
	}
}

// Exibe uma msg de erro de ajax na topBox
function errorAjax(o,t,e) {	
	messageBox('<div class="msg_box">Houve um erro na comunica&ccedil;&atilde;o! Tente novamente. (' + t + '|' + e + ')</div>');
}

// Funções básicas
function messageBox(m,d,h,a) {	
	var a = a?a:0;
	
	if(!$("#resp_geral").length)
		$("body").append("<div id=\"resp_geral\"></div><div id=\"h_geral\"></div>");

	$("#" + h).show();
	$("#" + h).html(m);
	
	$("#" + d).hide();
	$("#" + d).html('<a href="#' + h + '" class="message_box" id="message_box">.</a>');
	
	$(".message_box").fancybox({
		padding					: 0,
		leftSpace				: a,
		'transitionIn'			: 'fade',
		'transitionOut'			: 'fade',
		background				: '#333',
		overlayShow				: false,
		centerOnScroll          : true,
		enableEscapeButton		: true,
		hideOnContentClick		: false,
		'autoScale'         	: true,
		'autoDimensions'    	: true,
		onComplete				: function(){
									$("#" + h).fadeIn('fast');
								  },
		onCleanup				: function(){
									$("#" + h).fadeOut('fast');
								  }
	});
	
	$("#message_box").trigger('click');
}

function modalBox(m,d,h) {
	if(!$("#resp_geral").length)
		$("body").append("<div id=\"resp_geral\"></div><div id=\"h_geral\"></div>");
	
	$("#" + h).show();
	$("#" + h).html(m);
	
	$("#" + d).hide();
	$("#" + d).html('<a href="#' + h + '" class="message_box" id="message_box">.</a>');
	
	$(".message_box").fancybox({
		padding					: 5,
		'transitionIn'			: 'fade',
		'transitionOut'			: 'fade',
		modal					: true,
		centerOnScroll          : true,
		'autoScale'         	: true,
		'autoDimensions'    	: true,
		onComplete				: function(){
									$("#" + h).fadeIn('fast');
								  },
		onCleanup				: function(){
									$("#" + h).fadeOut('fast');
								  }
	});
	
	$("#message_box").trigger('click');
}

function thousandsSeparator(sValue){
	var sRegExp = new RegExp('(-?[0-9]+)([0-9]{3})');
	
	while(sRegExp.test(sValue)){
		sValue = sValue.replace(sRegExp, '$1.$2');
	}
	return sValue;
}
