var root_url = 'studyodream.com/';
var mainDiv = '#pagecontent';

function urlCleanUp(x,h){
	
	if (h == "")
		h = 0;
	
	x = x.toLowerCase();
	x = x.replace(".php?","");
	x = x.replace(".php","");
	x = x.replace("action=","");
	x = x.replace("index","anasayfa");	

	do{
		x = x.replace('&','/'); // clean all '&' and turn them into evil d'/'b slashes!
	}while (x.indexOf("&") > 0);
	
	if (x.indexOf("#") != -1)
		if (x.substr(x.indexOf("#")+1,1) != "/")
			x = x.replace("#","#/");
	
	x = x.replace(root_url,root_url+"#/");

	if (x.substr((x.length)-1,1) != "/")
		x = x + "/";

	return x;
}

function hashLink(page){
	var hash = window.location.hash;
	var hash2 = hash.substring(hash.indexOf("/"),hash.indexOf("/",hash.indexOf("/")+1));
	hash2 = hash2 + "/" + page + "/";
	if (window.location.hash == '#' + hash2)
		window.location.reload();
	else
		window.location.hash = urlCleanUp(hash2);
}



$(function () {

	if(document.location.href.indexOf("#") == -1){
		cleanURL = urlCleanUp(document.location.href);
		document.location.href = cleanURL;
	}else{
		
	}
	
	$("a:not(.ui-spinner-button, .file-link, .image-link, .cke_top *, .cke_dialog_body *, .cke_bottom *, textarea + span *, .ui-datepicker-calender tr td *)").live('click', function() {
		var url = $(this).attr("href");
		window.location.hash = urlCleanUp(url);
		
		return false;
	});
	
	var ultimate_url  = document.location.href;
	var sharp = ultimate_url.indexOf("#");
	var ultimate_hash = '';
	if (sharp > 0)
		ultimate_hash = ultimate_url.substring(ultimate_url.indexOf("#"));


		
    setInterval(function (){
		if(document.location.href  != ultimate_url || ultimate_hash != '' ) {
			url = window.location.hash;
			var slices = url.split("/");
			var rndm = Math.random; // to prevent read from old cached page
			var datastring = '';
			if (slices.length > 3){
				for (i=2; i<slices.length; i++)
					if (slices[i] != '' )
						datastring = '&' + datastring + slices[i] + '&'; // $.ajax ile gönderebileceğimiz bir forma sokuyoruz değişkenlerimizi
			}
			//alert(slices[0]+slices[1]+slices[2]+slices[3]+slices[4]);
			var datas = {page:slices[1], ajax:1, random:rndm };
			datas = $.param(datas);
			datas = datastring + datas;
			//alert(datas);
			if (slices[1] == '')
				slices[1] = 'anasayfa';
				
			if (slices[1] != undefined && slices[1] != "")
				$.ajax({
					type: "POST",
					cache: false,
					url: slices[1]+".php",
					dataType : "text",
					data: datas,
					success: function (txt) { 
						$(mainDiv).fadeTo(0,0.01);
						$(mainDiv).html(txt);
						$(mainDiv).fadeTo(650,1);
					}
				});
			ultimate_url = document.location.href;
			ultimate_hash = '';
		}	
	}, 10);
});
