//weblegs js footprint engine

var F = {
    engineNamespace: undefined,
    xhrCryBaby: false,
    cd: undefined,
    
    /**
     * sets up our engine
     */
    setup: function() {
        //set page namespace
        var myLocation = window.location.pathname;
        myLocation = myLocation.substring(1, myLocation.length);
        myLocation = myLocation.replace(".html", "");
        if(myLocation == "") { myLocation = "index"; }
        F.engineNamespace = myLocation;
    },
    
    /**
     * the global init (first thing added to "$(document).ready(xyz)"
     */
    init: function() {
        //mark active tabs by section
        if(F.engineNamespace.indexOf("online-degrees/") > -1) {
            $("[id='tab-online-degrees/index']").attr("class", "active");
        }
        else if(F.engineNamespace.indexOf("how-to-guide/") > -1) {
            $("[id='tab-how-to-guide/index']").attr("class", "active");
        }
        else if(F.engineNamespace.indexOf("financial-assistance/") > -1) {
            $("[id='tab-financial-assistance/index']").attr("class", "active");
        }
        else if(F.engineNamespace.indexOf("campuses/") > -1) {
            $("[id='tab-campuses/index']").attr("class", "active");
        }
        else if(F.engineNamespace == "index") {
            $("[id='tab-index']").attr("class", "active");
        }
        else {
            //handle like normal
            $("[id='tab-"+ F.engineNamespace +"']").attr("class", "active");
        }
        
        //setup cd finders
            if($("form.qdf").get(0) != undefined) {
                //setup form
                $("form.qdf").attr("action", "details/online-finder.html");
                $("form.qdf").attr("method", "get");
                $("form.qdf").unbind("submit").submit(function() {
                    var n = $("form.qdf select[name='degree_level_id']").val();
                    if(!(!isNaN(parseFloat(n)) && isFinite(n))) {
                        alert("Choose a degree.");
                        return false;
                    }
                    
                    n = $("form.qdf select[name='category_id']").val();
                    if(!(!isNaN(parseFloat(n)) && isFinite(n))) {
                        alert("Choose a category.");
                        return false;
                    }
                    
                    n = $("form.qdf select[name='subject_id']").val();
                    if(!(!isNaN(parseFloat(n)) && isFinite(n))) {
                        alert("Choose a subject.");
                        return false;
                    }
                });
                
                //is there defaults to set?
                var DefaultDegree = $("form.qdf select[name='degree_level_id']").attr("default");
                var DefaultCategory = $("form.qdf select[name='category_id']").attr("default");
                var DefaultSubject = $("form.qdf select[name='subject_id']").attr("default");
                
                //setup the drop downs
                    //(*no defaults*)
                    if(DefaultDegree == undefined && DefaultCategory == undefined && DefaultSubject == undefined) {
                        F.CD = new QuickDegreeFinder().populate(
                            "form.qdf select[name='degree_level_id']",
                            "form.qdf select[name='category_id']",
                            "form.qdf select[name='subject_id']"
                        );
                    }
                    //(Degree)
                    if(DefaultDegree != undefined && DefaultCategory == undefined && DefaultSubject == undefined) {
                        F.CD = new QuickDegreeFinder().populate(
                            "form.qdf select[name='degree_level_id']",
                            "form.qdf select[name='category_id']",
                            "form.qdf select[name='subject_id']"
                        ).setDefaults(DefaultDegree);
                    }
                    //(Degree,Category)
                    if(DefaultDegree != undefined && DefaultCategory != undefined && DefaultSubject == undefined) {
                        F.CD = new QuickDegreeFinder().populate(
                            "form.qdf select[name='degree_level_id']",
                            "form.qdf select[name='category_id']",
                            "form.qdf select[name='subject_id']"
                        ).setDefaults(DefaultDegree, DefaultCategory);
                    }
                    //(Degree,Category,Subject)
                    if(DefaultDegree != undefined && DefaultCategory != undefined && DefaultSubject != undefined) {
                        F.CD = new QuickDegreeFinder().populate(
                            "form.qdf select[name='degree_level_id']",
                            "form.qdf select[name='category_id']",
                            "form.qdf select[name='subject_id']"
                        ).setDefaults(DefaultDegree, DefaultCategory, DefaultSubject).onReady(F.CDSubjectFixer);
                    }
                //end setup the drop downs
            }
        //end setup cd finders
        
        //setup qu finders
            if($("form.qsf").get(0) != undefined) {
                //setup form
                $("form.qsf").attr("action", "details/offline-finder.html");
                $("form.qsf").attr("method", "get");
                $("form.qsf").unbind("submit").submit(function() {
                    var zip = $("form.qsf input[name='pc']").val();
                    if(zip == "") {
                        alert("Enter your zip code.");
                        return false;
                    }
                });
            }
        //end setup qu finders
        
        //setup our "goto" links
            $("[goto]").each(function(){
                $(this).attr("href", $(this).attr("goto"));
                $(this).removeAttr("goto");
            });
        //end setup our "goto" links
        
        //setup data-confirm functionality
        $("[data-confirm]").click(function() {
            return(confirm($(this).attr("data-confirm")));
        });
        
        //tab drop down bindings
        $("body").bind("click", function (e) {
            $('.dropdown-toggle, .menu').parent("li").removeClass("open");
        });
        $(".dropdown-toggle, .menu").click(function (e) {
            var $li = $(this).parent("li").toggleClass('open');
            return false;
        });
        
        //setup the date pickers
        $("[data-date-picker]").datepicker();
        
        //setup the time ago feature
        $("[data-time-ago]").each(function() {
            var totalSecondsAgo = parseInt($(this).text()) ? parseInt($(this).text()) : 0;
            var depth = parseInt($(this).attr("data-time-ago")) ? parseInt($(this).attr("data-time-ago")) : 1;
            
            var timeAgo = new Array();
            timeAgo.push({value: Math.floor(totalSecondsAgo / 86400), type: "day"});
            timeAgo.push({value: Math.floor((totalSecondsAgo / 3600) - (timeAgo[0].value * 24)), type: "hour"});
            timeAgo.push({value: Math.floor((totalSecondsAgo / 60) - (timeAgo[0].value * 1440) - (timeAgo[1].value * 60)), type: "minute"});
            timeAgo.push({value: Math.floor(totalSecondsAgo % 60), type: "second"});
            
            var output = "";
            for(var i = 0 ; i < timeAgo.length ; i++) {
                if(timeAgo[i].value != 0) {
                    output += timeAgo[i].value +" "+ timeAgo[i].type + (timeAgo[i].value > 1 ? "s" : "") +", ";
                    depth--; if(depth <= 0) { break; }
                }
            }
            
            //is the output empty
            if(output == "") { output = "0 seconds, "; }
            
            //remove the last comma+space
            output = output.substr(0, output.length - 2);
            
            //place the new value
            $(this).text(output +" ago");
        });
        
        //call the Page.init if it exists
        if(typeof(Page) != "undefined") {
            Page.init();
        }
    },
    
    /**
     * our xhr shorthand method
     */
    xhr: function(argData, argCallBack, argType, argURL) {
        if(argData == undefined) { argData = ""; }
        if(argCallBack == undefined) { argCallBack = ""; }
        if(argType == undefined || argType == "") { argType = "GET"; }
        if(argURL == undefined || argURL == "") { argURL = F.engineNamespace +".html"; }
        
        //create ajax object
        var xhrInstance = {
            datatype: "json",
            type: argType,
            data: argData,
            url: argURL,
            
            //loading handler
            beforeSend: function(request) { $("[class='ajax-running']").show(100); },
            
            //success handler
            success: function(jResponse, status, response) {
                //hide loading indicator
                $("[class='ajax-running']").hide();
                
                //process sections
                if(typeof(jResponse) == "object") {
                    if(jResponse["sections"]) {
                        F.processSections(jResponse["sections"]);
                    }
                    //do we have a callback?
                    if(argCallBack) {
                        if(typeof(argCallBack) == "function") {
                            argCallBack(jResponse, this);
                        }
                        else {
                            eval(argCallBack +"(jResponse, this)");
                        }
                    }
                }
            },
            
            //error handler
            error: function(response, text, error){
                //hide loading indicator
                $("[class='ajax-running']").hide();
                
                //should we cry?
                if(F.xhrCryBaby) {
                    //notify of error
                    alert("this.xhr: There was an error.\n"+ error);
                    
                    //get response and show in pop-up
                    var ErrorWindow = window.open("", "Error", "status=no,scrollbars=yes,resizable=yes,width=640,Height=480");
                    if(ErrorWindow){
                        ErrorWindow.document.write(response.responseText);
                    }
                }
            }
        };
        
        //execute request
        $.ajax(xhrInstance);
    },
    
    /**
     * proccesses the xhr request sections
     */
    processSections: function(sections) {
        for(var section in sections) {
            $("[data-section='"+ section +"']").html(sections[section]);
        }
        
        if(typeof(Page) != "undefined") {
            if(typeof(Page.attachEvents) != "undefined") {
                Page.attachEvents();
            }
        }
    },
    
    /**
     * our shorthand method for querystring data
     */
    input: function(name) {
        var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
        return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
    }
};

/**
 * setup engine before anything else happens
 */
F.setup();

/**
 * register our engine init method with jquery's ready event
 */
$(document).ready(F.init);

