$(document).ready(function() {
	
	// Esconde a janela de login
	$("#divLogin").hide();
	$("#divBlock").hide();
	
	// Ajusta os botões
	$(function(){
		//all hover and click logic for buttons
		$(".fg-button:not(.ui-state-disabled)")
		.hover(
			function(){ 
				$(this).addClass("ui-state-hover"); 
			},
			function(){ 
				$(this).removeClass("ui-state-hover"); 
			}
		)
		.mousedown(function(){
				$(this).parents('.fg-buttonset-single:first').find(".fg-button.ui-state-active").removeClass("ui-state-active");
				if( $(this).is('.ui-state-active.fg-button-toggleable, .fg-buttonset-multi .ui-state-active') ){ $(this).removeClass("ui-state-active"); }
				else { $(this).addClass("ui-state-active"); }	
		})
		.mouseup(function(){
			if(! $(this).is('.fg-button-toggleable, .fg-buttonset-single .fg-button,  .fg-buttonset-multi .fg-button') ){
				$(this).removeClass("ui-state-active");
			}
		});
	});

	// Recupera os containers
	var mainContent = $('#mainContent');
	var mainMap = $('#mainMap');

	// Variavel contendo os marcadores
	var markers = [];

	// Ajusta o tamanho do conteudo
	mainContent.css("height", ($(window).height() - 25)  + 'px');
	
	// Ajusta o tamanho do mapa				
	mainMap.css("width", ($(window).width() - 200)  + 'px');
	
	$(window).resize(function() {
		// Ajusta o tamanho do conteudo
		mainContent.css("height", ($(window).height() - 25)  + 'px');
		
		// Ajusta o tamanho do mapa				
		mainMap.css("width", ($(window).width() - 200)  + 'px');
    });

	// Posiciona o mapa no centro de andradina
	var map = new GMap2(document.getElementById('mainMap'));
	var llAndradina = new GLatLng(-20.897436,-51.376684);
	map.setCenter(llAndradina, 15);

	// Adiciona a caixa de descrição ao mapa
	$("#message").appendTo(map.getPane(G_MAP_FLOAT_SHADOW_PANE));
	function displayPoint(marker, i){
		$("#message").hide();
		$("#message").html(markers[i][1]).fadeIn();
		map.panTo(marker.getPoint());
		var markerOffset = map.fromLatLngToDivPixel(marker.getPoint());
		$("#message").show().css({ top:markerOffset.y, left:markerOffset.x });
	}
	  
	$('#txtSearch').bind('keypress', function(e) {
		code = e.keyCode ? e.keyCode : e.which;

        if(code == 13) 
        {
        	$('#buttonSearch').click();
        }
	});
	
	// Cria a função do submit
	$('#buttonSearch').click(function() {
		
		// Mostra e esconde os containers para efeito loading 
		$('#frmSearch').hide();
		$('#mainLoading').show();
		$("#message").hide();
		
		// Busca o JSON dos adsenses
		var dataValue = $("#txtSearch").val();
		var dataString = 'q=' + dataValue;
		$.ajax({
			type: "POST",
			url: "index.php?action=search",
			data: dataString,
			dataType: 'json',	
			error: function(xhr, ajaxOptions, thrownError)
			{
	            alert(thrownError);
	            
	            // Mostra e esconde os containers para efeito loading
				$('#mainLoading').hide(); 
				$('#frmSearch').show();
			},
			success: function(data) {
				try
				{
					// Remove os adsenses atuais
					$('#listAdsenses').html('');
	
					// Percorre os adsenses do JSON
					$.each(data.adsense, function(i, item){
						$('#listAdsenses').append('<li>' + item.description + '</li>');
					});

					// Remove os marcadores atuais
					$(markers).each(function(i, marker){
						map.removeOverlay(marker[0]);
					});
					markers = null;
					markers = [];
					
					if(data.markers.length <= 0)
					{
						alert("Sem resultado para: " + dataValue);
					}
						
					// Percorre os pontos
					$.each(data.markers, function(i, item){
						var point = new GLatLng(item.lt, item.lg);
						marker = new GMarker(point);
						map.addOverlay(marker);
						markers[i] = new Array(marker, item.description);
					});

					// Adiciona o evento click nos marcadores
					$(markers).each(function(i, marker){
						GEvent.addListener(marker[0], "click", function(){
							displayPoint(marker[0], i);
							map.panTo(marker[0].getLatLng());
						});
					});
				

					data = null;
				}
				catch(err)
				{
					alert("Sem resultado para: " + dataValue);
				}
				
				// Mostra e esconde os containers para efeito loading
				$('#mainLoading').hide(); 
				$('#frmSearch').show();
			}
		});
		
        return false;
    }); 
    
	// Coloca o foco no search
	$("#txtSearch").focus();
	
	// Link inicio 
	$('#lnkHome').click(function() {
		window.location = 'index.php?action=main';
	});
	
	// Link logout 
	$('#lnkLogout').click(function() {
		window.location = 'index.php?action=logout';
	});
	
	// Dialog do login
	$('#lnkLogin').click(function() { 
		
		$("#divBlock").css({
			width: $(window).width(),
			height: $(window).height()
		}).show();
		
		$("#divLogin").css({
			left: ($(window).width() / 2) - ($("#divLogin").width() / 2),
			top: ($(window).height() / 2) - ($("#divLogin").height() / 2),
			'z-index':'110'
		}).fadeIn("fast").show();
    });
	$('#frmLoginCancel').click(function() {
		$("#divLogin").fadeOut("fast").hide();
		$("#divBlock").hide();
	});
	
	
	// Dialog do registro
	$('#lnkRegister').click(function() { 
		
		$("#divBlock").css({
			width: $(window).width(),
			height: $(window).height()
		}).show();
		
		$("#divRegister").css({
			left: ($(window).width() / 2) - ($("#divRegister").width() / 2),
			top: ($(window).height() / 2) - ($("#divRegister").height() / 2),
			'z-index':'110'
		}).fadeIn("fast").show();
    });
	$('#frmRegisterCancel').click(function() {
		$("#divRegister").fadeOut("fast").hide();
		$("#divBlock").hide();
	});
	
});
