$(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.replace(/\?/, '$');
		location.href = s;
	} else {
		if (!getHash()) {
			$('#subpage').html('');
			location.hash = "#/home";
		}
		setTimeout("checkHash()", 100);
	}
});

// carrega a página do hash
prevHash = null;
function checkHash() {
	if (getHash() && getHash().substr(0, 2) == '#/' && getHash().substr(1) != prevHash) {
		ajaxLink(getHash().substr(1));
		prevHash = getHash().substr(1);
	}
	setTimeout("checkHash()", 250);
}

function bindLinks(parent) {
	$(document).delegate("a", "click", function(event) {
		t = $(this);
		if (!t.attr('target') || t.attr('target') == "_self") {
			if(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').replace(/\?/, '$').replace(RegExp("^http://"+location.hostname+"/"), '/');
				if ($.browser.msie) {
					$('#iframe_history').attr('src', "/iframe-history?url=" + encodeURIComponent(url));
					event.preventDefault();
				} else {
					t.attr("href", "/#"+url);
				}
			}
		}
		return true;
	});
}
function bindForms(parent) {
	$(parent).find("form").not("[target]").add("form[target='_self']").not("form[action^='http://']").each(function() {
		$(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("#subpage");
	$.each(otherTimeouts, function(k, v) {
		clearTimeout(v);	
	});
	otherTimeouts = {};
	loadingTimer = setTimeout("$('#subpage').attr('class', '').html(\"<img src='http://www.vermais.com.br/images/loading.gif' alt='' /> Carregando...\");", 500);
	if (xhr) xhr.abort();
	xhr = $.ajax({
		dataType: 'html',
		complete: function (xhr, status) {
			clearTimeout(loadingTimer);
			data = xhr.responseText;
			if (xhr.status != 200)
				data = "<title>Erro ("+xhr.status+")</title><pre>"+data.replace(/</, '&lt;')+"</pre>";
			var tt = data.match(/<title>(.*)<\/title>/i);
			document.title = tt?tt[1]:null;
			$('#subpage').attr("class", "").addClass("subpage_page_"+getHash().substr(2).replace(/\//g, '_').replace(/(\?.*)?$/g, ''));
			data = data.replace(/<title>.*?<\/title>/i, '');
			data = data.replace(/<hash>.*?<\/hash>/i, '');
			$('#subpage').html(data);
			bindLinks(document);
			bindForms(document);
		},
		data: data,
		type: method,
		url: url
	});
	lastURL = url;
	lastData = data;
	lastMethod = method;
}


function ajaxReload() {
	if(lastURL)
		ajaxRequest(lastURL, lastData, lastMethod);	
}
