$(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+"/") {
				url = t.attr('href').replace(/\?/, '$').replace(RegExp("^http://"+location.hostname+"/"), '/');
				if ($.browser.msie)
					$('#iframe_history').attr('src', "/iframe-history?url=" + encodeURIComponent(url));
				else
					location.href="/#"+url;
				event.preventDefault();
			}
		}
		return true;
	});
	/*
	$(parent).find("a").not("[target]").add("a[target='_self']").not("a[href^='http://']").add("a[href='^http://cuidados.teste.vermais.com']").each(function() {
	//$(parent).find("a").not("[target]").add("a[target='_self']").each(function() {
		/*$(this).unbind('click.ajaxFrame');
		$(this).bind('click.ajaxFrame', function() {
			ajaxLink($(this).attr('href'));
			return false;
		});* /
		$(this).css({'background': 'red'});
		if ($(this).attr("href").substr(0, 3) != '/#/')
			$(this).attr("href", '/#'+$(this).attr("href").replace(/\?/, '$'));
		$(this).unbind('click.ajaxFrame');
		$(this).bind('click.ajaxFrame', function() {
			location.href = $(this).attr('href');
			return false;
		});
	});*/
}
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 successCallback(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;
	pageTracker._trackPageview(getHash().substr(1));  // Google Analytics
	$('#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);
}

loadingTimer = null;
xhr = null;
otherTimeouts = {};
function ajaxLink(url) {
	$.scrollTo("#center_canvas");
	$.each(otherTimeouts, function(k, v) {
		clearTimeout(v);	
	});
	otherTimeouts = {};
	loadingTimer = setTimeout("$('#subpage').html(\"<img src='http://www.vermais.com/images/loading.gif' alt='' /> Carregando...\");", 500);
	if (xhr) xhr.abort();
	xhr = $.ajax({
		dataType: 'html',
		complete: successCallback,
		url: url
	});
}

function ajaxPost(form) {
	$.scrollTo("#center_canvas");
	$.each(otherTimeouts, function(k, v) {
		clearTimeout(v);	
	});
	otherTimeouts = {};
	loadingTimer = setTimeout("$('#subpage').html(\"<img src='http://www.vermais.com/images/loading.gif' alt='' /> Carregando...\");", 500);
	if (xhr) xhr.abort();
	xhr = $.ajax({
		dataType: 'html',
		complete: successCallback,
		data: $(form).serializeArray(),
		type: $(form).attr("method"),
		url: $(form).attr("action")
	});
}
