/**
*    Json key/value autocomplete for jQuery
*    Provides a transparent way to have key/value autocomplete
*    Copyright (C) 2008 Ziadin Givan www.CodeAssembly.com
*
*    This program is free software: you can redistribute it and/or modify
*    it under the terms of the GNU Lesser General Public License as published by
*    the Free Software Foundation, either version 3 of the License, or
*    (at your option) any later version.
*
*    This program is distributed in the hope that it will be useful,
*    but WITHOUT ANY WARRANTY; without even the implied warranty of
*    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*    GNU General Public License for more details.
*
*    You should have received a copy of the GNU Lesser General Public License
*    along with this program.  If not, see http://www.gnu.org/licenses/
*
*    Examples
*    $("input#example").autocomplete("autocomplete.php");//using default parameters
*    $("input#example").autocomplete("autocomplete.php",{minChars:3,timeout:3000,validSelection:false,parameters:{'myparam':'myvalue'},before : function(input,text) {},after : function(input,text) {}});
*    minChars = Minimum characters the input must have for the ajax request to be made
*    timeOut = Number of miliseconds passed after user entered text to make the ajax request
*    validSelection = If set to true then will invalidate (set to empty) the value field if the text is not selected (or modified) from the list of items.
*    parameters = Custom parameters to be passed
*    after, before = a function that will be caled before/after the ajax request
*/
jQuery.fn.autocomplete = function(url, settings , default_value)
{
    return this.each( function()//do it for each matched element
    {
        //this is the original input
        var textInput = $(this);
        //create a new hidden input that will be used for holding the return value when posting the form, then swap names with the original input
      if (textInput.attr('name').split('_')[1] != 'text')
        textInput.after('<input type="hidden" name="' + textInput.attr("name") + '" value="' + default_value  + '"/>').attr("name", textInput.attr("name") + "_text");
      else if (textInput.data('events'))
	textInput.data('events').keydown = undefined;
        var valueInput = $(this).next();
        //create the ul that will hold the text and values
        valueInput.after('<ul class="autocomplete" style="z-index: 100"></ul>');
        var pos = $(textInput).position();
        var list = valueInput.next().css({top: $(textInput).position().top + $(textInput).outerHeight()-3, left: $(textInput).position().left, width: textInput.width()+7});
        var oldText = '';
        var typingTimeout;
        var size = 0;
        var selected = 0;
        var outData = null;
        settings = jQuery.extend(//provide default settings
        {
            minChars : 3,
            timeout: 100,
            after : null,
            before : null,
  	    callback: null, // called with a sys_path, after selecting a city
 	    validator: /.*/,
            validSelection : true,
            parameters : {'inputName' : valueInput.attr('name'), 'inputId' : textInput.attr('id')}
        } , settings);

      function displayWarning() {
	var name = $('#'+textInput.attr('id')+'_label').text().split(':')[0].toLowerCase();
	list.html('<li id="lp">'
		  + '<strong>We are sorry</strong><br/>The '+ name +' you\'ve typed has not been recognized. Please check spelling.'
		  +'</li>');
      }

        function getData(text)
        {
	  if (!settings.validator.test(text) && text) {
	    displayWarning();
            list.show();
	    return;
	  }
            window.clearInterval(typingTimeout);
            if ( text.length < 3 )
            {
                clear()
            }
            if (/*text != oldText && */(settings.minChars != null && text.length >= settings.minChars))
            {
                clear();
                if (settings.before)
                {
                    settings.before(textInput,text);
                }
                textInput.addClass('autocomplete-loading');
                settings.parameters.text = text;
                $.getJSON(url,settings.parameters,function(data)
                {
                    outData = data;
                    var items = '';
                    if(data.err_happened != "true"){
                        if (data.completions.length > 0 || settings.callback){
                            size = data.completions.length;
                            for (i = 0; i < size; i++)//iterate over all options
                            {
                                //items += '<li id="lp' + i + '">' + data.completions[i][1] + '</li>';
                                k =[];
                                k = data.completions[i][1].split('');
                                var q=[];
                                q[0]="<strong>";
                                for(var j=0; j<text.length; j++){
                                  q[j+1]=k[j];
                                }
                                for(var w=text.length+1; w<k.length+2; w++){
                                    if(w == text.length+1){
                                        q[w]="</strong>";
                                    }else{
                                        q[w]=k[w-2];
                                    }
                                }
                                var suggestionText = q.join("");
                                items += '<li id="lp' + i + '" class="'+data.completions[i][0]+'">' + suggestionText + '</li>';
                            }
                          list.html(items);
                          //on mouse hover over elements set selected class and on click set the selected value and close list
                          list.show();
			  hideSelectsForIE6(list);
                          list.children().mouseover(
                              function(){
                                  $(this).addClass("selected");
                              });
                          list.children().mouseout(
                              function(){
                                  $(this).removeClass("selected");
                              });
			  list.children().click(
			    function(){
			      var completion = data.completions[parseInt($(this).attr("id").replace("lp",""))];
			      var is_ambiguous = completion[2];
			      var sys_path = completion[0];
			      if (is_ambiguous === 'false') {
				textInput.val( $(this).text() );

                                valueInput.val( sys_path );
                                clear();
				textInput.focus();
			      } else {
				textInput.val( $(this).text() );
                                valueInput.val( '' );
                                clear();
				textInput.focus();
			      }
			      if (settings.callback)
				settings.callback(sys_path, completion[1]);
                            });
			  if (data.completions.length == 1)
			    list.children().click();
			  else if (data.completions.length == 0 && settings.callback)
			    displayWarning();
                        if (settings.after)
                            {
                                settings.after(textInput,text);
                            }
                        }/*else{
                            alert("We are very sorry.\nThis location has not been recognized.\nPlease use different one.")
                        }*/
                        textInput.removeClass('autocomplete-loading');
                    }else{
                        alert(data.msg)
                    }
                });
                oldText = text;
            }
        }

        function clear()
        {
            list.hide();
            size = 0;
            selected = -1;
			hideSelectsForIE6(list);
        }

        textInput.keydown(function(e)
        {
            window.clearInterval(typingTimeout);
            if(e.which == 27)//escape
            {
                clear();
            } /*else if (e.which == 46 || e.which == 8)//delete and backspace
            {
                clear();
                //invalidate previous selection
                if (settings.validSelection) valueInput.val('');
            }*/
			else if(e.which == 9)
			{
				clear();
			}
            /*else if(e.which == 13)//enter
            {
                if ( list.css("display") == "none")//if the list is not visible then make a new request, otherwise hide the list
                {
                    getData(textInput.val());
                } else
                {
                    clear();
                }
                e.preventDefault();
                return false;
            }*/
            /*else if((e.which == 40 || e.which == 9 || e.which == 38) && textInput.val()!="")*/ //move up, down
            else if((e.which == 40 || e.which == 38) && textInput.val()!="")//move up, down
            {
              switch(e.which)
              {
				case 40:
                	selected = selected >= size - 1 ? 0 : selected + 1;
                    break;
                case 38:
                  	selected = selected <= 0 ? size - 1 : selected - 1;
                  	break;
                default: break;
              }
              //set selected item and input values
              var completion = outData.completions[parseInt(list.children().eq(selected).attr('id').replace("lp", ""))];
              if (completion[2] === 'false') {
			  		textInput.val(list.children().removeClass('selected').eq(selected).addClass('selected').text());
			  		valueInput.val(completion[0]);
			  }else{
			  		textInput.val(list.children().removeClass('selected').eq(selected).addClass('selected').text());
			  		valueInput.val('');
			  }
              if(settings.callback) {
                  settings.callback(completion[0], completion[1]);
              }

            }else if(e.which==13 && textInput.val()!="" && !settings.callback){
				switch(e.which)
				{
					case 13:
						$("#search_form").submit();
						break;
				}
			}
	  else
            {
                //invalidate previous selection
//                valueInput.value(textInput.val());
				if (settings.validSelection) valueInput.val('');
                typingTimeout = window.setTimeout(function() { getData(textInput.val()) },settings.timeout);
            }
        });
    });
};

