/**
 * UVa User Interface
 */ 
var UVa = {
    /**
     * Init UI functions
     */         
    init: function () {
        UVa.SortableBoxes.init();
        UVa.textSize();
        // UVa.emulateHover($('#nav li'));
        // UVa.mainNav();
        UVa.sitePrefsToggle($('.prefs a:first'));
        UVa.homeAccordion();
        UVa.audiencePanels();
        UVa.expandableBoxes();
        UVa.rollovers();
        UVa.preloadImages(["images/buttons/index-submit_over.gif", 
                           "images/buttons/full-page_over.gif", 
                           "images/bg/flyout.jpg", 
                           "images/bg/audience-panel.jpg"]);
        UVa.azIndex('#az-index-search', '#az-index-results', '#az-desc');
        $(".az-index form").bind("submit", function() { return false; });
        UVa.wipSlideshow('#slideshow', '{timeout: 5000}');
        UVa.loadPrefs();
    },
    /**
     * Increase/decrease text size
     */          
    textSize: function () {
        if ($.cookie('larger-text')) {
            $('body').addClass('large-text');
        }
        $('.accessibility .increase').bind('click', function () {
            $('body').addClass('larger-text');
            $.cookie('larger-text', 1);
            return false;
        });
        $('.accessibility .decrease').bind('click', function () {
            $('body').removeClass('larger-text');
            $.cookie('larger-text', null);
            return false;
        });
    },
    /**
     * Home page accordion
     */ 
    homeAccordion: function () {
        $('#home-accordion').accordion({
            header: 'h2',
            autoHeight: false,
            clearStyle: true,
            changestart: function(event, ui) {
                ui.oldHeader.removeClass('current');
                ui.newHeader.addClass('current');
                ui.oldContent.slideToggle('fast');
                ui.newContent.slideToggle('fast');
            }
        });
    },          
    /**
     * Toogle expandle boxes on home page
     */         
    expandableBoxes: function () {
        $('.expandable-box .tab a').bind('click', function () {
             $(this).parents('.expandable-box').find('.inner').toggleClass('expanded-box');
             $(this).toggleClass('expanded');
             return false;
        });
    },
    /**
     * Toogle alumni panels
     */         
    audiencePanels: function () {
        var panels = $('.audience-panel:not(.audience-panel-static)');
        var links = $('#audience-nav:not(.audience-nav-static) a');
        links.each(function (i) {
            $(this).bind('click', function () {
                var curLink = $(this);
                if(curLink.hasClass('current')) {
                    curLink.removeClass('current');
                    $(panels[i]).slideUp().removeClass('current');
                } else {
                    if(links.filter('.current').length > 0) {
                        links.filter('.current').removeClass('current');
                        panels.filter('.current').removeClass('current').slideUp("normal" , function() {
                            curLink.addClass('current');
                            $(panels[i]).slideDown().addClass('current');
                        });
                    } else {
                        curLink.addClass('current');
                        $(panels[i]).slideDown().addClass('current');
                    }
                }
                return false;
            });
        });
    },
    /**
     * Emulate hover in IE6
     */          
    emulateHover: function (items) {
        items.hover(
            function () {
                $(this).addClass('hover');
            },
            function () {
                $(this).removeClass('hover');
            }
        )
    },
    /**
     * Site Preferences toggler
     */          
    sitePrefsToggle: function (items) {
       items.toggle(
           function () {
               $(this).parent().addClass('active');
           },
           function () {
               closePrefsPanel();
           }
       )
   },
    /**
     * Main navigation
     */          
    mainNav: function () {
        $("#nav > li > a").bind('click', function () {
            $("#nav > li > a").not(this).parent().removeClass('hover');
            if($(this).next() && $(this).next().is('.flyout')) {
              $(this).parent().toggleClass('hover');
              return false;
            }
            return true;
        });
    },
    /**
     * Rollovers buttons
     */
    rollovers: function () {
        $('.rollover').hover(
            function () {
                $(this).attr('src', $(this).attr('src').replace(/.gif/, '_over.gif'));
            },
            function () {
                $(this).attr('src', $(this).attr('src').replace(/_over.gif/, '.gif')); 
            }
        );
    },
    /**
     * Preload images
     * @param {Array} images array with names of images   
     */               
    preloadImages: function (images) {
        for (var i = 0; i < images.length; i++) {
            var image = new Image();
            image.src = images[i];
        }
    },
    /** 
     * A-Z Index Autocomplete
     * @param searchbox - <input> to be bound
     * @param results - id of results target
     * @loading - id of loading image/animation
     * @desc - id of element which describes the content (ARIA)
     */
    azIndex: function (searchbox, results, desc) {
        clearAutoComplete();
        setAutoComplete(searchbox, results);
        autoComplete("a", "alpha");
        $(searchbox).focus(function(){ $(this).attr("value",""); });
        $(desc).hide();
    },
    /** 
     * WIP Slideshow
     * @param args - options for slideshow (str)
     */
    wipSlideshow: function (target, args) {
        $(target).slideshow({timeout: 5000});
    },
    loadPrefs: function() {
        //nav mouseover or hover
        if($.cookie('prefs_navclick') !== null && $.cookie('prefs_navclick') == "1") {
          UVa.emulateHover($('#nav li'));
        } else {
          UVa.mainNav();
        }
        //accordion
        if ($.cookie('prefs_accordion') !== null && $.cookie('prefs_accordion') != '') {
          $('#home-accordion').accordion('activate', parseInt($.cookie('prefs_accordion')));
        }
        //search
        if ($.cookie('prefs_search') !== null && $.cookie('prefs_search') != '') {
          $(".search_type:eq(" + $.cookie('prefs_search') + ")").attr("checked","checked");
          $(".search_type2:eq(" + $.cookie('prefs_search') + ")").attr("checked","checked");
        } else {
          $(".search_type:eq(0)").attr("checked","checked");
          $(".search_type2:eq(0)").attr("checked","checked");
        }
    }
}
/**
 * Sortable boxes 
 */
