$(document).ready(function() {
	resizeMapa();
	
	$('.bottom a.ajax').click(function() {
		detalle(this.href);
		return false;
	})
})

$(window).bind('resize', function() {
	resizeMapa();
})

function isIphone() {
	var isiPad = navigator.userAgent.match(/iPad/i) != null;
	var isiPod = navigator.userAgent.match(/iPod/i) != null;
	var isiPhone = navigator.userAgent.match(/iPhone/i) != null;
	
	return (isiPad || isiPod || isiPhone);
}

function setupIpod() {

	if(isIphone() && $('#scroller').size() > 0) {
		$('#scroller').css('height', $('#scroller').parent().height());
		new iScroll('scroller', { hScrollbar: false });
	}
}

function resizeMapa() {

	var width = $(window).width();
	width -= ($('#busqueda').outerWidth() + 60);
	
	var height = $(window).height() - $('h1').outerHeight() - 80;
	
	$('#mapa, #detalle').css({
		width: width,
		height: height
	})
	
	$('#mapaContent').css({
		height: height - 31
	})
	
	$('#resultados').css({
		height: (height - $('#busTop').outerHeight() - 30)
	})
	
	resizeDetalle()
}

function activateList() {
	
	$('.resultado').each(function(k, el) {
	
		var index = el.className.substr(el.className.indexOf(' n')+2)
		var overlay = overlays[index];
		
		$(el).click(function() {
			hideOverlays()
			overlay.show();
		})
	
	})
	
}

function detalle(url) {
	
	$('#detalle').load(url, function() {
		$('#detalle .content').get(0).scrollTop = 0
		$('#mapa').hide()
		$('#detalle').fadeIn();
		resizeDetalle();
		
		$('#detalle .close').click(function() {
			$('#detalle').hide();
			$('#mapa').fadeIn()
		})
		ajaxForm($('#consulta'));
	
		if(isIphone() && $('#scroller2').size() > 0) {
			$('#scroller2').css('height', $('#scroller2').parent().height());
			new iScroll('scroller2', { hScrollbar: false });
		}
		
	});
		
}

function resizeDetalle() {
	$('#detalle .content').css({
		height: $('#detalle').outerHeight() - 40,
		width: $('#detalle').outerWidth()
	});
	
	//$('#detalle .description').css('width', $('#detalle').width() - 310)
	
	$('#detalle .images .image').css('width', $('#detalle').outerWidth() - 20)

}

function ajaxForm(form) {

	form.bind('submit', function() {
		
		var fields = $(this).serialize();
		$.ajax('ajax/form.php', {
			data: fields,
			type: 'POST',
			success: function(data) {
				if(data != 'ok')
					alert(data)
				else {
					$('#consulta').html('<h2>Consulta</h2><p>Su consulta fue enviada.</p>')
				}
			}
		})
		
		return false;
		
	})
	
}