/*
 * hideSelectsForIE6
 * function hide selects located under autocompletition list
 */
var _selectsList =[];
function hideSelectsForIE6(e){
	if($.browser.msie && $.browser.version>=6.0 && $.browser.version<7.0){
		var _listDimension = [];
		if($(e).css("display")!="none"){
			_listDimension.push($(e).offsetParent().position().left + $(e).position().left);
			_listDimension.push($(e).offsetParent().position().left + $(e).position().left + $(e).width());
			_listDimension.push($(e).offsetParent().position().top + $(e).position().top);
			_listDimension.push($(e).offsetParent().position().top + $(e).position().top + $(e).height());
			$("select").each(function(){
				if((parseInt(_listDimension[2],10) <= parseInt($(this).position().top,10) &&
				parseInt($(this).position().top,10)<= parseInt(_listDimension[3],10) &&
				parseInt(_listDimension[0],10) <= parseInt($(this).position().left,10) &&
				parseInt($(this).position().left,10) <= parseInt(_listDimension[1],10)) ||
				(parseInt(_listDimension[2],10) <= parseInt($(this).position().top,10)+$(this).height() &&
				parseInt($(this).position().top,10)+$(this).height()<= parseInt(_listDimension[3],10) &&
				parseInt(_listDimension[0],10) <= parseInt($(this).position().left,10)+$(this).width() &&
				parseInt($(this).position().left,10)+$(this).width() <= parseInt(_listDimension[1],10))){
					_selectsList.push($(this).attr("id"));
					$(this).css("visibility","hidden");
				}
			})
		}else{
			for(var i=0;i<_selectsList.length; i++){
				$("#"+_selectsList[i]).css("visibility","visible");
			}
		}
	}
}

/*
 * end hideSelectsForIE6
 */

function hideDefaultInputText(e){
    var oldText = null;
    var focusNo = null;
    $(e).focus(function(){
        if(focusNo==null){
            focusNo+=1;
            oldText = $(this).val();
            $(this).val("");
        }else{
            if($(this).val()==oldText){
                $(this).val("");
            }
        }
    })
    $(e).blur(function(){
        if($(this).val()==""){
            $(this).val(oldText);
        }
    })
}

function checkValueAndSubmit(){
    if($("#query").val() == searchForText){ //searchForText is defined in base.html template
        $("#query").val("");
    }
    if($("#near_to").val() == areaText){ //areaText is defined in base.html template
        $("#near_to").val("");
    }
    $("#search_form").submit();
}
