/**
 * Author: Yong-Sheng Lin
 */
// normal font size
var normalFontSize = "100%";

// large font size
var largeFontSize = "105%";

// largest font size
var largestFontSize = "115%";

// default font size
var fontSize = normalFontSize;

// tab container height
var tabContainerHeight = 1050;

// for mobile device detection
var userAgent = navigator.userAgent.toLowerCase();
var mobileDevice = new Array();
mobileDevice[0] = "android";
mobileDevice[1] = "webos";
mobileDevice[2] = "ipod";
mobileDevice[3] = "iphone";

// config file location
var slideConfigLoc = "config/slides.txt";
var logoConfigLoc = "config/logo.txt";
var missionConfigLoc = "config/mission.txt";
var leftmenuConfigLoc = "config/leftmenu.txt";
var socialntwrkConfigLoc = "config/socialnetworks.txt";
var donateConfigLoc = "config/donate.txt";
var defTabConfigLoc = "config/defaulttabs.txt";
var hitCounterConfigLoc = "config/hitcounter.txt";

// max interval for style inject
var maxInterval = 10;

// tabs global initial values
var tabcounter = 0; // initial number of tabs
var tabURL = "";

// common css location
var cssLoc = "../css/common.css";

// last modified date
var modifiedDate = Date.parse(document.lastModified);

$(document).ready(function(){

    initSpecialHoverEvent(7, 200); // special event for menu items
    initSlideShowControl(); // initialize slide show control
    initLogo(); // initialize logo and logo text
    initMission(); // initialize mission statement
    initDefaultTabs(); // initialize default tabs
    initClosableTabs(); // allow tabs to be closed
    initLeftMenu(); // initialize left menu
    initSocialNetworks(); // initialize social networks
    initDonate(); // initialize donate link
    initHitCounter(); // initialize hit counter
    /**
     * font sizer
     */
    $(".fontSizeButton").click(function(){
        var id = $(this).attr("id");
        if (id == "fontSizeNormal") {
            fontSize = normalFontSize;
            setFont(false);
        }
        
        if (id == "fontSizeLarge") {
            fontSize = largeFontSize;
            setFont(false);
        }
        
        if (id == "fontSizeLargest") {
            fontSize = largestFontSize;
            setFont(false);
        }
    });
    
    var indexModifiedDate = new Date(modifiedDate);
    $("#lastModifiedLoc").text(indexModifiedDate.toString());
    $("#lastModifiedLoc").prepend("Last Modified <br/>");
    
    /**
     * smartphone detection
     */
    var detected = false;
    var device = "";
    for (i = 0; i < mobileDevice.length; i++) {
        if (userAgent.search(mobileDevice[i]) > -1) {
            detected = true;
            device = mobileDevice[i];
            break;
        }
    }
    
    if (detected) {
        fontSize = largeFontSize;
        setFont(true); // initialize font size
        $("#leftmenuloc").hide();
        $("<div>Are you using a mobile device?</div>").dialog({
            modal: true,
            title: "Mobile Device Detected: " + device,
            buttons: {
                "Yes": function(){
                    $(this).dialog("close");
                },
                "No": function(){
                    fontSize = normalFontSize;
                    setFont(true); // initialize font size
                    $("#leftmenuloc").show();
                    $(this).dialog("close");
                }
            }
        });
    }
    
    setFont(true); // initialize font size
    checkModifiedDate(); // check last modify date of the pages currently displaying
    $(window).resize(function(){ // change height of tab container when window is resized
        $("#tabs").height(tabContainerHeight + $("#tabs").find("ul").first().height());
    });
});

/**
 * function to set font size and family
 * @param {Object} isInitial if this is the 1st call to this function then isInitial is true
 */
