/*
 * Cool Search
 * 9/30/2011, Matthew Rohr
 *
 */

//Drop Down Styling : http://www.adamcoulombe.info/lab/jquery/select-box/
(function ($) {
    $.fn.extend({
        customSELECTStyle: function (options) {
            if (!$.browser.msie || ($.browser.msie && $.browser.version > 6)) {
                return this.each(function () {
                    var currentSelected = $(this).find(':selected');
                    $(this).after('<span class="searchFilterStyle"><span class="searchFilterStyleInner">' + currentSelected.text() + '</span></span>').css({ position: 'absolute', opacity: 0, fontSize: $(this).next().css('font-size') });
                    var selectBoxSpan = $(this).next();
                    $('.filterWrapper').removeClass("hide").addClass("show");
                    var selectBoxWidth = parseInt($(this).width()) - parseInt(selectBoxSpan.css('padding-left')) - parseInt(selectBoxSpan.css('padding-right'));
                    var selectBoxSpanInner = selectBoxSpan.find(':first-child');
                    selectBoxSpan.css({ display: 'inline-block' });
                    selectBoxSpanInner.css({ width: selectBoxWidth, display: 'inline-block' });
                    var selectBoxHeight = parseInt(selectBoxSpan.height()) + parseInt(selectBoxSpan.css('padding-top')) + parseInt(selectBoxSpan.css('padding-bottom'));
                    $(this).height(selectBoxHeight).change(function () {
                        // selectBoxSpanInner.text($(this).val()).parent().addClass('changed');   This was not ideal
                        selectBoxSpanInner.text($(this).find(':selected').text()).parent().addClass('changed');
                        // Thanks to Juarez Filho & PaddyMurphy
                    });
                });
            }

        }
    });
})(jQuery);


//Delay
var isOpenWindow = true;
var timingFrequWindow = 400; //msec
var myWindowInterval = 0;
function stop_WindowT() {
    myWindowInterval = clearInterval(myWindowInterval);
}
function start_WindowT() {
    isOpenWindow = false;
    myWindowInterval = setInterval("enable_Window()", timingFrequWindow);
}
function enable_Window() {
    isOpenWindow = true;
    stop_WindowT();
}


