﻿/// <reference path='Search.js' />

//onload method
$(document).ready(function () {
    //language change context menu
    $('#changeLanguage').contextMenu($('#changeLanguage_Menu').hide(), changeLanguage);

    //get a reference to the section table format so it can be duplicated for each source
    var tableFormat = $('#hiddenDiv .sectionDiv').remove();

    //loop through the sources
    for (var x = 0; x < sources.length; x++) {
        var source = sources[x];

        //if skipping this source
        if (typeof sourcesToSearch != 'undefined' && ($.inArray(x, sourcesToSearch) == -1 || !source.enabled))
            continue;

        //build the section table: make sure top doesn't have border, give it id, attach it to area, then give it the header
        tableFormat.clone().attr('id', 'Results' + source.name).appendTo('.resultsMiddle').find('.sectionTitle').text(source.header);
    }

    //wire up expand/collapse buttons for search areas
    var arrowExpand = function () {
        var arrow = $('.sectionArrow', this);
        if (arrow.css('display') != 'none') {
            //don't let hover and click cause a quick close
            if (arrow.data('wait'))
                return;
            arrow.data('wait', true);
            setTimeout(function () { arrow.data('wait', false); }, 500);

            var expanded = arrow.attr('src') == '/Images/arrow_down.gif';
            arrow.attr('src', expanded ? '/Images/arrow_right.gif' : '/Images/arrow_down.gif');
            $(this).parents('.sectionDiv').find('.sectionResults').height(expanded ? sectionResultsMaxHeight : 'auto');
        }
    };
    $('.sectionHeader>span').hoverIntent(arrowExpand, $.noop).click(arrowExpand);

    //wire up autocomplete for the search text
    $('#searchText').autocomplete({
        source: autoCompleteMethod,
        minLength: minSearchLength,
        select: function () { setTimeout(executeSearch, 1); }
    }).keyup(function (event) {
        //if you press enter fire the search and hide the autocomplete
        var stopSearch = event.keyCode == $.ui.keyCode.ENTER;
        if (stopSearch) {
            setTimeout(executeSearch, 1);
            $('#searchText').autocomplete('close').blur();
        }
        $(this).data('searching', !stopSearch);
    });

    //comments submit button only enabled after 5 letters in the comments box
    $('#comments').keyup(function () { $('#commentsButton').attr('disabled', $.trim($(this).val()).length > 5 ? '' : 'disabled'); });

    //addthis button
    $('#addthis').contextMenu($('#addthis_Menu').hide(), function (item) { if ($('a', item).attr('href') != '#') window.open($('a', item)[0].href); });

    if (typeof myonload != 'undefined') myonload();
});

function closeAutoComplete() { $('#searchText').autocomplete('close'); }

function showAbout() {
    var height = $(window).height() * .5;
    $('#aboutCtn').dialog({ height: height, width: 691, dialogClass: 'aboutCtnDialog' });
}

function _showAuthenticate() {
    var buttons = {};
    buttons[submitText + ' >'] = function () { $('#authenticationDialog').submit(); };
    buttons[signin.register] = showRegistration;
    $('#authenticationDialog').dialog({ modal: true, buttons: buttons }).find('input:first').focus();
}
function _showForgotPassword() {
    $('#authenticationDialog').dialog('close');
    var buttons = {};
    buttons[submitText + ' >'] = function () { $('#forgotPasswordDialog').submit(); };
    $('#forgotPasswordDialog').dialog({ modal: true, buttons: buttons }).find('input:first').focus();
}
function _showRegistration() {
    $('#authenticationDialog').dialog('close');

    var buttons = {};
    buttons[submitText + ' >'] = function () { $('#registrationDialog').submit(); };
    $('#registrationDialog').dialog({ modal: true, buttons: buttons, width: 525 }).find('input:first').focus();
}
function populateSpecialtyMethod() {
    $('#jbtitDiv').empty();
    return function (data) {
        $($.map(data, function (item) {
            return $('<div/>').append($('<input type="radio" name="jbtit"/>')
                                            .attr('value', item.ID).add($('<span/>').text(item.Title)));
        })).appendTo('#jbtitDiv');
    };
}


function submitComments() {
    $('#commentsThankYou').show();
    $.ajax({
        url: '/Home/SubmitComment',
        data: { comment: $.trim($('#comments').val()) },
        type: 'POST'
    });
    $('#comments').val('');
    $('#commentsButton').attr('disabled', 'disabled');
}


function _ProcessData(results, context) {
    var source = sources[context.sourceIndex];
    var currentPage = $('#resultsDiv').data('pages')[context.sourceIndex];

    var resultsDiv = $('.sectionResults', '#Results' + source.name);

    if (currentPage == 1) //clear out the timer in this section
        resultsDiv.empty();

    //call the correct draw method and check row count
    var hasRows = (source.multiSection ? DrawMultiSection : DrawDefault)(results, context.sourceIndex, resultsDiv);

    if (currentPage == 1) {
        if (!hasRows)
            appendRowToDiv(false, resultsDiv, noResultsText);
        if (results.length > firstSectionCount)
            collapseSectionResult($('#Results' + source.name), sectionResultsMaxHeight);
    }
    //resultsDiv.append(results.length + ' results... time in milliseconds: ' + (new Date().getTime() - $('#resultsDiv').data('time')));
}

function collapseSectionResult(sectionDiv, maxHeight) {
    //show the expand arrow if there are results in the extra section, drugs comes back as a single object so it never gets the arrow
    var resultsDiv = $('.sectionResults', sectionDiv);
    resultsDiv.height('auto');
    if (resultsDiv.height() > maxHeight) {
        $('.sectionHeader', sectionDiv).css('cursor', 'pointer');
        $('.sectionArrow', sectionDiv).attr('src', '/Images/arrow_right.gif').show();
        resultsDiv.height(sectionResultsMaxHeight);
    }
}