function setFont(isInitial){

    tabContainerHeight = tabContainerHeight * fontSize; // adjust tab container height with font size
    $("body").css("font-size", fontSize);
    
    if (isInitial) {
        var numOfLoadedFrame = 0;
        var numOfReadyFrame = 0;
        
        for (i = 0; i < frames.length; i++) {
            $(frames[i]).load(function(){
                numOfLoadedFrame++;
                if (numOfLoadedFrame == frames.length) {
                    for (j = 0; j < frames.length; j++) {
                        $("body", frames[j].document).css("font-size", fontSize);
                    }
                }
            });
            
            $(frames[i].document).ready(function(){
                numOfReadyFrame++;
                if (numOfReadyFrame == frames.length) {
                    for (j = 0; j < frames.length; j++) {
                        $("body", frames[j].document).css("font-size", fontSize);
                    }
                }
            });
        }
    }
    else {
        for (i = 0; i < frames.length; i++) {
            $("body", frames[i].document).css("font-size", fontSize);
        }
    }
    
    // font sizer button's font size
    $("#fontSizeNormal").css("font-size", "13px");
    $("#fontSizeLarge").css("font-size", "16px");
    $("#fontSizeLargest").css("font-size", "19px");
}

function checkModifiedDate(){
    var numOfLoadedFrame = 0;
    var numOfReadyFrame = 0;
    
    for (i = 0; i < frames.length; i++) {
        $(frames[i]).load(function(){
            numOfLoadedFrame++;
            if (numOfLoadedFrame == frames.length) {
                var numOfFramesProcessed = 0;
                var delayId = setInterval(function delayFn(){
                    var frameDate = Date.parse(frames[numOfFramesProcessed].document.lastModified);
                    if (frameDate > modifiedDate) {
                        modifiedDate = frameDate;
                        var newestModifiedDate = new Date(frameDate);
                        $("#lastModifiedLoc").text(newestModifiedDate.toString());
                        $("#lastModifiedLoc").prepend("Last Modified <br/>");
                    }
                    numOfFramesProcessed++;
                    if (numOfFramesProcessed >= frames.length) {
                        clearInterval(delayId);
                    }
                }, 500);
            }
        });
        
        $(frames[i].document).ready(function(){
            numOfReadyFrame++;
            if (numOfReadyFrame == frames.length) {
                var numOfFramesProcessed = 0;
                var delayId = setInterval(function delayFn(){
                    var frameDate = Date.parse(frames[numOfFramesProcessed].document.lastModified);
                    if (frameDate > modifiedDate) {
                        modifiedDate = frameDate;
                        var newestModifiedDate = new Date(frameDate);
                        $("#lastModifiedLoc").text(newestModifiedDate.toString());
                        $("#lastModifiedLoc").prepend("Last Modified <br/>");
                    }
                    numOfFramesProcessed++;
                    if (numOfFramesProcessed >= frames.length) {
                        clearInterval(delayId);
                    }
                }, 500);
            }
        });
    }
}

function initLogo(){
    $.get(logoConfigLoc, function(data){
        var configArray = data.split(";");
        $("#logo").append("<img src='image/" + configArray[0] + "' align='" + configArray[1] + "'/>");
        $("#logo").append(configArray[2]);
    });
}

function initMission(){
    $.get(missionConfigLoc, function(data){
        $("#mission").append(data);
    });
}

