var indexContent = '';

var elias = {
    Ajaxify: {
        debugMode: false,
        AutoCloseNonSelectedMenuItems: true,
        PreviousPageURL: '',
        SetupMenuOptions: function() {
 /*           jQuery.each(jQuery.browser, function(i) {
                if ($.browser.msie) {
                    //$("#div ul li").css("display", "inline");
                    elias.Ajaxify.AutoCloseNonSelectedMenuItems = false;
                } else {
                    //$("#div ul li").css("display", "inline-table");
                    $("#navigationDiv a").css({ 'display': 'block' });
                }
            });*/
        },
        MenuItemSelected: function(selectedAnchor) {
            debug("clicked " + $(this).text());

           /* if ($(this).attr('ajaxed') == 'false')
                return true; //get out of here is this link is not ajaxed.
			*/
            //all currently selected items are marked as wasSelected and the new item is marked as selected
            $('#navigationDiv .selected').addClass('wasSelected');
            $(this).parents('li:first').children('ul:first').toggle("fast", elias.Ajaxify.AfterAnimateSelectedMenu); //expand submenu for clicked item
            $('#navigationDiv li a').removeClass('selected');
            $(this).addClass('selected');


            //todo: should i disable ajaxification if the url starts with http? i think yes, since all ajax calls should be within the current domain
            //var p = '../_template/minimal.php?page=' + $(this).attr("page");
			var page= $(this).attr("page");
			var p = '../_system/controller.php?page=' + page;
            //if p is # or some variation of ? then set p to the previous loaded page
            var firstChar = p.charAt(0);
            if (p === '#')
                return false;  //if a pound is used as the href, that means the link is only a placeholder to show submenues.
            else if (firstChar == '#') { //pass this statement to the previous page with no ajax
                document.location = this.PreviousPage + p;
            }
            else if (firstChar == '?') { 
                p = elias.Ajaxify.PreviousPageURL + p;
            } else {
                elias.Ajaxify.PreviousPageURL = p;
            }
            //if the title attribute is set on the hyperlink, use it as the page title, otherwise, use the hyperlink text 
            var pgTitle = $(this).attr("title");
            if (pgTitle == '')
                pgTitle = $(this).html();

            $('#pageTitle').text(pgTitle);

            debug("Navigating to: " + p);
            //msg("PageTitle to: " + pgTitle);
            document.title = pgTitle;
            var destinationId = '#contentDiv';
            var sourceId = '#subContentDiv'; //if the source id exists inside of the page loaded, use it as the content


            $(destinationId).addClass("loading");
			//return false;
            contentLoadInit(page, p, destinationId, sourceId);
            //$(this).fadeOut("fast", fadeSelectedMenuItemBackIn) //where this is the clicked button
            return false;
        },
        AfterAnimateSelectedMenu: function() {
            //get out of here if auto closing is disabled
            if (!elias.Ajaxify.AutoCloseNonSelectedMenuItems)
                return;
            //do not toggle if the current item is a child of the wasDisplayed item
            var selectedParentULCount = $('.selected').parents('ul').size();

            debug('selectedParentULCount: ' + selectedParentULCount);
            if (selectedParentULCount > 1) {
                return;
            }

            //close previously selected menu items which  have class: wasSelected
            $('.wasSelected').parents('li').children('ul').slideUp("slow");
            $('.wasSelected').removeClass('wasSelected');

        }	
    },
	DeferredLoader:{/*This is */
		loadjscssfile:function(filename, filetype){
			if (filetype=="js"){ //if filename is a external JavaScript file
				var fileref=document.createElement('script')
				fileref.setAttribute("type","text/javascript")
				fileref.setAttribute("src", filename)
			}
			else if (filetype=="css"){ //if filename is an external CSS file
				var fileref=document.createElement("link")
				fileref.setAttribute("rel", "stylesheet")
				fileref.setAttribute("type", "text/css")
				fileref.setAttribute("href", filename)
			}
			if (typeof fileref!="undefined") {
			document.getElementsByTagName("head")[0].appendChild(fileref)
			alert('loaded ' + filename);
			}
		}
	}


};




