// Handle hash functions.
var ql;
$(function(){
	$.historyInit(pageLoad);
	
	if(isRealUser()){
		
	}else{
		if(!$.cookie("signin")){
			// If the cookie is not set, show the signin
			signUp('layouts');
			// Then set the cookie so it's not shown again
			$.cookie("signin", "true", { expires: 1, path: '/' });
		}
	}
	
	ql = new QuickLook('ql');
	ql.addNav("Favorites", "toggleFavorites");
	$("#qlnav").click(function(){
		ql.toggleFavorites(1);
	});
	ql.toggleFavorites(1);
	
	historyInit();
});

function historyInit(){
	$("a[rel='history']").unbind('click');
	$("a[rel='history']").click(function(){
		var hash = this.href;
		hash = hash.replace(/^.*#/, '');
		// moves to a new page. 
		// pageload is called at once. 
		$.historyLoad(hash);
		return false;
	});
}

var appRunning = false;

var hashLock = false;

var hashRoot;

// This function is called every time the hash changes.
function pageLoad(hash){
	if(hash){
		hash = hash.split('/');
		
		// We do a number of things based on what the 'root' is (will be edit, new, etc.)
		hashRoot = hash[0];
		// Remove the first entry (the root), so we are left with nice parameters.
		hash = hash.splice(1, 1);
		if(!appRunning){
			loadPage('layoutapp.php', function(){
				historyInit();
				appRunning = true;
				if(hashRoot == 'edit'){
					layout_edit(hash);
				}else if(hashRoot == 'new'){
					layout_new(hash);
				}else if(hashRoot == 'view'){
					layout_view(hash);
				}else if(hashRoot == 'template'){
					layout_template(hash);
				}
			});
		}else{	
			if(hashRoot == 'edit'){
				layout_edit(hash);
			}else if(hashRoot == 'new'){
				layout_new(hash);
			}else if(hashRoot == 'view'){
				layout_view(hash);
			}else if(hashRoot == 'template'){
				layout_template(hash);
			}
		}
		
	}else{
		appRunning = false;
		// Just show the default layouts 'landing page.'
		loadPage('landingpage.php', function(){
			historyInit();
		});
	}
}

// Load a page into the layout container
function loadPage(page, callback){
	$("#layoutContainer").html(''); // Clear the layout container to remove any junk
	$("#layoutContainer").addClass("loading");
	
	$("#layoutContainer").load("/pages/new/layouts/" + page, '', function(){
		$("#layoutContainer").removeClass("loading");
		if(callback){
			callback();
		}
	});
}

/**
 * Deleting a room confirmation
 */
function showConfirm(t, roomid){
	$(t).replaceWith('<span class="confirmation">Are you sure? <a href="/SavedRooms/?delete=' + roomid + '">Yes</a> - <a href="#" onclick="cancelConfirm();return false;">No</a></span>');
}

function cancelConfirm(){
	$(".confirmation").replaceWith('<a class="deletelink" href="#" onclick="showConfirm(this);return false;">delete</a>');
}