/////////////////////////////////////////////////////////////
// Main Javascript for VotaMejor
// (c) Written by Tomas Pollak for Google Inc.
// Nov. 19, 2009
/////////////////////////////////////////////////////////////

var zoomlevel = 16;
var coords = [];
var response = false;

var gmaps_keys = [];
gmaps_keys['votamejor.appspot.com'] = 'ABQIAAAAX5rhm_rRwi1zFjjHYVykUBTpcaFbRtKBucejeg8-uPoFXdNFXBQveWExegJbObQG2sPN8z8rhGoXaw';
gmaps_keys['www.votamejor.appspot.com'] = 'ABQIAAAAX5rhm_rRwi1zFjjHYVykUBTpcaFbRtKBucejeg8-uPoFXdNFXBQveWExegJbObQG2sPN8z8rhGoXaw';
gmaps_keys['www.votamejor.com'] = 'ABQIAAAAX5rhm_rRwi1zFjjHYVykUBTaoJXLj4T_mQE47eLYCI_6NBBPnxRcjFeqw4gMioOWgVNQQ4IC7qCNlw';

$(document).ready(function(){

	Site.init();

});

var Site = {

	init: function(){

		Cufon.replace('h2, #menu li');

		Site.getDate();

		if(location.href.indexOf('#') != -1){
			l = location.href.split('#');
			Site.gotoTab(l[1]);
		}

		$('#menu a').click(function(){
			Site.tabSize(this);
			return false;
		});

		$('#mapsearch').submit(function(){

			if(this.rut.value == '' || !validate_rut(this.rut.value)) {
				alert('Debes ingresar un RUT válido.');
			} else if($('#captcha #code').val() != '') {
				Site.getInfo();
			} else {
				Site.showCaptcha();
			}
			return false;

		});

		$('#captcha form').submit(function(){
			$('#captcha').hide().next('#mapsearch').fadeIn();
			Site.getInfo();
			return false;
		});

		$('#rut').keyup(function(){
			// if(this.value.length >= 6){
				if(this.value.length > 7 && validate_rut(this.value)) $(this).next().addClass('ok').fadeIn('slow').removeClass('error');
				else $(this).next().fadeOut('fast', function(){
					$(this).addClass('error').removeClass('ok');
				});
			// } else {
			//	$(this).next().removeClass();
			// }
		});

		$('#getdirections').submit(function(){
			$(this).addClass('loading');
			// google.load("maps", "2", {"callback" : Site.getDirections});
			Site.getDirections();
			return false;
		}).children('#address').focus(function(){
			$(this).siblings('p').fadeIn();
		}).keyup(function(){
			$(this).siblings('p').fadeOut();
		}).blur(function(){
			$(this).siblings('p').fadeOut();
		});

	},

	getDate: function(){

		var t = new Date();
		var formatted_date = t.getFullYear() + '-' + t.getMonth() + '-' + t.getDate();
		$(formatted_date).addClass('today');

	},

	gotoTab: function(anchor){

			a = $('#menuitem-' + anchor + ' a');
			Site.showDiv('#' + anchor, a);
	},

	tabSize: function(a){

		if($(a).parent().hasClass('selected') || $(a).hasClass('loading')) return;
		target = '#' + a.href.split("#")[1];
		Site.showDiv(target, a);

	},

	showDiv: function(target, a){

		$(target).fadeIn(400).siblings('div').not('.control').hide();
		$(a).removeClass('loading').parent().addClass('selected').siblings().removeClass('selected').parent('.submenu').removeClass('loading');
		Cufon.replace('#menu li');

	},

	getApiKey: function() {
		return gmaps_keys[window.location.hostname];
	},

	disableForm: function(form){
		$(form).addClass('loading').find('input').attr('disabled', true).filter(':submit').val('Buscando...');
	},

	enableForm: function(form){
		$(form).removeClass('loading').find('input').attr('disabled', false).filter(':submit').val('Buscar');;
	},

	showCaptcha: function(){

		$('#mapsearch').fadeOut('fast', function(){
			$('#captcha').show().find('#code').focus();
		});

	},

	getInfo: function(){

		var form = '#mapsearch';
		var rut = $(form + ' #rut').val();
		Site.disableForm(form);
		$('#where #details li').html('');

		$.getJSON("/find/" + rut, {verification : $('#captcha #code').val() }, function(data){
			if(data && data.Nombre){
				response = data;
				$.each(data, function(key,val){
					if (val == '' && key == 'RUN') return true;
					var html = "<strong>" + key + "</strong><br /><span>" + val + '</span>';
					key = key.replace(/ /gi, '-');
					$('li.detail-' + key).removeClass('hidden').html(html);
				});
				$('li.detail-RUN').removeClass('hidden').html("<strong>RUN</strong><br /><span>" + rut + '</span>');
				if (data.place){
					coords['lat'] = data.place.lng; // dont know why they work the other way around
					coords['lng'] = data.place.lat;
					Site.renderPlace(data.place);
				} else {
					response = false;
					alert('No pudimos encontrar un mapa para tu lugar de votación. Sólo verás un plano de referencia.');
				}
				$('#where').show().next().hide();
				Site.showOverlay();

			} else if (data.response == "Invalid verification."){

				Site.showCaptcha();
				alert('Codigo de verificacion inválido.');

			} else {
				// alert('No pudimos encontrar información asociada a ese RUT. \nVerifica que lo hayas escrito bien.');
				alert('Hubo un problema al intentar obtener los datos de Servel. Por favor inténtalo en unos minutos.');
			}

			Site.enableForm(form);

		});

		return false;

	},

	renderPlace: function(data){
			$('#staticmap').attr('src', Site.getStaticMap());
			$('#overlay-content #place-name').html(data.name + ' en ' + data.address);
			Cufon.replace('#overlay-content h2');
			$('#getdirections').fadeTo(4000, 1).fadeIn('slow');
			// $('#getdirections').show('slow');
	},

	getDirections: function(){

		initialize();
		$('#directions').html('');
		var from_address = $('#getdirections #address').val() + ', Chile';
		var to_address = response.address + ", " + response.locality + ", Chile";
		var method =  $('#getdirections #method').val();
		setDirections(from_address, to_address, method);

	},

	getStaticMap: function(){
		c = coords['lat'] + ',' + coords['lng'];
		return 'http://maps.google.com/staticmap?center='+c+'&zoom='+zoomlevel+'&size=400x400&maptype=mobile&markers='+c+',greenb&key='+Site.getApiKey()+'&sensor=true';
	},

	showOverlay: function(){

		var closeable = arguments[0] || true;

		// the opacity thingy doesn't work well on firefox and camino on mac, so we have to use a PNG background
		var ua = navigator.userAgent.toLowerCase();
		if (ua.indexOf('mac') != -1 && (ua.indexOf('firefox')!=-1 || ua.indexOf('camino')!=-1)) {
			$('#overlay').removeClass('opacity').addClass('macffhack');
		}

		$('#overlay').show().next().show();

		if(closeable){
			// close it on click outside the box content
			// $('#overlay').click(function(){ Site.hideOverlay(); });
			// close it on ESC keypress if the overlay is visible
			$(document).keyup(function(e) {
				var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
				if (key == 27 && $('#overlay').is(':visible')) {
					Site.hideOverlay();
				}
			});
		}
		return false;
	},

	hideOverlay: function(){
		$('#overlay').hide().next().hide();
	}

}

