﻿if (typeof Pagen == "undefined" || !Pagen) {
    var Pagen = {};
}
var searchbox;

FutureLab.addNamespace(Pagen,'Pagen.Web.UI');

Pagen.Web.UI.SearchBox = Class.create({

    initialize: function(input,results) {
        var me = this;
        this.cur = -1;   
        this.textbox = $(input);
        this.layer = $(results);
        this.form = $('header-search-form');
        this.submit = $('header-search-btn');
        
        this.form.onsubmit = function(e) {
            return false;
        };
        
        this.submit.onclick = function(e) {
            if (me.cur==-1) {
                me.googleSearch();
            }
            return false;
        };
                     
        this.textbox.onkeyup = function (e) {        
            if (!e) {
                e = window.event;
            }
            me.handleKeyUp(e);
            if (e.keyCode==13) {
                return false;
            }
        };
        
        this.textbox.onkeydown = function (e) {    
            if (!e) {
                e = window.event;
            }
            me.handleKeyDown(e);
            
            if (e.keyCode==13) {
                if (me.cur==-1) {
                    me.googleSearch();
                }
                return false;
            }
        };
        
        this.textbox.onblur = function () {
            setTimeout(
                function() {
                   me.hideSuggestions();
                   me.showTextWatermark();
                },250);
        };
        this.textbox.onfocus = function () {
            me.hideTextWatermark();
            me.hideLanguageChange();
        };
        this.textbox.onclick = function () {
            me.hideTextWatermark();
        };
    },
    
    nextSuggestion : function () {
        var cSuggestionNodes = this.getSuggestionNodes(); //this.layer.childNodes; 
        if (cSuggestionNodes.length > 0 && this.cur < cSuggestionNodes.length-1) {
            var oNode = cSuggestionNodes[++this.cur];
            this.highlightSuggestion(oNode);
        }
    },
    
    previousSuggestion : function () {
        var cSuggestionNodes = this.getSuggestionNodes(); 
        if (cSuggestionNodes.length > 0 && this.cur > 0) {
            var oNode = cSuggestionNodes[--this.cur];
            this.highlightSuggestion(oNode);
        }
    },
    
    getSuggestionNodes : function() {
        return $$('div.header-search-results-result');
    },
    
    hideSuggestions : function () {

        var me = this;
        if (!popup.popIsActive) {
            $$('select').each( function(node) { node.style.visibility = 'visible' });
            $$('object', 'embed').each( function(node) { node.style.display = '' });        
            $$('.flash_alternate').each( function(node) { node.style.display='none'});        
        }
        setTimeout(
            function() {
                me.cur = -1;                 
                me.layer.style.display='none';
                me.layer.innerHTML='';
            },250);
    },

    highlightSuggestion : function (currentNode) {    
        $(currentNode).addClassName('selected');
        $(currentNode).siblings().each( 
            function(item){ item.removeClassName('selected'); 
        });
    },
    
    hideTextWatermark : function() {
        this.textbox.value = '';
    },
    
    showTextWatermark : function() {
        this.textbox.value = this.textbox.defaultValue;
    },

    mouseOverSuggestion : function(currentNode) {
        var nodes = this.getSuggestionNodes();    
        this.cur = nodes.indexOf(currentNode);
        this.highlightSuggestion(currentNode);
    },

    mouseOutSuggestion : function(currentNode) {
        this.cur=-1;    
        $(currentNode).siblings().each( 
            function(item){ item.removeClassName('selected'); 
        }); 
    }, 

    handleKeyDown : function (e) {
        switch(e.keyCode) {
            case 38: //up arrow
                this.previousSuggestion();
                break;
            case 40: //down arrow 
                this.nextSuggestion();
                break;
            case 13: //enter
                this.loadItem();
                this.hideSuggestions();
                break;
        }
    },

    handleKeyUp : function (e) {
        var iKeyCode = e.keyCode;
        //for backspace (8) and delete (46), shows suggestions without typeahead
        if (iKeyCode == 8 || iKeyCode == 46) {
            this.search();
        //make sure not to interfere with non-character keys
        } else if (iKeyCode < 32 || (iKeyCode >= 33 && iKeyCode < 46) || (iKeyCode >= 112 && iKeyCode <= 123)) {
            //ignore
        } else {
            this.cur = -1;
            this.search();
        }
    },

    search : function() {

        var me = this;
           
        var succeeded = function(result) {
            
            $$('select').each( function(node) { node.style.visibility = 'hidden' });
            $$('object', 'embed').each( function(node) { node.style.display = 'none' });        
            $$('.flash_alternate').each( function(node) { node.style.display='block'});
        
            me.layer.innerHTML = result;
            me.layer.style.display='block';
            //hook up mouse events on the suggested items.
            var nodes = me.getSuggestionNodes();

            for (var i=0; i < nodes.length; i++) {
                nodes[i].onmouseover = function() { me.mouseOverSuggestion(this); };
                nodes[i].onmouseout = function() { me.mouseOutSuggestion(this); };
                nodes[i].onclick = function() { me.loadItem(); return false; };
                
                var a = nodes[i].firstDescendant();
                a.onclick = function() { alert('den här ska man inte klicka på!'); return false; };
            }
        }    
        var failure = function(result) { alert('Search : Failure : ?'); }
        
        if (this.textbox.value.length > 0) {
            API.Web.UI.Client.Service.Search.RenderSearchResult(this.textbox.value, succeeded, failure);
        } else {
           me.layer.innerHTML = '';
        }
    },
    
    googleSearch: function() {
        var url = this.form.action;
        var q = this.textbox.value;
        q = this.urlEncode(q);
        document.location.href=url+'?q='+q;
    },

    loadItem : function() {

        var nodes = this.getSuggestionNodes();
        if (this.cur>-1) {        
            //locate url-payload in the dummy anchor.
            var a = nodes[this.cur].firstDescendant(); 
            if (a.rel && a.rel.startsWith('poplink')) {
                if(popup) {
                    popup.display(a.href);

                }
            } else {            
                document.location.href = a.href;
            }
        }
    },
    
    urlEncode : function(str) {
        var ret = str;
        ret = ret.toString();
        ret = encodeURIComponent(ret);
        ret = ret.replace(/%20/g, '+');     
        return ret;
    },
    
    displayLanguageChange : function() {
        me = this;
        if ($('language-change').style.display=='') {
            $('language-change').style.display='none';
            $('language-btn').removeClassName('selected');
        } else {
            $('language-change').style.display='';
            $('language-btn').addClassName('selected');
            
            setTimeout( function() {
                Event.observe(document.body,'click', function() {
                    setTimeout( function() { 
                        me.hideLanguageChange();
                    }, 200);
                });
            }, 200);
        }
    },
    
    hideLanguageChange : function() {
        Event.stopObserving(document.body,'click');
        $('language-change').style.display='none';
        $('language-btn').removeClassName('selected');
    }


});

Event.observe(window, 'load', function() {  
    searchbox = new Pagen.Web.UI.SearchBox('searchbox_input','header-search-results');
}); 