//this method appends a div to the section container (or whatever it's passed) with the correct styles attached
function appendRowToDiv(bAlt, div, content) {
    var row = $('<div/>').addClass('sectionRow' + (bAlt ? ' sectionRowAlt' : ''));
    div.append(row.append($('<div/>').addClass('sectionRowContent').append(content)));
}

function appendError(sourceIndex) {
    //if the callback fails append an error
    $('.sectionCount', '#Results' + sources[sourceIndex].name).text('0');
    var resultsDiv = $('.sectionResults', '#Results' + sources[sourceIndex].name).show();
    appendRowToDiv(false, resultsDiv.empty(), errorResultsText);
}

//draws a default section, one that just lists items that have a url and a title
function DrawDefault(results, sourceIndex, resultsDiv) {
    var source = sources[sourceIndex];
    var currentPage = $('#resultsDiv').data('pages')[sourceIndex];

    //find the tooltip method to use, or use generic
    var tooltipmethod = typeof window['tooltip' + source.name] == 'undefined' ? tooltipGeneric : window['tooltip' + source.name];

    $.each(results, function (cnt, result) {
        var link = $('<a/>').attr('href', result.url).text(result.title);
        //pass bAlt correctly and attach to either main or hidden div
        appendRowToDiv(cnt % 2 == 0, resultsDiv, link);

        tooltip(link, result, tooltipmethod);
        link.hoverClass('sectionRowHover');
    });

    //add an extend search button if the maxCount results have been returned
    $('.extendSearch', resultsDiv).remove();
    if (results.length == source.maxCount && !(source.searchFormat == 'google' && currentPage == (source.cse ? 10 : 8)))//google has max 8 pages (10 for cse)
        $('<div/>').addClass('extendSearch').html(moreText + '...<img src="/Images/arrow_down.gif" alt="' + moreText + '" />').appendTo(resultsDiv)
            .click(function () {
                $(this).unbind('click').html('<img alt="" src="/Images/ajax-loader.gif" />');
                _executeSearch(sourceIndex, currentPage + 1, false);
            });

    return results.length > 0;
}

function DrawMultiSection(results, sourceIndex, resultsDiv) {
    if (results.length == 0) return false;
    var currentPage = $('#resultsDiv').data('pages')[sourceIndex];

    //go through each drug section
    var numResults = 0;
    for (var tableName in results[0]) {
        var sectionResults = results[0][tableName];
        numResults += sectionResults.length;

        //create one line per result, if first page then place it in a holder div, otherwise add it to it's section
        var adivId = 'accordionDiv_' + sourceIndex + '_' + tableName;
        var adiv = currentPage == 1 ? $('<div id="' + adivId + '"/>').hide() : $('#' + adivId);
        DrawDefault(sectionResults, sourceIndex, adiv);

        if (currentPage == 1) {
            //create the accordion header div in the main div
            var accordionExpand = function () {
                var accordionDiv = this;

                //don't let hover and click cause a quick close
                if ($(accordionDiv).data('wait'))
                    return;
                $(accordionDiv).data('wait', true);
                setTimeout(function () { $(accordionDiv).data('wait', false); }, 500);

                var isVisible = $(accordionDiv.parentNode.nextSibling).toggle().is(':visible');
                $(accordionDiv).toggleClass('accordionHeaderExtended', isVisible)
                            .find('img').attr('src', isVisible ? '/Images/arrow_down.gif' : '/Images/arrow_right.gif');
            };

            var header = $('<span/>').html(window[sources[sourceIndex].name + 'Sections'][tableName])
                                        .addClass(sources[sourceIndex].name + 'Sections_' + tableName);
            //don't display arrow and do expansion if there's no results in this section (ie> No Interaction Combinations)
            if (sectionResults.length > 0)
                header.prepend('<img src="/Images/arrow_right.gif" alt="" />&nbsp;')
                    .click(accordionExpand).hoverIntent(accordionExpand, $.noop);
            $('<div class="accordionHeader"/>').append(header).appendTo(resultsDiv);

            //append the accordion div to the main div
            resultsDiv.append(adiv);
        }
    }
    return numResults > 0;
}


//create a tooltip on an element, allowing data to be passed to the tooltip creation function
function tooltip(element, result, fn) {
    $(element).data('resultData', result).tooltip({
        content: function () { return fn($(this).data('resultData')); },
        position: { collision: "fit" }
    });
}


//jquery extensions

//jquery overwrites
var hoverIntentDefaultInterval = 300;

//add hoverClass method to shortcut hover class changes
(function ($) { $.fn.extend({ hoverClass: function (e) { return typeof e == 'string' ? this.hover(function () { $(this).addClass(e); }, function () { $(this).removeClass(e); }) : this; } }); })(jQuery);

//add contextMenu
(function ($) {
    $.fn.extend({
        contextMenu: function (menu, method) {
            menu.menu({
                select: function (event, ui) {
                    $(this).hide();
                    method(ui.item);
                },
                input: $(this)
            });
            return this.data('menu', menu).click(function (event) {
                var menu = $(this).data('menu');
                if (menu.is(":visible")) {
                    menu.hide();
                    return false;
                }
                menu.show().css({ top: 0, left: 0 })
                    .position({ my: "left top", at: "left bottom", of: this, collision: 'fit' });
                $(document).one("click", function () {
                    menu.hide();
                });
                return false;
            });
        }
    });
})(jQuery);