//var cachedContent = {
//    pageName: '',
//    html: '',
//    New: function(p, txt) {
//        this.pageName = p;
//        this.html = txt;
//    }
//};
var cacheArray = new Array();
cacheArray['index.html'] = {page:'index.html', html:'hello world'};

$(document).ready(function() {
    indexContent = '';
    //one says do this event once for each matched element
    $('#navigationDiv a[ajaxify="true"]').click(elias.Ajaxify.MenuItemSelected);

});



function fadeSelectedMenuItemBackIn (){
	$(this).slideDown("fast");
	
}

function contentLoadInit(page, p, destinationId, sourceId) {
//    if (false && cacheArray[p] !== undefined) {
//        msg(p + ' Loaded from cache');
//        $(destinationId).html(cacheArray[p].html);
    //    } else {


    //$(destinationId).html('loading ' + p + '...');
    $(destinationId).fadeOut('fast', function(){
		debug('Adding class to @mainbody: ' + page + ". $('#mainbody').size() = " + $('#mainbody').size());
		$('#mainbody').removeClass().addClass(page);
		$(destinationId).load(p, 'isAjaxRequest=1', contentLoadCallBack);});
    //$(destinationId).load(p, 'isAjaxRequest=1', contentLoadCallBack);

//    }
    
}
function contentLoadCallBack(responseText, textStatus, XMLHttpRequest) {
    var destinationId = "#contentDiv";
    var sourceId = "#subContentDiv";
    $(destinationId).html(responseText);  //set the responsetext into the destionation Div
    
    var txt = $(destinationId + ', ' + sourceId).html();
    try { //If page has a subcontentDiv, use that as the content here
        if (txt !== null) {
            //msg("SubcontentDiv: " + txt);
            debug("SubcontentDiv used as the body of the content section.");
			if (txt!==null)
			    $(destinationId).html(txt);
		}
	} catch(err){
		msg("Error while getting subcontentDiv" + err);
	}
	

	
    //animate the destination div
	 $(destinationId).fadeIn('fast');
	//$(destinationId).fadeIn("slow");
	//add the txt of the page to the cache
	//cacheArray[p] = { page: p, html: txt };
	$(destinationId).removeClass("loading");
}

function debug(str) {
    if (elias.Ajaxify.debugMode !== true) {
        return;
    }
    var targetDiv = "#msgDiv";
    var dateTime = new Date();
    if ('none' == $(targetDiv).css('display')) 
        $(targetDiv).show("fast");
    var time = dateTime.getHours() + ":" + dateTime.getMinutes() + ":" + dateTime.getSeconds();
    $(targetDiv).prepend("\r\n<span style='color:grey'>" + time + ": " + str + "</span><br/>");
}
function msg(str, targetDiv){
	if(targetDiv===undefined)
		targetDiv = "#msgDiv";
	var dateTime = new Date();
	var minutes = dateTime.getMinutes();
	var pad2 = function(str){
			str = str + '';
			return (str.length===1)? '0' + str:str;
		};
	var time = pad2(dateTime.getHours()) + ":" + pad2(dateTime.getMinutes()) + ":" + pad2(dateTime.getSeconds());
	$(targetDiv).prepend("\r\n" + time + ": " + str + "<br/>");

	//show target div if it is hidden
	if ('none' == $(targetDiv).css('display')) 
	$(targetDiv).show("fast");
}

jQuery.fn.Hello = function(url, options) {
    // define defaults and override with options, if available
    // by extending the default settings, we don't modify the argument
    settings = jQuery.extend({
        name: "defaultName",
        size: 5,
        global: true
    }, options);
    //msg("You called Hello method from jQuery... with url parameter: " + url);
    //msg("Settings name, size,global: " + settings.name + "," + settings.size + "," + settings.global);
}
