/*
Author:        Wing Ming Chan
Version:       1.0
Last Modified: 7/7/2011
*/

$(function() {

    /* ================== Find a doc ================== */
    /* global path info */
    var site_path             = '/scripts/faculty/';
    var template_path         = '/templates/2011/';
    var clinic_path           = 'clinics/';
    var disease_path          = 'diseases/';
    var doctor_path           = 'doctors/';
    var lib_path              = 'lib/findadoc/';
    var specialty_path        = 'specialties/';

    /* colors */    
    var hover_title_color     = '#ffffff';
    var hover_text_color      = '#e6f5ff';
    var non_hover_title_color = '#33678c';
    var non_hover_text_color  = '#000000'; 
    var hover_box_color       = '#f3f5ea'; // background when a doctor is hovered
    
    // used by pagination
    var num_entry_per_page    = 5;

    /* hide the browse name link for javascript users */
    $('#browse_by_name_list_li').hide();
    $('#no_js_last_name_a_z_list').hide();
    
    /* show hidden h2 */
    $('h2').removeClass("hidden");
    
    /* show hidden interface */
    $('#search_name_fieldset').css('display', 'block');
    $('#search_param_button').css('display', 'block');
    
    /* show message for noscript pages */
    $('#browse_by_last_name_index').load('/hospital/doctors/browse_by_last_name.htm');
    
    /* to light up the menu item when the submenu is hovered */
    // this code does not work for IE6
    if(!$.browser.msie || parseFloat($.browser.version) > 6.0)
    {
        $("ul#nav > li").hover(
            function() {
                $(this).addClass('currentMenuItem');
                $('.currentMenuItem > ul').css('display', 'block');
            }
            ,
            function() {
                //$item_id = '';
                $('.currentMenuItem > ul').css('display', 'none');
                $('.currentMenuItem').removeClass('currentMenuItem');
            });
    }
    
    /* the accordion for the three buttons */
    $(".search_accordion > div").hide();

    $(".search_accordion h2").click(function(){
        var current_button = $(this);
        
        current_button.toggleClass("active");
        current_button.siblings("h2").removeClass("active");
        
        if(current_button.is('.active')) {
            current_button.next('div').slideDown('slow', function() {
                $('.search_browse_button').each(function() {
            
                    $(this).css('background', 
                                'url(' + template_path + 'images/uh-search.jpg) no-repeat');
                    $(this).children().eq(0)
                        .css('color', non_hover_title_color);          
                    $(this).children().eq(1)
                        .css('color', non_hover_text_color);
                });        
                current_button
                    .css('background', 
                         'url(' + template_path + 'images/uh-search.jpg) no-repeat 0 -60px');
                current_button.children().eq(0).css('color', hover_title_color);
                current_button.children().eq(1).css('color', hover_text_color);
                // put focus on input whenever a div is expanded
                $(this).find('input[class=ui-autocomplete-input]').focus();
            });
        } else {
            current_button.next('div').slideUp('slow', function() {
                $('.search_browse_button').each(function() {
                    if($(this).next().css('display') == 'none') {
                        $(this).css('background', 
                                    'url(' + template_path + 'images/uh-search.jpg) no-repeat');
                        $(this).children().eq(0)
                            .css('color', non_hover_title_color);          
                        $(this).children().eq(1)
                            .css('color', non_hover_text_color);
                    }
                });
            });
        }
        
        current_button.next("div").siblings("div:visible").slideUp("slow");
    });
    
    /* light up a button when hovered or when the accordion is expanded
       the hover event is needed even the click event is defined because
       the hover event will be fired after the clicking event */
    $('.search_browse_button').hover(
        function() {
            $(this).css('background', 
                        'url(' + template_path + 'images/uh-search.jpg) no-repeat 0 -60px');
            $(this).children().eq(0).css('color', hover_title_color);
            $(this).children().eq(1).css('color', hover_text_color);
        },
        function() {
            var current_button = $(this);
            
            // back to normal state
            $('.search_browse_button').each(function() {
                if($(this).next().css('display') == 'none') {
                    $(this).css('background', 
                                'url(' + template_path + 'images/uh-search.jpg) no-repeat');
                    $(this).children().eq(0)
                        .css('color', non_hover_title_color);          
                    $(this).children().eq(1)
                        .css('color', non_hover_text_color);
                }
            });
            
            // highlight the expanded button
            if(current_button.next().css('display') != 'none') {
                current_button.css('background', 
                            'url(' + template_path + 'images/uh-search.jpg) no-repeat 0 -60px');
                current_button.children().eq(0).css('color', hover_title_color);
                current_button.children().eq(1).css('color', hover_text_color);
            }
        }
    );
    
    /* create the Top link for long pages */
    function createTopLink() {
        // remove the old link
        // this is necessary because the height of the page may change and 
        // the page may not need such a link
        removeTopLink();
    
        // create the new one if necessary
        $('body').prepend('<a id="top" name="top"></a>');
        $('#result_panel').append('<div id="top_link" class="rightobject"><a href="#top">Top</a></div>');
        $('#centercolumn').append('<div id="top_link" class="rightobject"><a href="#top">Top</a></div>');
    }
    
    /* remove the top link */
    function removeTopLink() {
        $('#top').remove();
        $('#top_link').remove();
    }

    /* functions used by pagination */
    
    // callback when pagination is needed
    function pageselectCallback(page_index, jq) {
        /* hide what is supposed to be hidden */
        $('#hiddenresult').css('display', 'none');
    
        var items_per_page = $('#items_per_page').val();
        var num_entries    = jQuery('#hiddenresult div.physician_brief').length;
        var max_elem       = Math.min((page_index + 1) * items_per_page, num_entries);

        // Iterate through a selection of the content and build an HTML string
        var new_content = '';
    
        for(var i = page_index * items_per_page; i < max_elem; i++) {
            new_content += 
                ('<div class="physician_brief">' + $('#hiddenresult div.physician_brief:eq(' + 
                i + ')').html() + '</div>');
        }
        
        $('#Searchresult').empty().append(new_content);
        $('#pagination_select').removeClass('hidden');
        
        updateBio();

        return false; 
    }
    
    function initPagination() {
        // count entries inside the hidden content
        var num_entries = jQuery('#hiddenresult div.physician_brief').length;
        
        // hide pagination altogether if there are less than X entries
        if(num_entries == 0) {
            return;
        }
        
        if(num_entries <= num_entry_per_page) {
            $('#hiddenresult').css('display', 'block');
            $('#pagination_select').css('display', 'none');
            $('#Searchresult').css('display', 'none');
            
            // hide the top link if there are less than 5
            if($("#result_content").height() < 3000)
            //if(num_entries < num_entry_per_page) 
            {
                removeTopLink();
            }

            return;
        }
        else {
            if($("#result_content").height() < 3000)
            //if(num_entries < num_entry_per_page) 
            {
                removeTopLink();
            }
            else
            {
                // create the Top link only when the navigation is shown
                createTopLink();
            }
        }
      
        // Create content inside pagination element
        $(".Pagination").pagination(
            num_entries, 
            {
                callback: pageselectCallback,
                items_per_page: $('#items_per_page').val(),
                num_display_entries: 5,
                num_edge_entries: 2
            });
        
        // when the number of doc per page select is changed,
        // redo the pagination
        $('#items_per_page').change(function() {
            $(".Pagination").pagination(
                num_entries, 
                {
                    callback: pageselectCallback,
                    items_per_page: $('#items_per_page').val(),
                    num_display_entries: 5,
                    num_edge_entries: 2
                });
        });
    }
    
    /* change the background color of a doctor when hovered */
    function docHover() {
        $('.physician_brief_content').hover(
            function(){
                $(this).css('background', hover_box_color);
            },
            function(){
                $(this).css('background', hover_title_color);
            }
        );
    }
    
    /* load the content of a doctor to the overlay */
    function loadFileForOverlay() {
        var $loadingIndicator = $('<img/>')
            .attr({
                'id':     'load-wait',
                'src':    '/templates/2011/images/ajax-loader.gif',
                'alt':    'Loading. Please wait.',
                'width':  '32',
                'height': '32'
            })
            .css({'position':'fixed', 'top':300, 'left': $('body').width() / 2 + 150})
            .appendTo($('#leftcenterrightcolumn'));
            
        // this assumes that the id is in the format of xxxxxx_file-name
        var wrap = this.getOverlay().find(".simple_overlay_inner");
        var id = wrap.attr('id');
        var pos = id.indexOf('_'); // first _
        var file_name = id.substr(pos + 1, id.length - pos - 1);
            wrap.load(site_path + lib_path + 'process_filename.php?filename=' + file_name,
            function()
            {
                $loadingIndicator.remove();
                $('#rq_button_div').hide();
            });
            
        // force overlay to stay on top in IE by attaching overlay to body
        var overlay_id = this.getOverlay().attr('id');
        var overlay_parent = $('#' + overlay_id).parent().attr('id');
        
        this.getOverlay().remove().appendTo("body");
        // save the overlay for later use
        var popup = this;
            
        /* function used to close an overlay */
        $(".close").click(function(e)
        {  
            // close the overlay
            // hide the content first so that font-sizes do not matter */
            $('.simple_overlay_inner').html('');
            // close overlay
            popup.close();
            // return the overlay to the parent so that overlay can be reused
            popup.getOverlay().appendTo($('#' + overlay_parent));
            // remove the hash value
            //window.location.hash = '';
        });
    }
    
    /* update the doc bio */
    function updateBio() {
        docHover();
        $('h2').removeClass("hidden");

        var num_entries = jQuery('#hiddenresult div.physician_brief').length;
        
        // overlay
        for(var i = 1; i <= num_entries; i++) {
            $("#img_mies" + i).attr({'rel':'#mies' + i});
            $("#a_mies" + i).attr({'rel':'#mies' + i});
            $("#a_mies_more" + i).attr({'rel':'#mies' + i});
        }
        
        $("img[rel]").overlay({
            onBeforeLoad: loadFileForOverlay
        });
        
        $("a[rel]").overlay({
            onBeforeLoad: loadFileForOverlay
        });
    }
    
    // intercept and process return keypress
    $('#name').keypress(function(e) {
        if(e.which == 13){
            e.preventDefault();
            $('#submit_name').click();
        }
    });
    
    $('#specialty').keypress(function(e) {
        if(e.which == 13){
            //$('#search_name_form').submit();
            $('#submit_param').click();
            e.preventDefault();
        }
    });
    
    // clear text input to clear sticky title
    $('#search_param_button').click(function() {
        $('#name').attr('value', '');
        $('#name').attr('title', '');
        $('#specialty').focus();
    });
    
    $('#search_name_button').click(function() {
        $('#specialty').attr('value', '');
        $('#specialty').attr('title', '');
        $('#name').focus();
    });
    
    /* AJAX code to process name A-Z list */
    $('#name_a_z_list a').click(function() {
        var $loadingIndicator = $('<img/>')
            .attr({
                'id':     'load-wait',
                'src':    '/templates/2011/images/ajax-loader.gif',
                'alt':    'Loading. Please wait.',
                'width':  '32',
                'height': '32'
            })
            .css({'top': 200, 
                'left': 650,
                'position': 'absolute'
            })
            .appendTo($('#leftcenterrightcolumn'));
    
        $('#result_content').load(site_path + lib_path + 
            'process_name_list.php?alpha=' + $(this).text(),
            function() {
                $loadingIndicator.remove();
                initPagination();
                updateBio();
            });

        return false;
    });
    
    /* AJAX code to process form submit */
    $('#submit_name').click(function() {
        id   = $('#name').attr('title');
        name = $('#name').attr('value');
        
        $('#result_content').load(site_path + lib_path 
             + 'process_name.php?id=' + id + '&name=' + urlencode(name),
             function() {
                initPagination();
                updateBio();
             });
        
        /* google analytics code */
        if(id != '' && name != '') {
        	_gaq.push(['_trackEvent', "Name Search: " + name, 'clicked']);
        }
        
        return false;
    });
    
    function urlencode(str) {  
        return escape(str).replace(/\+/g,'%2B').replace(/%20/g, '+')
            .replace(/\*/g, '%2A').replace(/\//g, '%2F').replace(/@/g, '%40');  
    }  

    $('#reset_param').click(function() {
        // clear the text
        $('#specialty').val('');
        // check the third button
        $('input:radio[name=gender]:eq(2)').attr('checked', 'checked');
        $('input:radio[name=type]:eq(2)').attr('checked', 'checked');
        // fall back to the first option
        $("select").val('Null');
        // return focus to text input
        $('#specialty').focus();
        
        return false;
    });

    $('#submit_param').click(function() {
        var type      = $('input:radio[name=type]:checked').val();
        var specialty = $('#specialty').val();
        var location  = $('#location').val();
        var gender    = $('input:radio[name=gender]:checked').val();
        var language  = $('#language').val();
        var id        = $('#specialty').attr('title');
        
        // first remove the top link, which can be added back later
        removeTopLink();
        
        // private function
        var cleanup = function(input) {
            input = encodeURI(input);
            input = escape(input);
            return input;
        }
        
        var $loadingIndicator = $('<img/>')
            .attr({
                'id':     'load-wait',
                'src':    '/templates/2011/images/ajax-loader.gif',
                'alt':    'Loading. Please wait.',
                'width':  '32',
                'height': '32'
            })
            .css({'top': 200, 
                  'left': 650,
                  'position': 'absolute'
            })
            .appendTo($('#leftcenterrightcolumn'));
              
        //$('#result_content').load(site_path + lib_path + 'process_param_db.php?' +
        $('#result_content').load(site_path + lib_path + 'process_param.php?' +
            'type=' + type +
            '&specialty=' + cleanup(specialty) +
            '&location=' + cleanup(location) +
            '&gender=' + gender +
            '&language=' + language +
            '&id=' + id,
            function() {
                $loadingIndicator.remove();
                initPagination();
                updateBio();
                
                // turn the h1 into h2 and change the title
                var h1_text = $('#result_panel h1').text();
                var h1Array = h1_text.split(":");
                //h1_text = "Results:" + h1Array[1];
                h1_text = "Results: " + h1_text;

                $('#result_panel h1').replaceWith('<h2>' + h1_text + '</h2>');
                $('#result_panel #diseases_a_z_list').hide();
            });
        
        /* google analytics code */
        if(id != '' && specialty != '') {
        	specialty_fixed = toTitleCase(specialty);
            _gaq.push(['_trackEvent', "Disease: " + specialty_fixed, 'clicked']);
        }
        
        if(language != 'Null') {
        	_gaq.push(['_trackEvent', "Language: " + language, 'clicked']);
        }
        
        if(location != 'Null') {
        	_gaq.push(['_trackEvent', "Location: " + location, 'clicked']);
        }
        
        if(gender != 'no_preference') {
        	gender_fixed = gender.charAt(0).toUpperCase() + gender.substr(1).toLowerCase();
        	_gaq.push(['_trackEvent', "Gender: " + gender_fixed, 'clicked']);
        }
        
        if(type != 'no_preference') {
        	type_fixed = type.charAt(0).toUpperCase() + type.substr(1).toLowerCase();
        	_gaq.push(['_trackEvent', "Treats: " + type_fixed, 'clicked']);
        }
        
        return false;
    });
    
    function toTitleCase(str)
    {
        return str.replace(/\w\S*/g, function(txt) {
            return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
    }
    
    /* extension to select the first child of autocomplete ui
       by Scott Gonzalez (http://scottgonzalez.com) */
    $(".ui-autocomplete-input").live( "autocompleteopen", function() {
        var autocomplete = $(this).data("autocomplete"),
                           menu = autocomplete.menu;
        
        if (!autocomplete.options.selectFirst) {
            return;
        }
        
        menu.activate($.Event({type: "mouseenter"}), menu.element.children().first());
    });
    
    /* autocomplete */
    $("#name").autocomplete(
        {
            source: site_path + lib_path + 'process_name_autocomplete.php?callback=?',
            minLength: 2,
            delay: 0,
            select: function(event, ui) {
                $("#name").attr({value: ui.item.label, title: ui.item.id});
                $('#submit_name').click();
            },
            selectFirst: true // rely on the extension above
        });
    
    $("#specialty").autocomplete(
        { 
            source: site_path + lib_path + 'process_specialty_autocomplete.php?callback=?',
            minLength: 2,
            delay: 0,
            select: function(event, ui) {
                $("#specialty").attr({value: ui.item.label, title: ui.item.id});
            },
            selectFirst: true
        });
    
    
    /* initialization for browsing */
    initPagination();

    /* customized accordion code */
    $(".search_accordion h2, .search_accordion > div").addClass("js");
    
    updateBio();
    
    $('#pagination_select').removeClass('hidden');
    $('#personalinfo').hide();
    $('#additional').hide();
    $('#researchabst').hide();
    
    /* ================== Homepage ================== */
    /*
    $(
    "<div><img src='/hospital/images/homeslide2.jpg' width='950' height='280' alt='Photo 2' /><div id='banner_link2'><a class='banner_link' href=''></a></div></div>" + 
    "<div><img src='/hospital/images/homeslide3.jpg' width='950' height='280' alt='Photo 3' /><div id='banner_link3'><a class='banner_link' href=''></a></div></div>").insertAfter($('#first_slide'));
    */
    

    $("#ad_block").scrollable({circular: true}).autoscroll({autoplay:true, interval:10000});
    $("#ad_block_items").css("left", "-249px");
    
    // show hidden navigation
    $(".scroll_nav").show();
    
    $('#info_block li, #about_block li').hover(
        function() {
            $(this).css({background:'#ffffff', listStyle:'none'});
        },
        function() {
            $(this).css('background', '');
    });
});

