/* -*- js2 -*-
 *
 * $Id$
 */

function SearchHintControl(base_input,hint_frame,hint_body,admin_mode) {

    var hint_active = false;
    var last_state = '';
    var hint_selected = -1;
    var hints_total = 0;
    var hint_locations = [];
	var selectSize = null;
    var redirectTo = null;
    var $ = jQuery;
    var set_position = !admin_mode; // set top and left somehow (M&M only for now - set true there)

    function setHintVisible(state) {
        if ((state==true) || (state==undefined)) {
            if (set_position == true) {
                var input = jQuery(base_input);
                var top = input.offset().top
                    + input.height() 
                    + parseFloat(input.css('padding-top'))
                    + parseFloat(input.css('padding-bottom'))
                    + 3; // borders, odstęp and stuff
                var left = input.position().left + 8; // bo tak
                
                jQuery(hint_frame).css({
                                           'display':'block',
                                           'top': top,
                                           'left': left });
            }
            else {
                jQuery(hint_frame).css('display', 'block');
            }
        }
        else {
            jQuery(hint_frame).css('display','none');
        }
    }

    function onSubmit(ev) {
        if (redirectTo) {
            window.location.href = redirectTo;
            return false;
        }
    }

    function onKeyUp(ev) {

        if ((ev.which != 38 ) && (ev.which != 40)) {
            var search_for = $(base_input).val();
            if (search_for!=last_state) {
                var data = {
                    'component': 'cSearchBox',
                    'method': 'searchHint',
                    'adminMode': admin_mode,
                    'searchFor': search_for

                };
                if (search_for.length>2) {
                    $.getJSON('/_json/',data,onSearchHintResponse);
                }
                else {
                    hints_total=0;
                    hint_locations = [];
                    hint_selected = -1;
                    setHintVisible(false);
                }
                last_state = search_for;
            }
            ev.stopPropagation();
        }
    }

    function onKeyDown(ev) {
        var new_hint = -1;

        if (ev.which == 13 && admin_mode && hint_selected == -1) {
            onHintSelected({value:ev.target.value});
            ev.cancelBubble = true;
            return false;
        }

        if (hint_locations.length > 0) {
            if (ev.which == 38)
                new_hint = (hint_selected>0) ? (hint_selected-1) : (hint_locations.length-1);
            if (ev.which == 40)
                new_hint = (hint_selected == (hint_locations.length-1)) ? 0 : (hint_selected+1);
            if (ev.which == 13) { // if ENTER was pressed...
                if (hint_selected > hint_locations.length) {
                    redirectTo = jQuery('#searchbox_hint_box div[id$=search_hint_line_'+hint_selected+'] a').attr('href');
                    window.location.href = redirectTo;
                    ev.cancelBubble = true; // i tried
                    return false;           // really hard
                }
                else if (admin_mode) {
                    onHintSelected({value:ev.target.value, product_id: hint_locations[hint_selected].product_id});
                    ev.cancelBubble = true; // i tried
                    return false;           // really hard
                }
                return true;
            }
            else if (ev.which == 13) { // ...and if not, maybe it was...?
                throw 'This line should have never been executed, congratulations. You can claim your reward at team@greentech.pl';
/*                ev.cancelBubble = true;
                $(base_input+'_search_hint_line_'+hint_selected).click();
                return false;*/
            }
            if (new_hint>=0) {
                onHintHighlight(new_hint);
                if (!admin_mode) {
                    $(base_input).val(hint_locations[new_hint]);
                } else {
                    $(base_input).val(hint_locations[new_hint].value);
                }
            }
        }
        ev.cancelBubble = true;
    }

    function setHintInvisible() {
        setHintVisible(false);
    }

    function onBlur(ev) {
        setTimeout(setHintInvisible,200);
        hint_active = false;
    }

    function onFocus(ev) {
        hint_active = true;
        last_state = $(base_input).val();
    }

    function onSearchHintResponse(response) {
		var date = new Date();
        var linenr = 0;
        if (hint_active) {
            hints_total = (response.products ? response.products.length : 0) + (response.sections ? response.sections.length : 0);
            hint_locations = response.products;
            hint_selected = -1;
            var htmlbody = '';

            if (response.products) {
                if (!admin_mode) {
                    htmlbody += '<div class="search_hint_header">' + _("Products:") + '</div>';
                }
                for (i in response.products) {
                    var name = (admin_mode) ? response.products[i].product_id + ': ' + response.products[i].value : response.products[i];
                    htmlbody += '<div class="search_hint_line search_hint_line_' + (linenr % 2 == 0 ? 'odd' : 'even')
                        + '" id="'+base_input.substring(1)+'_search_hint_line_'+linenr
                        +'"><a href="#">'+name+'</a></div>\n';
                    linenr++;
                }
            }
            if (!admin_mode) {
                if (response.sections) {
                    htmlbody += '<div class="search_hint_header">' + _("Sections:") + '</div>';
                    for (i in response.sections) {
                        htmlbody += '<div class="search_hint_line search_hint_line_' + (linenr % 2 == 0 ? 'odd' : 'even')
                            + '" id="'+base_input.substring(1)+'_search_hint_line_'+linenr
                            +'"><a href="'+response.sections[i].url+'">'+response.sections[i].title+'</a></div>\n';
                        linenr++;
                    }
                }
            }


            $(hint_body).html(htmlbody);
            setHintVisible(true);
            for (var line = 0; line < linenr; line++) {
                var clickAction = function(ev) {
                    onHintSelected(arguments.callee.phrase,ev);
                    return false;
                };
                clickAction.phrase = response.products[line];

                var mouseOverAction = function(ev) {
                    onHintHighlight(arguments.callee.line,ev);
                };
                mouseOverAction.line = parseInt(line);

                if (line < response.products.length) {
                    // click action only for products
                    $(base_input+'_search_hint_line_'+line).click(clickAction);
                }
                $(base_input+'_search_hint_line_'+line).mouseover(mouseOverAction);
            }
            if (response.length==0) {
                setHintVisible(false);
            }
            $(hint_frame).css('height','auto');
//            $(hint_frame).width(jQuery(hint_body).width()+20);
        }
    }

    function onHintHighlight(linenr) {
        if (hint_selected>=0) {
            jQuery(base_input+'_search_hint_line_'+hint_selected).removeClass("search_hint_highlight");
        }
        hint_selected=linenr;
        if (linenr>=0) {
            jQuery(base_input+'_search_hint_line_'+linenr).addClass("search_hint_highlight");
        }
    }

    function onHintSelected(hintbody,ev) {
        if (admin_mode) {
            if (orderModifier) {
                orderModifier.itemSelected(hintbody);
            }
        } else {
            $(base_input).val(hintbody);
            $('#searchbox_submit').click();
        }
        return false;
    }

    $(base_input).keyup(onKeyUp);
    $(base_input).keydown(onKeyDown);
    $(base_input).blur(onBlur);
    $(base_input).focus(onFocus);
    $(base_input).attr('autocomplete','off');
    $(base_input).closest('form').submit(onSubmit);
}

jQuery(document).ready(function () {
                           if (jQuery('#admin-panel-container').size() > 0) {
                               SearchHintControl('#newProductName','#new_hint_box','#new_hint_body', true);
                           } else {
                               SearchHintControl('#searchbox_string','#searchbox_hint_box','#searchbox_hint_body', false);
                           }
});