function initLeftMenu(){

    $.get(leftmenuConfigLoc, function(data){
        var configArray = data.split("\r\n");
        for (i = 0; i < configArray.length; i++) {
            if (configArray[i].charAt(0) != '-') {
                $("#leftmenu").append("<h4><a href='#'>" + configArray[i] + "</a></h4><div></div>");
            }
            else {
                $("div", "#leftmenu").last().append("<h5 class='menuitem'>" + configArray[i].replace("-", "") + "</h5>");
            }
        }
        
        $("#leftmenu").accordion({
            collapsible: true,
            event: "click hoverintent",
            autoHeight: false
        });
        
        $("#leftmenu").accordion("activate", false);
        
        $(".menuitem").mouseover(function(){
            $(this).css("text-decoration", "underline");
            $(this).css("color", "blue");
        });
        
        $(".menuitem").mouseout(function(){
            $(this).css("text-decoration", "none");
            $(this).css("color", "black");
        });
        
        $(".menuitem").click(function(){
            var eleFound = findTab($(this).text());
            if (eleFound != null) {
                $("#tabs").tabs("select", $(eleFound).parent().index());
            }
            else {
                var itemText = $(this).text();
                tabURL = itemText.toLowerCase();
                tabURL = tabURL.replace(new RegExp(" ", 'g'), "_");
                tabcounter++;
                $("#tabs").tabs("add", "#tabs-" + tabcounter, $(this).text());
                
                /**
                 * for IE and FireFox to function, .load and .ready have to use
                 */
                var frameEle = document.getElementsByName("tabframe-" + tabcounter);
                var frameIndex = 0;
                
                for (i = 0; i < frames.length; i++) {
                    if (frames[i].name == $(frameEle).attr("name")) {
                        frameIndex = i;
                    }
                }
                
                $(frames[frameIndex]).load(function(){
                    $("body", frames[frameIndex].document).css("font-size", fontSize);
                    $("#tabs").tabs("select", $("#tabs").tabs("length") - 1);
                    var frameDate = Date.parse(frames[frameIndex].document.lastModified);
                    if (frameDate > modifiedDate) {
                        modifiedDate = frameDate;
                        var newestModifiedDate = new Date(frameDate);
                        $("#lastModifiedLoc").text(newestModifiedDate.toString());
                        $("#lastModifiedLoc").prepend("Last Modified <br/>");
                    }
                });
                
                $(frames[frameIndex].document).ready(function(){
                    $("body", frames[frameIndex].document).css("font-size", fontSize);
                    $("#tabs").tabs("select", $("#tabs").tabs("length") - 1);
                    var frameDate = Date.parse(frames[frameIndex].document.lastModified);
                    if (frameDate > modifiedDate) {
                        modifiedDate = frameDate;
                        var newestModifiedDate = new Date(frameDate);
                        $("#lastModifiedLoc").text(newestModifiedDate.toString());
                        $("#lastModifiedLoc").prepend("Last Modified <br/>");
                    }
                });
            }
        });
    });
}

function initSocialNetworks(){

    $.get(socialntwrkConfigLoc, function(data){
        var configArray = data.split("\r\n");
        $("td", "#followus").eq(0).append(configArray[0]);
        for (i = 1; i < configArray.length; i++) {
            var buttonArray = configArray[i].split(";");
            $("td", "#followus").eq(1).append("<img title='" +
            buttonArray[0] +
            "' id='" +
            buttonArray[0] +
            "' class='socialnetworkbtn' src='image/" +
            buttonArray[1] +
            "' href='" +
            buttonArray[2] +
            "'/>");
            $("#" + buttonArray[0]).click(function(){
                window.open($(this).attr("href"));
            });
        }
    });
}

function initDonate(){

    $.get(donateConfigLoc, function(data){
        var configArray = data.split(";");
        $("#donate").append("<img src='image/" + configArray[1] +
        "' id='" +
        configArray[0] +
        "' class='donatebtn' title='Donate Now Through Network for Good'/>");
        $("#" + configArray[0]).click(function(){
            window.open(configArray[2]);
        });
    });
    
    $("#donate").css("position", "absolute");
    $("#donate").css("z-index", "600");
    
    $("#donate").position({
        my: "right bottom",
        at: "right bottom",
        of: $("#donate").parent(),
        offset: "-105 -45"
    });
}

function initDefaultTabs(){

    $.get(defTabConfigLoc, function(data){
        var configArray = data.split("\r\n");
        tabcounter = configArray.length;
        for (i = 0; i < configArray.length; i++) {
            var id = i + 1;
            $("ul", "#tabs").append("<li><a href='#tabs-" + id + "'>" + configArray[i] + "</a></li>");
            $("#tabs").append("<div id='tabs-" + id + "'><iframe src='html/" +
            $("li", "#tabs").last().text().replace(new RegExp(" ", 'g'), "_").replace("?", "").toLowerCase() +
            ".html' allowtransparency='true' frameborder='0'></iframe></div>");
        }
        
        $("#tabs").height(tabContainerHeight + $("#tabs").find("ul").first().height());
        
        $("#tabs").tabs({
            tabTemplate: "<li><a href='#{href}'>#{label}</a> <span class='ui-icon ui-icon-close'>Remove Tab</span></li>",
            event: "click",
            add: function(event, ui){
                $(ui.panel).append("<iframe name='tabframe-" + tabcounter + "' src='html/" +
                tabURL +
                ".html' allowtransparency='true' frameborder='0'></iframe>");
                $("#tabs").height(tabContainerHeight + $("#tabs").find("ul").first().height());
            }
        });
    });
}

