function log(wut) {
    if (window.console) {
        console.log(wut);
    }
}
var contentdiv = [];
var projects = [];
var pages = [];
var ajaxEnabled = true;
var uifixes = true;

$(function() {
    log("starting");
    if (ajaxEnabled) ajaxify();
    if (uifixes) uiFixes();
});

function ajaxify() {
    contentdiv = $("#content");
    doWhenStartingLoading();
    getPages();
    getProjects();
    $(window).bind( 'hashchange', function(e) {
        checkAndDoHashAction();
    });
}

function uiFixes() {
    disableDrag();
    externalizeLinks();
}


function disableDrag() { 
    $("img").mousedown(function(event){
     if(event.preventDefault)
      {
        event.preventDefault();
      }
      // Other code...
    });
}

function externalizeLinks() { 
      $('a[href^="http://"]')
      .attr({
        target: "_blank", 
        title: "Opens in a new window"
      });
      $('a[href^="https://"]')
      .attr({
        target: "_blank", 
        title: "Opens in a new window"
      });
}

var cache = [];
function preload(images) {
    $.each(images,function() {
      var cacheImage = document.createElement('img');
      cacheImage.src = this;
      cache.push(cacheImage);
    });
} 

var pagesloading = 1;
var projectsloading = 1;
function doWhenStartingLoading() {
    if ((pagesloading == 1 || projectsloading == 1) && shouldWeShowLoading() == true) {
        log("Starting loading");
        contentdiv.hide();
        $("#activity").show();
    } else {
        $("#activity").hide();
    }
}
function doWhenFinishedLoading() {
    if (pagesloading == 0 && projectsloading == 0) { //done! do the action
        if ($("#activity:visible").length > 0) {
            $("#activity").fadeOut(fadeDur, function()  {
                log("Done loading!")
                $(window).trigger( 'hashchange' );
            });
        } else {
            log("Done loading!")
            $(window).trigger( 'hashchange' );
        }
        scanAndPreload();
    }
}
function scanAndPreload() {
    log("calling fucntion: "+pages.length);
    $.each(pages, function(key,page) {
        log("page!");
        var x = $(page);
        log(x);
    });   
}

function getProjects() {
    $.getJSON("/json/projects/", function(data) {
        $.each(data,function(index, json_item) {
            projects[json_item.name.toLowerCase()] = json_item;
            //log(json_item.title);
        });
        projectsloading = 0;
        doWhenFinishedLoading();
    });
}

function getPages() {
    $.getJSON("/json/pages/", function(data) {
        $.each(data,function(index, json_item) {
            pages[json_item.title.toLowerCase()] = json_item;
            log(json_item.title);
        });
        pagesloading = 0;
        doWhenFinishedLoading();
    });
}

fadeDur = 100;
function loadContent(content) {
    contentdiv.fadeTo(fadeDur,0, function() {
        contentdiv.html(content);       
        contentdiv.fadeTo(fadeDur,1, function() {
            uiFixes();
        });
        hashifyLinks();
    });
}
function loadPage(page) {
    loadContent(page.html);
    highlightMenu(page.title);
}
function loadPageFromName(pagename) {
    loadPage(pages[pagename]);
}
function loadProject(project) {
    loadContent(project.details);
    highlightSubmenu(project.name);
}
function loadProjectFromName(projectname) {
    loadProject(projects[projectname]);
}

function removeMenuHighlight() {
    $(".menuhighlight").removeClass("menuhighlight");
}
function highlightMenu(menuname) {
    removeMenuHighlight();
    log("HIghlighting: "+menuname);
    $(".navbar-"+menuname.toLowerCase()).addClass("menuhighlight");
}
function highlightSubmenu(menuname) {
    removeMenuHighlight();
    $(".subnavbar-"+menuname.toLowerCase()).addClass("menuhighlight");
}

function hashifyLinks() {
    $("a").attr("href", function(i, href) {
        if( window.location.hostname === this.hostname && href.search("/static/") == -1) {
            return insertHash(href);           
        }
    });
}
function insertHash(href) {
    if (href.indexOf("/#/") < 0)
        return href.replace('/', '/#/');
    else
        return href;
}

function shouldWeShowLoading() {
    url = $.param.fragment();
    log("shouldweload: "+url);
    if (url != "") return true;
    else return false;
}

function checkAndDoHashAction() {
    url = $.param.fragment();
    log(url);
    actions = url.split('/');
    log(actions);
    firstaction = "";
    secondaction = "";
    $.each(actions, function() {
        if (firstaction == "") 
            firstaction = this;
        else if (firstaction != "" && secondaction == "") 
            secondaction = this;
    });
    log("First action: "+firstaction);
    log("second action: "+secondaction);

    

    if (secondaction != "") {
        log("Loading project page: "+secondaction);
        loadProjectFromName(secondaction.toLowerCase());
    } else if (firstaction != "") {
        log("Loading page: "+firstaction);
        loadPageFromName(firstaction.toLowerCase());
    } else if (url != "") { 
        loadPageFromName("home"); //oops. load the home page!
    } else {
        //for now, do nothing at all.
    }
    hashifyLinks();
    uiFixes();
}


