//Declaring Dependencies
dojo.require("dojo.back");

//Main Application
function main()
{
    var self = this;
    this.domainName = "mohamedattar.com";
    this.contentNode = null; //set on init
    this.pages =
    {
	about: { url: "pages/about.html", data: null },
	resume: { url: "pages/resume.html", data: null },
	portfolio: { url: "pages/portfolio.html", data: null },
	contact: { url: "pages/contact.html", data: null },
	blog: { url: "pages/blog.html", data: null }
    };
    
    this.historyState =
    {
	back: function() { self.backPage(); },
	forward: function() { self.forwardPage(); },
	changeUrl: self.initPage
    };
    
    dojo.back.init();
    dojo.back.setInitialState(self.historyState);
    

    this.init = function()
    {
	self.contentNode = dojo.byId("content");
	var initHash = self.getCurrentHash();
	var initPage = (initHash.length>0?initHash:"about");
        self.loadPage(initPage);
    };
    
    this.getCurrentHash = function()
    {
	return (location.hash).replace(/#/,"");
    }

    this.backPage = function()
    {
	var page = self.getCurrentHash();
	if(page)
	    self.loadPage(page);
	else self.loadPage("about");
    }
    
    this.forwardPage = function(page)
    {
    	var page = self.getCurrentHash();
	if(page)
	    self.loadPage(page);
	else self.loadPage("about");
    }
    
    this.gotoPage = function(page)
    {
	self.historyState.changeUrl = page;
	dojo.back.addToHistory(self.historyState);
	self.loadPage(page);
    }
    
    this.loadPage = function(page)
    {
	
	if(self.pages[page].data != null)
	{
	    self.onPageLoad(self.pages[page].data, null);
	}
	else
	{
	    dojo.xhrGet({
		url: self.pages[page].url,
		handleAs: "text",
		load: self.onPageLoad,
		error: self.onPageError,
		page: page
	    });
	}
    };
    
    this.onPageLoad = function(data, args)
    {
	dojo.fadeOut(
	{
	    node: self.contentNode,
	    onEnd: function()
	    {
		if(args != null)
		    self.pages[args.args.page].data = data;
		self.contentNode.innerHTML = data;
		dojo.fadeIn({ node: self.contentNode }).play();
	    }
	}).play();
    }
    
    this.onPageError = function(data, args)
    {
	while(self.contentNode.childNodes.length > 0)
	    self.contentNode.removeChild(self.contentNode.childNodes[0]);
	var errorMsg = document.createElement("div");
	errorMsg.className = "pageError";
	errorMsg.innerHTML = "Error Loading Page";
	self.contentNode.appendChild(errorMsg);
    }

    this.toggleWatermark = function(object, value)
    {
	if(value != null && value.length > 0)
	{
	    if(object.value == "")
	    {
		object.className = "watermark";
		object.value = value;
	    }
	}
	else
	{
	    if(object.className == "watermark")
	    {
		object.value = "";
		object.className = "";
	    }
	}
    }
    
    dojo.addOnLoad(self.init);
};