//var allowSearch = false; var allowSearch2 = false;
//var searchDelayInterval = 0;
//var timingFrequCheck = 1000; //sec
$(document).ready(function () {
    //=============
    //Filter if enabled
    if ($("#hd_filter").val() != null)
        $("#mainFilterDDL").val($("#hd_filter").val());//selected filter : MUST be before filter styling
    else $("#mainFilterDDL").val("-1");
    //Style drop down
    $('.searchFilterDDL').customSELECTStyle();

    //Set up for overwriting form submit if user selects a ajax quick search query and presses enter
    var allowStandardSubmit = true;
    $('#searchForm').submit(function() {
        if (allowStandardSubmit)return true;
        else return false;
    });

    //*********************************
    //Drop Down Selections
    $("#searchTextBox").keydown(function (e) {
        if ($("#hd_ajaxoptions").val() != null & $(".dynamicSearchPop").is(":visible")) {

            //=====================
            //Find current selected : Index starts at 0
            var currentIndex = -1; //default if none selected
            var newIndex = 0;
            var maxIndex = 0;
            $('.dynamicSearchPop ul li').each(function (index) {
                if ($(this).hasClass('selectedAjax')) currentIndex = index; //alert(index + ': ' + $(this).text());
                maxIndex = index;
            });

            //======================
            //Get the key that was pressed, up|down : Set new selected index
            var code = (e.keyCode ? e.keyCode : e.which);

            //ENTER : If this is a label search, send to new page
            if (e.keyCode == 13)
                if ($("#hd_ajaxoptions").val() == "5" || $("#hd_ajaxoptions").val() == "7") {
                    $('.dynamicSearchPop ul li').each(function (index) {
                        if ($(this).hasClass('selectedAjax')) {
                            allowStandardSubmit = false;
                            location.href = $(this).find('a').attr("href");
                        }
                    });
                }

            //DOWN : Make sure were not at the index limit
            if (e.keyCode == 40 & currentIndex != maxIndex & currentIndex != -1) newIndex = currentIndex + 1;
            if (currentIndex == maxIndex) newIndex = maxIndex; //endlimit

            //UP : Make sure were not at top limit
            if (e.keyCode == 38 & currentIndex != 0) newIndex = currentIndex - 1;

            //=====================
            //Go through list again, disable and reneable based what is currently selected and the new index
            if (code == 40 | code == 38) {
                $('.dynamicSearchPop ul li').each(function (index) {
                    if (index == currentIndex) $(this).removeClass('selectedAjax');
                    if (index == newIndex) {
                        $(this).addClass('selectedAjax');
                        $('#searchTextBox').val($(this).text());
                    }
                });
            }
        }
    })
    //Remove current selected, mouse over
    $(".dynamicSearchPop").hover(function (e) {
        $('.dynamicSearchPop ul li').each(function (index) {
            if ($(this).hasClass('selectedAjax')) $(this).removeClass('selectedAjax');
        });
    })

    //*********************************
    //Ajax Search Results

    //Search closure if Blured
    $("body").click(function(evt) {
        if ($("#hd_ajaxoptions").val() != null) {
            var target = evt.target;
            if (target.tagName != 'A' & target.tagName != 'SELECT' & target.tagName != 'INPUT') {
                $(".dynamicSearchPop").addClass("hide").removeClass("show");
            }
        }
    });

    var lastSearch = "";
    $("#searchTextBox").keyup(function (e) { //text box trigger
        //Prevent multiple spam by only allowing new searches through
        var currentSearch = $("#searchTextBox").val();
        if (($.trim(currentSearch)) != ($.trim(lastSearch)))
            doSearch(e);//Execute Possible Search
    })

    $("#mainFilterDDL").change(function (e) { //filter trigger
        doSearch(e);
    })


    function doSearch(e) {
        if ($("#hd_ajaxoptions").val() != null) {

            var filter = -1;
            if ($("#mainFilterDDL").val() != null)filter = $("#mainFilterDDL").val();

            //Call Search if > 3 char AND this is not an up and down key event
            var code = (e.keyCode ? e.keyCode : e.which);
            var query = $("#searchTextBox").val();
            lastSearch = query;
            if (query.length > 2 & code != 40 & code != 38 & isOpenWindow) {

                //Start window timer
                start_WindowT();

                $.ajax({
                    type: "GET", //GET or POST
                    url: "/service/ajaxsearch", //URL to call
                    data: "query=" + query + "&filter=" + filter,
                    success: handleData,
                    error: ajaxFailed
                });
            }
            //Hide if less than 4
            if (query.length < 3) $(".dynamicSearchPop").addClass("hide").removeClass("show");
        }

        function handleData(data, status) {
            if (data.length > 1) {// & data != "null") {
                $(".dynamicSearchPop").addClass("show").removeClass("hide");
                $("#searchULBox").html(data);
            } else $(".dynamicSearchPop").addClass("hide").removeClass("show");
        }

        function ajaxFailed(xmlRequest) {
            $(".dynamicSearchPop").addClass("hide").removeClass("show");
            //alert("Error\n\r\n\r" + xmlRequest.status + ' \n\r ' + xmlRequest.statusText + '\n\r' + xmlRequest.responseText);
        }
    }
});


//      clearInterval(searchDelayInterval); allowSearch2 = false; allowSearch = true;
//      searchDelayInterval = setInterval("EnableSearch()", timingFrequCheck);
//function sleep(milliseconds) {
//  var start = new Date().getTime();
//  for (var i = 0; i < 1e7; i++) {
//    if ((new Date().getTime() - start) > milliseconds){
//      break;
//    }
//  }
//}