UVa.SortableBoxes = {
    closed: Array, 
    numSortables: 3,
    /**
     * Init function
     */          
    init: function () {
        UVa.SortableBoxes.moveBoxes();
        UVa.SortableBoxes.toggleBoxes();
        UVa.SortableBoxes.toggleBoxesOnLoad();
    },
    /**
     * Move sortable boxes
     */         
    moveBoxes: function () {
        $("#sortable1").sortable({
            connectWith: ["#sortable2", "#sortable3"],
            handle: "h2",
			update: function(e, ui) {
               UVa.SortableBoxes.createCookie('sortable1', $(this).sortable('toArray'));
            },
            receive: function(e, ui) {
                UVa.SortableBoxes.createCookie('sortable1', $(this).sortable('toArray'));
            },
            remove: function(e, ui) { 
                UVa.SortableBoxes.createCookie('sortable1', $(this).sortable('toArray'));
            } 
        }); 
        $("#sortable2").sortable({
            connectWith: ["#sortable1", "#sortable3"],
            handle: "h2",
			 update: function(e, ui) { 
               UVa.SortableBoxes.createCookie('sortable2', $(this).sortable('toArray')); 
            },
            receive: function(e, ui) { 
                UVa.SortableBoxes.createCookie('sortable2', $(this).sortable('toArray')); 
            },
            remove: function(e, ui) { 
                UVa.SortableBoxes.createCookie('sortable2', $(this).sortable('toArray'));
            } 
        });
        $("#sortable3").sortable({
            connectWith: ["#sortable1", "#sortable2"],
            handle: "h2",
			 update: function(e, ui) { 
               UVa.SortableBoxes.createCookie('sortable3', $(this).sortable('toArray')); 
            },
            receive: function(e, ui) { 
                UVa.SortableBoxes.createCookie('sortable3', $(this).sortable('toArray')); 
            },
            remove: function(e, ui) { 
                UVa.SortableBoxes.createCookie('sortable3', $(this).sortable('toArray'));
            } 
        });
    },
    createCookie: function (column, boxes) {
       //alert(column);
        var cookie = '';
        for (var i = 0; i < boxes.length; i++) {
            cookie += boxes[i] + ".";
        }
       // alert(cookie);
        $.cookie(column, cookie, {expires: 365});
    },
    /**
     * Toggle boxes on/off
     */         
    toggleBoxes: function () {
        var links = $(".customize-box h2 a, .sortable-box h2 a")
        links.bind('click', function () {
             var closedboxes = '';
             $(this).parents('li').toggleClass('sortable-box-closed');
             $('.sortable-box-closed').each(function (i) {
                 closedboxes += $(this).attr('id') + '.';
             });
             $.cookie('closedboxes', closedboxes, {expires: 365});
             return false;
        });
    },
    /**
     * Close boxes onload 
     */         
    toggleBoxesOnLoad: function () {
        // Check if user set any boxes to be closed
        if ($.cookie('closedboxes') !== null && $.cookie('closedboxes') != '') {
            var closedboxes = $.cookie('closedboxes').slice(0, -1);
            UVa.SortableBoxes.closed = closedboxes.split('.');
        // Cookie is set but is empty - user have all boxes opened    
        } else if ($.cookie('closedboxes') !== null && $.cookie('closedboxes') == '') {
            UVa.SortableBoxes.closed = [];
        }
        if (UVa.SortableBoxes.closed.length > 0) {
            for (var i = 0; i < UVa.SortableBoxes.closed.length; i++) {
                $("#" + UVa.SortableBoxes.closed[i]).addClass('sortable-box-closed');
            }
        }
    }
}    
$(document).ready(function () {
    UVa.init();
});