﻿/// <reference path='Search.js' />

//onload method
function myonload() {

    $.each(sources, function (i) { appendCategory(i); });
    showResultsDivs(true);

    //Todo: handle drag to first/last case in IE8: http://dev.jqueryui.com/ticket/5772
    $('#categoriesDiv').sortable({ containment: 'parent', placeholder: 'categoriesDiv_Sort',
        update: function () {

            window.sources = $('#categoriesDiv input:checkbox').map(function (i, elm) { return sources[$(elm).data('sourceIndex')]; });

            setCookieCategories(function () { location.reload(); });
        }
    });

    //add category dialog
    $('#categoryAdd').click(addCategory);

    //close section area when hovering over it
    /*$('.sectionDiv').hoverClass('sectionDivHover');
    $.each(sources, function (i, source) {
        $('#Results' + source.name + ' .sectionDivClose').click(function () {
            $('#categoriesDiv input:checkbox:eq(' + i + ')').attr('checked', false).click();
        });
    });*/



    //wire up expand/collapse buttons for categories areas
    var arrowExpand = function () {
        var arrow = $('img', this);

        //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/bigarrow_down.png';
        arrow.attr('src', expanded ? '/Images/bigarrow_right.png' : '/Images/bigarrow_down.png');
        $('#categoriesDiv').toggle(!expanded);
    };
    $('#categoriesText>div').hoverIntent(arrowExpand, $.noop).click(arrowExpand);

    //focus the search on load
    $('#searchText').focus();

    //back button - re-execute
    if (getSearchText().length > 0)
        executeSearch();
    else //chrome back button resetting search
        $.ajax({
            url: '/Home/GetSearchTerm/?' + Math.ceil(100000000 * Math.random()), //don't cache this url
            success: function (data) {
                if (data != null && data != '' && getSearchText() == '') {
                    $('#searchText').val(data);
                    executeSearch();
                }
            }
        });
}

//populate categories customization
function appendCategory(sourceIndex) {
    var source = sources[sourceIndex];
    //need to store source name in checkbox so when re-ordering can trace the category
    var chk = $('<input type="checkbox"/>').data('sourceIndex', sourceIndex)
                    .click(function () {
                        source.enabled = this.checked;
                        showResultsDivs();

                        //populate this area when showing it
                        if (this.checked && $('#resultsDiv').is(':visible'))
                            _executeSearch(sourceIndex, 1, false);
                    });

    var cat = $('<div/>').html(source.header).append(chk).appendTo('#categoriesDiv').hoverClass('categoryHover');

    if (source.custom) {
        var closeBut = $('<img/>').attr('alt', deleteText).attr('src', '/Images/trash.gif').css('margin-right', '2px').css('margin-bottom', '2px')
                        .click(function () { confirmDelete(sourceIndex); });
        var editBut = $('<img/>').attr('alt', editText).attr('src', '/Images/edit.jpg').css('margin-left', '2px')
                        .click(function () { addCategoryDialog(sourceIndex); });
        $('<div/>').addClass('customCategoryButtons').prependTo(cat).append(closeBut).append('<br/>').append(editBut);
    }

    //need to do this after append due to ie6 bug storing state of checkboxes before append
    chk.attr('checked', source.enabled);
}

function showResultsDivs(bSkipCookieSet) {
    //hide all sections and remove first class
    $('.sectionDiv').hide().removeClass('sectionDivFirst');
    //show checked elements and place them in correct order
    $($('#categoriesDiv input:checked').map(function (i, elm) { return $('#Results' + sources[$(elm).data('sourceIndex')].name)[0]; }))
        .show().prependTo('.resultsMiddle');
    //apply first class to first element
    $('.sectionDiv:first').addClass('sectionDivFirst');

    if (!bSkipCookieSet)
        setCookieCategories();

    //IE8 bug http://dev.jqueryui.com/ticket/5773, sortable sticks checkbox state in ie8
    $('#categoriesDiv input:checkbox').each(function () { var context = [this, this.checked]; setTimeout(function () { context[0].checked = context[1]; }, 1); });
}

function _addCategoryDialog() {
    var buttons = {};
    buttons[saveText] = function () { $('#categoryAddDialog').submit(); };

    $('#categoryAddDialog').dialog({ modal: true, buttons: buttons }).find('input:first').focus();
}

//search method executed on autocomplete selection, enter click, click on magnifier glass, etc
function executeSearch() {
    var resultsDiv = $('#resultsDiv');
    //remove the 'term' data so clicking enter before callback returns wont display auto complete
    var val = getSearchText();

    //if search term has not changed
    if ($('#resultsDiv').data('search') == val)
        return;

    setResultsDivData(val);

    //only show the div if they are actually searching
    if (val.length < minSearchLength) {
        resultsDiv.hide();
        return;
    }

    //put a timer in each section
    for (var x = 0; x < sources.length; x++)
        if (sources[x].enabled) {
            var sectionDiv = $('#Results' + sources[x].name);
            $('.sectionResults', sectionDiv).html('<img alt="" src="/Images/ajax-loader.gif" />');
            $('.sectionArrow', sectionDiv).hide();
            $('.sectionHeader', sectionDiv).css('cursor', 'auto');
        }

    resultsDiv.show();

    //only track one of the medtango searches
    var searchTracked = false;

    //call the appropriate callback
    for (var x = 0; x < sources.length; x++) {
        if (sources[x].enabled) {
            var bTrackSearch = false;
            if (!searchTracked && sources[x].searchFormat == 'medtango')
                bTrackSearch = searchTracked = true;
            _executeSearch(x, 1, bTrackSearch);
        }
    }

    //track the search if all medtango calls disabled
    if (!searchTracked)
        trackSearch();
}