$(function() {
	if ($.browser.msie)
		$('body').append("<iframe id='iframe_history' src='/iframe-history' style='position: absolute; top: -10000px;'></iframe>");
	bindLinks(document);
	bindForms(document);
	if (location.pathname != '/') {
		$('#subpage').html('');
		var s = location.pathname;
		if (location.search)
			s += location.search;
		s += (s.indexOf('?') == -1 ? '?' : '&')
		d = new Date();
		s += "c="+d.getTime();
		setHash(s);
	} else {
		if (!getHash()) {
			$('#subpage').html('');
			setHash("/home");
		}
		setTimeout("checkHash()", 100);
	}
});

// carrega a página do hash
prevHash = null;
noRedir = false;
function checkHash() {
	if (getHash() && getHash().substr(0, 2) == '#/' && getHash().substr(1) != prevHash && !noRedir) {
		ajaxLink(getHash().substr(1));
		prevHash = getHash().substr(1);
	}
	setTimeout("checkHash()", 250);
}

function setHash(url) {
	url = url.replace(/\?/g, '$').replace(RegExp("^http://"+location.hostname+"/"), '/');
	if ($.browser.msie) {
		$('#iframe_history').attr('src', "/iframe-history?url=" + encodeURIComponent(url));
		$('#iframe_history').bind('load.ajaxFrame', function() {noRedir = false});
	} else {
		location.href = "/#"+url;
		noRedir = false;
	}
}

function bindLinks(parent) {
	$(document).delegate("a", "click", function(event) {
		var t = $(this);
		if (!t.attr('target') || t.attr('target') == "_self") {
			if (t.attr('href') && (t.attr('href').substr(0,1) == '/' || t.attr('href').substr(0, location.hostname.length + 8) == "http://"+location.hostname+"/")) {
				if (t.attr('href').substr(0,3) == '/#/')
					url = t.attr('href').substr(2);
				else
					url = t.attr('href');
				setHash(url);
				event.preventDefault();
			}
		}
		return true;
	});
}

function bindForms(parent) {
	$(parent).find("form").not("[target]").add("form[target='_self']").not("form[rel='noajax']").each(function() {
		if($(this).attr("action").substr(0,7) != "http://") {
			$(this).unbind('submit.ajaxFrame');
			$(this).bind('submit.ajaxFrame', function() {
				ajaxPost(this);
				return false;
			});
		}
	});
}

function getHash() {
	var hsh = location.hash;
	if (!hsh) return null;
	if (hsh == '') return null;
	if (hsh.substr(0, 1) != '#')
		hsh = '#' + hsh
	return hsh.replace(/\$/gi, "?");
}

function errorCallback(xhr, status, error) {
	clearTimeout(loadingTimer);
	$(subpage).html("<h1>Erro ao carregar a página.</h1><p>Por favor, tente novamente.</p>")
}

function ajaxLink(url) {
	return ajaxRequest(url, null, "GET"); 
}

function ajaxPost(form) {
	f = $(form);
	return ajaxRequest(f.attr("action"), f.serializeArray(), f.attr("method")); 
}

lastData = null;
lastMethod = null;
lastURL = null;
loadingTimer = null;
xhr = null;
otherTimeouts = {};
lastLink = null;
function ajaxRequest(url, data, method) {
	$.scrollTo(0,0);
	$.each(otherTimeouts, function(k, v) {
		clearTimeout(v);	
	});
	otherTimeouts = {};
	$('#subpage').attr('class', '').html("<img src='http://www.vermais.com.br/images/loading.gif' alt='' /> Carregando...");
	if (xhr) xhr.abort();
	$("#subpage").trigger("startedLoading");
	xhr = $.ajax({
		dataType: 'html',
		complete: function (xhr, status) {
			data = xhr.responseText;
			if (xhr.status != 200 && !(xhr.getResponseHeader("Content-Type").match(/html/) && data.match(/<title>(.*)<\/title>/i)))
				data = "<title>Erro ("+xhr.status+")</title><pre>"+data.replace(/&/g, "&amp;").replace(/</g, "&lt;")+"</pre>";
			var tt = data.match(/<title>(.*)<\/title>/i);
			document.title = tt?tt[1]:null;
			data = data.replace(/<title>.*?<\/title>/i, '');
			hh = data.match(/<hash>(.*?)<\/hash>/i);
			if (hh) {
				hh = hh[1];
				prevHash = hh;
				noRedir = true;
				setHash(hh);
			} else {
				hh = getHash().substr(1);
			}
			data = data.replace(/<hash>.*?<\/hash>/i, '');
			$('#subpage').html(data).attr("class", "").addClass("subpage_page_"+hh.substr(1).replace(/\//g, '_').replace(/(\?.*)?$/g, ''));
			bindLinks(document);
			bindForms(document);
			$("#subpage").trigger("finishedLoading");
		},
		data: data,
		type: method,
		url: url
	});
	lastURL = url;
	lastData = data;
	lastMethod = method;
}


function ajaxReload() {
	if(lastURL)
		ajaxRequest(lastURL, lastData, lastMethod);	
}