/**
 * slide show function
 */
function initSlideShowControl(){

    $.get(slideConfigLoc, function(data){
        var configArray = data.split("\r\n");
        for (i = 0; i < configArray.length; i++) {
            $("#slideshow").append("<iframe allowtransparency='true' frameborder='0' src='html/" + configArray[i] + ".html'></iframe>");
        }
        
        $("#controlloc").hide();
        
        $("#controlloc").mouseover(function(){
            $("#controlloc").show();
        });
        
        $("#controlloc").mouseout(function(){
            $("#controlloc").hide();
        });
        
        $("#slideshow").mouseover(function(){
            $("#controlloc").show();
        });
        
        $("#slideshow").mouseout(function(){
            $("#controlloc").hide();
        });
        
        $("#slideshow").cycle({
            fx: "fade",
            speed: 5000,
            timeout: 8000,
            fastOnEvent: 1,
            easeIn: 'easeInOutExpo',
            easeOut: 'easeInOutExpo'
        });
        
        $("#slidePrev").button({
            text: false,
            icons: {
                primary: "ui-icon-seek-prev"
            }
        });
        
        $("#slidePause").button({
            text: false,
            icons: {
                primary: "ui-icon-pause"
            }
        });
        
        $("#slideNext").button({
            text: false,
            icons: {
                primary: "ui-icon-seek-next"
            }
        });
        
        $("#slidePause").toggle(function(){
            $(this).button("option", "icons", {
                primary: "ui-icon-play"
            });
        }, function(){
            $(this).button("option", "icons", {
                primary: "ui-icon-pause"
            });
        })
        
        $(".slideControl").click(function(){
            var id = $(this).attr("id");
            
            if (id == "slidePrev") {
                $("#slideshow").cycle("prev");
            }
            
            if (id == "slidePause") {
                $("#slideshow").cycle("toggle");
            }
            
            if (id == "slideNext") {
                $("#slideshow").cycle("next");
            }
        });
    });
}

function initHitCounter(){
    $.get(hitCounterConfigLoc, function(data){
        $("#hitcounter").append(data);
    })
}

/**
 * function to find tab according to its label
 *
 * @param {Object} tabLabel label of the tab
 */
function findTab(tabLabel){
    var eleFound = null;
    $("a", $("#tabs")).filter(function(){
        if ($(this).text() == tabLabel) {
            eleFound = this;
        }
    });
    return eleFound;
}

/**
 * function that allows tabs to be closed
 */
function initClosableTabs(){
    $("#tabs span.ui-icon-close").live("click", function(){
        var index = $("li", $("#tabs")).index($(this).parent());
        $("#tabs").tabs("remove", index);
    });
}

/**
 * special hover event for menu items
 *
 * @param {Object} accuracy
 * @param {Object} timeout
 */
function initSpecialHoverEvent(accuracy, timeout){
    var cfg = ($.hoverintent = {
        sensitivity: accuracy,
        interval: timeout
    });
    
    $.event.special.hoverintent = {
        setup: function(){
            $(this).bind("mouseover", jQuery.event.special.hoverintent.handler);
        },
        teardown: function(){
            $(this).unbind("mouseover", jQuery.event.special.hoverintent.handler);
        },
        handler: function(event){
            event.type = "hoverintent";
            var self = this, args = arguments, target = $(event.target), cX, cY, pX, pY;
            
            function track(event){
                cX = event.pageX;
                cY = event.pageY;
            };
            pX = event.pageX;
            pY = event.pageY;
            function clear(){
                target.unbind("mousemove", track).unbind("mouseout", arguments.callee);
                clearTimeout(timeout);
            }
            function handler(){
                if ((Math.abs(pX - cX) + Math.abs(pY - cY)) < cfg.sensitivity) {
                    clear();
                    jQuery.event.handle.apply(self, args);
                }
                else {
                    pX = cX;
                    pY = cY;
                    timeout = setTimeout(handler, cfg.interval);
                }
            }
            var timeout = setTimeout(handler, cfg.interval);
            target.mousemove(track).mouseout(clear);
            return false;
        }
    };
}

