// Main JavaScript Init
$(document).ready(function(){
    
    initMenu();
    initToggle();
    initTabs();
});

function initToggle() {
    //init "read more" content toggle
    $('h6.toggle').click(function() {
        $(this).next().toggle("normal");
        $(this).toggleClass('upArrow');
        return false;
    });
    
    //init FAQ toggle
    $('a.toggle').click(function() {
        $(this).next().toggle("normal");
        $(this).toggleClass('open');
        if($(this).hasClass("open")) {
            $(this).toggleQuestionHistory(true);            
        } else {
            $(this).toggleQuestionHistory(false);    
        }
        return false;
    });
    
};

//Toggle URL hash history
$.fn.toggleQuestionHistory = function(add) {
    
    var hash = window.location.hash;
    var anchor_id = $(this).attr("id");
    
    //must be formatted correctly before we try to change hash
    if (anchor_id.length>5) {    
        if (add) {
            window.location.hash = anchor_id.substr(3); // set anchor as hash (less pr_ prefix)
        } else {
            window.location.hash = anchor_id.substr(3, 4); //only set year as hash
        }    
    }
    return this;
};


function initTabs() {
    // only init if they exist
    if ($("ul#tabs").length>0) {  
        
        $("ul#tabs").tabs("div.panes > div", { history: true});
        
        if (window.location.hash) { // the URL contains an anchor
            var hash = window.location.hash.split('#')[1];
            var anchors = hash.split('_');
            
            //has additional anchors indicated by underscore
            if (anchors.length>0) {
                
                var tab = anchors[0];
                var prefix = 'pr_';
                var question = prefix+hash;
                
                var api = $("ul#tabs").data("tabs");
                api.click(tab);
                
                if ($("#"+question).length>0) { // ensure question exists   
                    
                    $("#"+question).next().toggle(true); // expand question
                    $("#"+question).addClass('open');
                    
                    var prevHR = $("#"+question).prev().prev();
                    $.scrollTo(prevHR);
                    
                }
                
            }
        }
        
    };
}

function initMenu() {
    // init dropdown nav
    $('#mainNav').dropDownMenu({timer: 500, parentMO: 'parent-hover', childMO: 'child-hover'});
};


function submitSearch() {
    document.forms["search_form"].submit();
}


function clearField(tF) {
    if(tF.defaultValue == tF.value) {
        tF.value = ""; tF.style.color = "black";
    }
}

function selectShow(select, trigger, element) {
    $(select).change(function() {
        $(element).css("display", ($(this).val() == trigger) ? 'block' : 'none');
    });
    //fire change event in case trigger is default value
    $(select).trigger("change");
    
}




