// JavaScript Document
(function($) {

$.fn.tokenInput = function (url, options) {
    var settings = $.extend({
        url: url,
        prePopulate: "",
        hintText: "Type in a search term",
        noResultsText: "No results",
        searchingText: "Searching...",
        searchDelay: 300
    }, options);

    settings.classes = $.extend({
        tokenList: "token-input-list",
        token: "token-input-token",
        tokenDelete: "token-input-delete-token",
        selectedToken: "token-input-selected-token",
        highlightedToken: "token-input-highlighted-token",
        dropdown: "token-input-dropdown",
        dropdownItem: "token-input-dropdown-item",
        dropdownItem2: "token-input-dropdown-item2",
        selectedDropdownItem: "token-input-selected-dropdown-item",
        inputToken: "token-input-input-token"
    }, options.classes);

    return this.each(function () {
        var list = new $.TokenList(this, settings);
    });
};

$.TokenList = function (input, settings) {
    //
    // Variables
    //

    // Input box position "enum"
    var POSITION = {
        BEFORE: 0,
        AFTER: 1,
        END: 2
    };
    
    // Keys "enum"
    var KEY = {
        BACKSPACE: 8,
        RETURN: 13,
        LEFT: 37,
        UP: 38,
        RIGHT: 39,
        DOWN: 40
    };
    
    // Save the tokens
    var saved_tokens = [];
    
    // Basic cache to save on db hits
    var cache = new $.TokenList.Cache();

    // Keep track of the timeout
    var timeout;
    
    // Create a new text input an attach keyup events
    var input_box = $("<input type=\"text\" value='Type the name of a Connection(s)' style='color:#999999;'>")
        .css({
            outline: "none"
        })
        .focus(function () {
            //show_dropdown_hint();
			 if($(this).val('Type the name of a Connection(s)')) {
				 $(this).val('');
			 }
			 $(this).attr('style','color:#000000');
        })
        .blur(function () {
            if(!selected_dropdown_item) {
                hide_dropdown();
            }
			if($(this).val('')) {
				 $(this).val('Type the name of a Connection(s)');
				 $(this).attr('style','color:#999999');
			}
        })
        .keydown(function (event) {
            var previous_token;
            var next_token;

            switch(event.keyCode) {
                case KEY.LEFT:
                case KEY.RIGHT:
                case KEY.UP:
                case KEY.DOWN:
                    if(!$(this).val()) {
                        previous_token = input_token.prev();
                        next_token = input_token.next();
                        
                        if((previous_token.length && previous_token.get(0) === selected_token) || (next_token.length && next_token.get(0) === selected_token)) {
                            // Check if there is a previous/next token and it is selected
                            if(event.keyCode == KEY.LEFT || event.keyCode == KEY.UP) {
                                deselect_token($(selected_token), POSITION.BEFORE);
                            } else {
                                deselect_token($(selected_token), POSITION.AFTER);
                            }
                        } else if((event.keyCode == KEY.LEFT || event.keyCode == KEY.UP) && previous_token.length) {
                            // We are moving left, select the previous token if it exists
                            select_token($(previous_token.get(0)));
                        } else if((event.keyCode == KEY.RIGHT || event.keyCode == KEY.DOWN) && next_token.length) {
                            // We are moving right, select the next token if it exists
                            select_token($(next_token.get(0)));
                        }
                    } else {
                        var dropdown_item = null;

                        if(event.keyCode == KEY.DOWN || event.keyCode == KEY.RIGHT) {
                            dropdown_item = $(selected_dropdown_item).next();
                        } else { 
                            dropdown_item = $(selected_dropdown_item).prev();                
                        }

                        if(dropdown_item.length) {
                            select_dropdown_item(dropdown_item);
                        }
                        return false;
                    }
                    break;
                
                case KEY.BACKSPACE:
                    previous_token = input_token.prev();

                    if(!$(this).val().length) {
                        if(selected_token) {
                            delete_token($(selected_token));
                        } else if(previous_token.length) {
                            select_token($(previous_token.get(0)));
                        }
                        
                        return false;
                    } else if($(this).val().length == 1) {
                        hide_dropdown();
                    } else {
                        show_dropdown_searching();
                        do_search(1);
                    }
                    break;

                case KEY.RETURN:
                    if(selected_dropdown_item) {
                        add_token($(selected_dropdown_item));
                        return false;
                    }
                    break;

                default:
                    if(is_printable_character(event.keyCode)) {
                        show_dropdown_searching();
                        clearTimeout(timeout);
    				    timeout = setTimeout(do_search, settings.searchDelay);
				    }
				    
                    break;
            }
        });

    // Keep a reference to the original input box
    var hidden_input = $(input)
                           .hide()
                           .focus(function () {
                               input_box.focus();
                           })
                           .blur(function () {
                               input_box.blur();
                           })
                           .val("");

    // Keep a reference to the selected token and dropdown item
    var selected_token = null;
    var selected_dropdown_item = null;
    
    // The list to store the token items in
    var token_list = $("<ul />")
        .addClass(settings.classes.tokenList)
        .insertAfter(hidden_input)
        .click(function (event) {
            var li = get_element_from_event(event, "li");
            if(li && li.get(0) != input_token.get(0)) {
                toggle_select_token(li);
                return false;
            } else {
                input_box.focus();
            
                if(selected_token) {
                    deselect_token($(selected_token), POSITION.END);
                }
            }
        })
        .mouseover(function (event) {
            var li = get_element_from_event(event, "li");
            if(li && selected_token !== this) {
                li.addClass(settings.classes.highlightedToken);
            }
        })
        .mouseout(function (event) {
            var li = get_element_from_event(event, "li");
            if(li && selected_token !== this) {
                li.removeClass(settings.classes.highlightedToken);
            }
        })
        .mousedown(function (event) {
            // Stop user selecting text on tokens
            var li = get_element_from_event(event, "li");
            if(li){
                return false;
            }
        });


    // The list to store the dropdown items in
    var dropdown = $("<div>")
        .addClass(settings.classes.dropdown)
        .insertAfter(token_list)
        .hide();
    
    // The token holding the input box
    var input_token = $("<li />")
        .addClass(settings.classes.inputToken)
        .appendTo(token_list)
        .append(input_box);
        
    init_list();
    
    //
    // Functions
    //

    function is_printable_character(keycode) {
        if((keycode >= 48 && keycode <= 90) ||      // 0-1a-z
           (keycode >= 96 && keycode <= 111) ||     // numpad 0-9 + - / * .
           (keycode >= 186 && keycode <= 192) ||    // ; = , - . / ^
           (keycode >= 219 && keycode <= 222)       // ( \ ) '
          ) {
              return true;
          } else {
              return false;
          }
    }

    // Get an element of a particular type from an event (click/mouseover etc)
    function get_element_from_event (event, element_type) {
        var target = $(event.target);
        var element = null;

        if(target.is(element_type)) {
            element = target;
        } else if(target.parent(element_type).length) {
            element = target.parent(element_type+":first");
        }

        return element;
    }
    
    // Add a token to the token list
    function add_token (item) {		
        var li_data = $.data(item.get(0), "tokeninput");
		var exist_val = hidden_input.val().split(",");
		//alert(exist_val.join().indexOf(li_data.id));
		if(exist_val.join().indexOf(li_data.id) > -1) 
			return;
        var this_token = $("<li><p>"+ li_data.name +"</p> </li>")
            .addClass(settings.classes.token)
            .insertBefore(input_token);
             
        $("<span>x</span>")
            .addClass(settings.classes.tokenDelete)
            .appendTo(this_token)
            .click(function () {
                delete_token($(this).parent());
                return false;
            });
        

		
//		alert(settings.url);
        $.data(this_token.get(0), "tokeninput", {"id": li_data.id, "name": li_data.name});
		
		/* START - Checked all checkboxes of same user id & profile id - Access Rights 2.0 CR - ZV */
		if(settings.url.substr(settings.url.lastIndexOf("/")+1) == 'getCustomConnection') {
			if($j("#chkPublic").attr('checked')) {
				checkUncheckEveryoneAllContacts(true,li_data.id,input.form.id);
			}
			if($j("#chkAllCon").attr('checked')) {
				checkUncheckContacts(true,li_data.id,input.form.id);
			}			
		} else {
			if(settings.url.substr(settings.url.lastIndexOf("/")+1) == 'friendList') {
				checkUncheckContacts(true,li_data.id);
			}else {
				checkUncheckNonSohoContacts(true,li_data.id);
			}
		}
		/* END - Checked all checkboxes of same user id & profile id - Access Rights 2.0 CR - ZV */
		
        // Clear input box and make sure it keeps focus
        input_box
            .val("")
            .focus();        
        
        // Don't show the help dropdown, they've got the idea
        hide_dropdown();

        // Save this token id
        var id_string = li_data.id + ","
        hidden_input.val(hidden_input.val() + id_string);
    }
    
	//pre-populate list if items exist
    function init_list () {
        li_data = settings.prePopulate;
        if(li_data.length) {
            for(var i in li_data) {

            var this_token = $("<li><p>"+li_data[i].name+"</p> </li>")
                .addClass(settings.classes.token)
                .insertBefore(input_token);
                 
            $("<span>x</span>")
                .addClass(settings.classes.tokenDelete)
                .appendTo(this_token)
                .click(function () {
                    delete_token($(this).parent());
                    return false;
                });
            
            $.data(this_token.get(0), "tokeninput", {"id": li_data[i].id, "name": li_data[i].name});

            // Clear input box and make sure it keeps focus
            input_box
                .val("")
                .focus();        
            
            // Don't show the help dropdown, they've got the idea
            hide_dropdown();

            // Save this token id
            var id_string = li_data[i].id + ","
            hidden_input.val(hidden_input.val() + id_string);
            }
        }
    }

    // Select a token in the token list
    function select_token (token) {
        token.addClass(settings.classes.selectedToken);
        selected_token = token.get(0);

        // Hide input box
        input_box.val("");
        
        // Hide dropdown if it is visible (eg if we clicked to select token)
        hide_dropdown();
    }

    // Deselect a token in the token list
    function deselect_token (token, position) {
        token.removeClass(settings.classes.selectedToken);
        selected_token = null;

        if(position == POSITION.BEFORE) {
            input_token.insertBefore(token);
        } else if(position == POSITION.AFTER) {
            input_token.insertAfter(token);
        } else {
            input_token.appendTo(token_list);
        }

        // Show the input box and give it focus again
        input_box.focus();
    }
    
    // Toggle selection of a token in the token list
    function toggle_select_token (token) {
        if(selected_token == token.get(0)) {
            deselect_token(token, POSITION.END);
        } else {
            if(selected_token) {
                deselect_token($(selected_token), POSITION.END);
            }
            select_token(token);
        }
    }
    
    // Delete a token from the token list
    function delete_token (token) {
        // Remove the id from the saved list
        var token_data = $.data(token.get(0), "tokeninput");
        //saved_tokens.splice($.inArray(saved_tokens, token_data.id), 1);

        // Delete the token
        token.remove();
        selected_token = null;

        // Show the input box and give it focus again
        input_box.focus();

        // Delete this token's id from hidden input
        var str = hidden_input.val()
        var start = str.indexOf(token_data.id+",");
        var end = str.indexOf(",", start) + 1;

        if(end >= str.length) {
            hidden_input.val(str.slice(0, start));
        } else {
            hidden_input.val(str.slice(0, start) + str.slice(end, str.length));
        }
		
		/* START - Checked all checkboxes of same user id & profile id - Access Rights 2.0 CR - ZV */
		if(settings.url.substr(settings.url.lastIndexOf("/")+1) == 'getCustomConnection') {
			if($j("#chkPublic").attr('checked')) {
				checkUncheckEveryoneAllContacts(false,token_data.id,input.form.id);
			}
			if($j("#chkAllCon").attr('checked')) {
				checkUncheckContacts(false,token_data.id,input.form.id);
			}			
		} else {
			if(settings.url.substr(settings.url.lastIndexOf("/")+1) == 'friendList') {
				checkUncheckContacts(false,token_data.id);
			} else {			
				checkUncheckNonSohoContacts(false,token_data.id);
			}
		}
		/* END - Checked all checkboxes of same user id & profile id - Access Rights 2.0 CR - ZV */
    }

    // Hide and clear the results dropdown
    function hide_dropdown () {
        dropdown.hide().empty();
        selected_dropdown_item = null;
    }
    
    function show_dropdown_searching () {
        dropdown
            .html("<p>"+settings.searchingText+"</p>")
            .show();
    }
    
    function show_dropdown_hint () {
        dropdown
            .html("<p>"+settings.hintText+"</p>")
            .show();
    }

    // Highlight the query part of the search term
	function highlight_term(value, term) {
		return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<em>$1</em>");
	}
	
	// Populate the results dropdown with some results
    function populate_dropdown (query, results) {

		/* START - Unchecked all checkboxes of connections first time when user type in smart type input box - ZV */
		/*if(hidden_input.val().length == 0) {
			if(accessRightsAction != "edit") {
				checkUncheckAllConnection(false,input.form.id,false);			
			}
		}*/
		/* END - Unchecked all checkboxes of connections first time when user type in smart type input box - ZV */
        if(results.length) {
            dropdown.empty();
            var dropdown_ul = $("<ul>")
                .appendTo(dropdown)
                .mouseover(function (event) {
                    select_dropdown_item(get_element_from_event(event, "li"));
                })
                .click(function (event) {
                    add_token(get_element_from_event(event, "li"));
                })
                .mousedown(function (event) {
                    // Stop user selecting text on tokens
                    return false;
                })
                .hide();        
		
            for(var i in results) { 
				
				if (results.hasOwnProperty(i)) {
                    var this_li = $("<li>"+highlight_term(results[i].name, query)+"</li>")
                                      .appendTo(dropdown_ul);
                
                    if(i%2) {
                        this_li.addClass(settings.classes.dropdownItem);
                    } else {
                        this_li.addClass(settings.classes.dropdownItem2);
                    }
                
                    if(i == 0) {
                        select_dropdown_item(this_li);
                    }
        
                    $.data(this_li.get(0), "tokeninput", {"id": results[i].id, "name": results[i].name});			
					
                }
            }

            dropdown.show();
            dropdown_ul.slideDown("fast");

        } else {
            dropdown
                .html("<p>"+settings.noResultsText+"</p>")
                .show();
        }
    }
    
    // Highlight an item in the results dropdown
    function select_dropdown_item (item) {
        if(item) {
            if(selected_dropdown_item) {
                deselect_dropdown_item($(selected_dropdown_item));
            }
        
            item.addClass(settings.classes.selectedDropdownItem);
            selected_dropdown_item = item.get(0);
        }
    }
    
    // Remove highlighting from an item in the results dropdown
    function deselect_dropdown_item (item) {
        item.removeClass(settings.classes.selectedDropdownItem);
        selected_dropdown_item = null;
    }

    // Do a search
    function do_search(trim_last_char) {
        var query = input_box.val().toLowerCase();
        
        if(trim_last_char == 1) {
            query = query.substring(0, query.length-1);
        }

        if(query && query.length) {
            if(selected_token) {
                deselect_token($(selected_token), POSITION.AFTER);
            }
            
            var cached_results = cache.get(query);
            if(cached_results) {
                populate_dropdown(query, cached_results);
            } else {
                $.get(settings.url, {"q": query }, function (results) {
                    cache.add(query, results);
                    populate_dropdown(query, results);
                }, "json");
            }
        }
    }
};

// Really basic cache for the results
$.TokenList.Cache = function (options) {
    var settings = $.extend({
        max_size: 10
    }, options);
    
    var data = {};
    var size = 0;

    var flush = function () {
        data = {};
        size = 0;
    };

    this.add = function (query, results) {
        if(size > settings.max_size) {
            flush();
        }
        
        if(!data[query]) {
            size++;
        }
        
        data[query] = results;
    };
    
    this.get = function (query) {
        return data[query];
    };
};

})(jQuery);



/******************************************************/


jQuery.autocomplete = function(input, options) {
	// Create a link to self
	var me = this;

	// Create jQuery object for input element
	var $input = $j(input).attr("autocomplete", "off");

	// Apply inputClass if necessary
	if (options.inputClass) $input.addClass(options.inputClass);

	// Create results
	var results = document.createElement("div");
	// Create jQuery object for results
	var $results = $j(results);
	$results.hide().addClass(options.resultsClass).css("position", "absolute");
	if( options.width > 0 ) $results.css("width", options.width);

	// Add to body element
	$j("body").append(results);

	input.autocompleter = me;

	var timeout = null;
	var prev = "";
	var active = -1;
	var cache = {};
	var keyb = false;
	var hasFocus = false;
	var lastKeyPressCode = null;

	// flush cache
	function flushCache(){
		cache = {};
		cache.data = {};
		cache.length = 0;
	};

	// flush cache
	flushCache();

	// if there is a data array supplied
	if( options.data != null ){
		var sFirstChar = "", stMatchSets = {}, row = [];

		// no url was specified, we need to adjust the cache length to make sure it fits the local data store
		if( typeof options.url != "string" ) options.cacheLength = 1;

		// loop through the array and create a lookup structure
		for( var i=0; i < options.data.length; i++ ){
			// if row is a string, make an array otherwise just reference the array
			row = ((typeof options.data[i] == "string") ? [options.data[i]] : options.data[i]);

			// if the length is zero, don't add to list
			if( row[0].length > 0 ){
				// get the first character
				sFirstChar = row[0].substring(0, 1).toLowerCase();
				// if no lookup array for this character exists, look it up now
				if( !stMatchSets[sFirstChar] ) stMatchSets[sFirstChar] = [];
				// if the match is a string
				stMatchSets[sFirstChar].push(row);
			}
		}

		// add the data items to the cache
		for( var k in stMatchSets ){
			// increase the cache size
			options.cacheLength++;
			// add to the cache
			addToCache(k, stMatchSets[k]);
		}
	}

	$input
	.keydown(function(e) {
		// track last key pressed
		lastKeyPressCode = e.keyCode;
		switch(e.keyCode) {
			case 38: // up
				e.preventDefault();
				moveSelect(-1);
				break;
			case 40: // down
				e.preventDefault();
				moveSelect(1);
				break;
			case 9:  // tab
			case 13: // return
				if( selectCurrent() ){
					// make sure to blur off the current field
					$input.get(0).blur();
					e.preventDefault();
				}
				break;
			default:
				active = -1;
				if (timeout) clearTimeout(timeout);
				timeout = setTimeout(function(){onChange();}, options.delay);
				break;
		}
	})
	.focus(function(){
		// track whether the field has focus, we shouldn't process any results if the field no longer has focus
		hasFocus = true;
	})
	.blur(function() {
		// track whether the field has focus
		hasFocus = false;
		hideResults();
	});

	hideResultsNow();

	function onChange() {
		// ignore if the following keys are pressed: [del] [shift] [capslock]
		if( lastKeyPressCode == 46 || (lastKeyPressCode > 8 && lastKeyPressCode < 32) ) return $results.hide();
		var v = $input.val();
		if (v == prev) return;
		prev = v;
		if (v.length >= options.minChars) {
			$input.addClass(options.loadingClass);
			//var selSearch=document.getElementById(MODEL+'Type').value;
			
			/* START - GUEST View - Below condition has been added By Zaver for the Guest View Smart city search */
			if(MODEL == 'Guest')
			{
				if($input.attr('id') == "autoCompleteGuestViewCity") 
				{
					var selSearch = document.getElementById('autoCompleteGuestViewCity').value;
					var countryName = document.getElementById('autoCompleteGuestViewCountry').value;
					selSearch += "&countryName="+countryName;;
				} 
				
				if($input.attr('id') == "autoCompleteGuestViewCountry") 
				{
					var selSearch = document.getElementById('autoCompleteGuestViewCountry').value;					
				}
				
				if($input.attr('id') == "autoCompleteBusiness") 
				{
					//var selSearch = document.getElementById('autoCompleteBusiness').value;					
					var selSearch = "business";					
				}
				
				if($input.attr('id') == "autoCompleteSearch") 
				{
					var cityName = document.getElementById('autoCompleteGuestViewCity').value;
					var countryName = document.getElementById('autoCompleteGuestViewCountry').value;
					
					if(document.getElementById('UserRoleId').value == 1) {
						var selSearch = "people&countryName="+countryName+"&cityName="+cityName;	
					}
					
					if(document.getElementById('UserRoleId').value == 2) {
						var selSearch = "business&countryName="+countryName+"&cityName="+cityName;	
					}
					
					if(document.getElementById('UserRoleId').value == 3) {
						var selSearch = "question_answer&countryName="+countryName+"&cityName="+cityName;
					}
					
					if(document.getElementById('UserRoleId').value == 4) {
						var selSearch = "blogs&countryName="+countryName+"&cityName="+cityName;	
					}
					
					if(document.getElementById('UserRoleId').value == 5) {
						var selSearch = "photos&countryName="+countryName+"&cityName="+cityName;	
					}
					
					if(document.getElementById('UserRoleId').value == 6) {
						var selSearch = "videos&countryName="+countryName+"&cityName="+cityName;
					}
					
					if(document.getElementById('UserRoleId').value == 7) {
						var selSearch = "audios&countryName="+countryName+"&cityName="+cityName;	
					}
				}					
			}
			else
			{
				var selSearch=document.getElementById(MODEL+'Type').value;
				if ($input.attr('id') == "ProductBrand" || $input.attr('id') == "product_brand") {
					
					if (document.getElementById('business_profile_id')) {
						
						var bProfileId = document.getElementById('business_profile_id').value;	
						selSearch += "&bProfileId="+bProfileId;
					}
				}
				
				if ($input.attr('id') == "autoCompleteProductCategorySearch") {
					if (document.getElementById('business_profile_id')) {
						var bProfileId = document.getElementById('business_profile_id').value;	
						selSearch += "&bProfileId="+bProfileId;
						//alert(selSearch);
					}	
				}
			}			
			/* END - GUEST View - Below condition has been added By Zaver for the Guest View Smart city search */
			//alert(selSearch);
			requestData(v,selSearch);
		} else {			
			$input.removeClass(options.loadingClass);
			$results.hide();
		}
	};

 	function moveSelect(step) {

		var lis = $j("li", results);
		if (!lis) return;

		active += step;

		if (active < 0) {
			active = 0;
		} else if (active >= lis.size()) {
			active = lis.size() - 1;
		}

		lis.removeClass("ac_over");

		$j(lis[active]).addClass("ac_over");

		// Weird behaviour in IE
		// if (lis[active] && lis[active].scrollIntoView) {
		// 	lis[active].scrollIntoView(false);
		// }

	};

	function selectCurrent() {
		var li = $j("li.ac_over", results)[0];
		if (!li) {
			var $li = $("li", results);
			if (options.selectOnly) {
				if ($li.length == 1) li = $li[0];

			} else if (options.selectFirst) {
				li = $li[0];
			}
		}
		if (li) {
			selectItem(li);
			return true;
		} else {
			return false;
		}
	};

	function selectItem(li) {
		if (!li) {
			li = document.createElement("li");
			li.extra = [];
			li.selectValue = "";
		}
		
		li.selectValue = li.selectValue.replace(/<span style='color:#0000FF; font-weight:bold;'>/gi,"");
		li.selectValue = li.selectValue.replace(/<\/span>/gi,"");
		
		var v = $j.trim(li.selectValue ? li.selectValue : li.innerHTML);
		
		input.lastSelected = v;
		prev = v;
		$results.html("");
		$input.val(v);
	
	/* START - Automatically form post after selecting item from the smart type search result BY Zaver Vaghasiya on 13/10/2010 */
		if($input.attr('id') == "autoCompleteSearch") {
			searchsubmit(MODEL);
		}
	/* END - Automatically form post after selecting item from the smart type search result BY Zaver Vaghasiya on 13/10/2010 */
	
		hideResultsNow();
		if (options.onItemSelect) setTimeout(function() { options.onItemSelect(li) }, 1);
	};

	// selects a portion of the input string
	function createSelection(start, end){
		// get a reference to the input element
		var field = $input.get(0);
		if( field.createTextRange ){
			var selRange = field.createTextRange();
			selRange.collapse(true);
			selRange.moveStart("character", start);
			selRange.moveEnd("character", end);
			selRange.select();
		} else if( field.setSelectionRange ){
			field.setSelectionRange(start, end);
		} else {
			if( field.selectionStart ){
				field.selectionStart = start;
				field.selectionEnd = end;
			}
		}
		field.focus();
	};

	// fills in the input box w/the first match (assumed to be the best match)
	function autoFill(sValue){
		// if the last user key pressed was backspace, don't autofill
		if( lastKeyPressCode != 8 ){
			// fill in the value (keep the case the user has typed)
			$input.val($input.val() + sValue.substring(prev.length));
			// select the portion of the value not typed by the user (so the next character will erase)
			createSelection(prev.length, sValue.length);
		}
	};

	function showResults() {
		// get the position of the input field right now (in case the DOM is shifted)
		var pos = findPos(input);
		// either use the specified width, or autocalculate based on form element
		var iWidth = (options.width > 0) ? options.width : $input.width();
		// reposition
		$results.css({
			width: parseInt(iWidth) + "px",
			top: (pos.y + input.offsetHeight) + "px",
			left: pos.x + "px"
		}).show();
	};

	function hideResults() {
		if (timeout) clearTimeout(timeout);
		timeout = setTimeout(hideResultsNow, 200);
	};

	function hideResultsNow() {
		if (timeout) clearTimeout(timeout);
		$input.removeClass(options.loadingClass);
		if ($results.is(":visible")) {
			$results.hide();
		}
		if (options.mustMatch) {
			var v = $input.val();
			if (v != input.lastSelected) {
				selectItem(null);
			}
		}
	};

	function receiveData(q, data) {
		if (data) {
			$input.removeClass(options.loadingClass);
			results.innerHTML = "";

			// if the field no longer has focus or if there are no matches, do not display the drop down
			if( !hasFocus || data.length == 0 ) return hideResultsNow();

			if ($j.browser.msie) {
				// we put a styled iframe behind the calendar so HTML SELECT elements don't show through
				$results.append(document.createElement('iframe'));
			}
			results.appendChild(dataToDom(data));
			// autofill in the complete box w/the first match as long as the user hasn't entered in more data
			if( options.autoFill && ($input.val().toLowerCase() == q.toLowerCase()) ) autoFill(data[0][0]);
			showResults();
		} else {
			hideResultsNow();
		}
	};

	function parseData(data) {
		if (!data) return null;
		var parsed = [];
		var rows = data.split(options.lineSeparator);
		for (var i=0; i < rows.length; i++) {
			var row = $j.trim(rows[i]);
			if (row) {
				parsed[parsed.length] = row.split(options.cellSeparator);
			}
		}
		return parsed;
	};

	function dataToDom(data) {
		var ul = document.createElement("ul");
		var num = data.length;

		// limited results to a max number
		if( (options.maxItemsToShow > 0) && (options.maxItemsToShow < num) ) num = options.maxItemsToShow;

		for (var i=0; i < num; i++) {
			var row = data[i];
			if (!row) continue;
			var li = document.createElement("li");
			if (options.formatItem) {
				li.innerHTML = options.formatItem(row, i, num);
				li.selectValue = row[0];
			} else {
				li.innerHTML = row[0];
				li.selectValue = row[0];
			}
			var extra = null;
			if (row.length > 1) {
				extra = [];
				for (var j=1; j < row.length; j++) {
					extra[extra.length] = row[j];
				}
			}
			li.extra = extra;
			ul.appendChild(li);
			$j(li).hover(
				function() { $j("li", ul).removeClass("ac_over"); $j(this).addClass("ac_over"); active = $j("li", ul).indexOf($j(this).get(0)); },
				function() { $j(this).removeClass("ac_over"); }
			).click(function(e) { e.preventDefault(); e.stopPropagation(); selectItem(this) });
		}
		return ul;
	};

	function requestData(q,selSearch) {
		if (!options.matchCase) q = q.toLowerCase();
		var data = options.cacheLength ? loadFromCache(q) : null;
		data = null;
		// recieve the cached data
		if (data) {
			receiveData(q, data);
		// if an AJAX url has been supplied, try loading the data now
		} else if( (typeof options.url == "string") && (options.url.length > 0) ){
			$j.get(makeUrl(q,selSearch), function(data) {
				data = parseData(data);
				//alert(data);
				addToCache(q, data);
				receiveData(q, data);
			});
		// if there's been no data found, remove the loading class
		} else {
			$input.removeClass(options.loadingClass);
		}
	};
	

	function makeUrl(q,selSearch) {
		//alert(q);
		//alert(selSearch);
		//var model="<?php echo 'test' ?>";
		//alert(MODEL);
		//var selSearch=document.getElementById(MODEL+'Type').value;
		//alert(options.extraParams[0].value);
		//alert(selSearch);
		//alert(encodeURI(options.extraParams[0]));
		var url = options.url + "?q=" + encodeURI(q) + "&selSearch="+selSearch;
		for (var i in options.extraParams) {
			
			url += "&" + i + "=" + encodeURI(options.extraParams[i]);
		}
		
		//alert(url);
		return url;
	};

	function loadFromCache(q) {
		if (!q) return null;
		if (cache.data[q]) return cache.data[q];
		if (options.matchSubset) {
			for (var i = q.length - 1; i >= options.minChars; i--) {
				var qs = q.substr(0, i);
				var c = cache.data[qs];
				if (c) {
					var csub = [];
					for (var j = 0; j < c.length; j++) {
						var x = c[j];
						var x0 = x[0];
						if (matchSubset(x0, q)) {
							csub[csub.length] = x;
						}
					}
					return csub;
				}
			}
		}
		return null;
	};

	function matchSubset(s, sub) {
		if (!options.matchCase) s = s.toLowerCase();
		var i = s.indexOf(sub);
		if (i == -1) return false;
		return i == 0 || options.matchContains;
	};

	this.flushCache = function() {
		flushCache();
	};

	this.setExtraParams = function(p) {
		options.extraParams = p;
	};

	this.findValue = function(){
		var q = $input.val();

		if (!options.matchCase) q = q.toLowerCase();
		var data = options.cacheLength ? loadFromCache(q) : null;
		if (data) {
			findValueCallback(q, data);
		} else if( (typeof options.url == "string") && (options.url.length > 0) ){
			$j.get(makeUrl(q), function(data) {
				data = parseData(data)
				addToCache(q, data);
				findValueCallback(q, data);
			});
		} else {
			// no matches
			findValueCallback(q, null);
		}
	}

	function findValueCallback(q, data){
		if (data) $input.removeClass(options.loadingClass);

		var num = (data) ? data.length : 0;
		var li = null;

		for (var i=0; i < num; i++) {
			var row = data[i];

			if( row[0].toLowerCase() == q.toLowerCase() ){
				li = document.createElement("li");
				if (options.formatItem) {
					li.innerHTML = options.formatItem(row, i, num);
					li.selectValue = row[0];
				} else {
					li.innerHTML = row[0];
					li.selectValue = row[0];
				}
				var extra = null;
				if( row.length > 1 ){
					extra = [];
					for (var j=1; j < row.length; j++) {
						extra[extra.length] = row[j];
					}
				}
				li.extra = extra;
			}
		}

		if( options.onFindValue ) setTimeout(function() { options.onFindValue(li) }, 1);
	}

	function addToCache(q, data) {
		if (!data || !q || !options.cacheLength) return;
		if (!cache.length || cache.length > options.cacheLength) {
			flushCache();
			cache.length++;
		} else if (!cache[q]) {
			cache.length++;
		}
		cache.data[q] = data;
	};

	function findPos(obj) {
		var curleft = obj.offsetLeft || 0;
		var curtop = obj.offsetTop || 0;
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
		return {x:curleft,y:curtop};
	}
}

jQuery.fn.autocomplete = function(url, options, data) {
	// Make sure options exists
	options = options || {};
	// Set url as option
	options.url = url;
	// set some bulk local data
	options.data = ((typeof data == "object") && (data.constructor == Array)) ? data : null;

	// Set default values for required options
	options.inputClass = options.inputClass || "ac_input";
	options.resultsClass = options.resultsClass || "ac_results";
	options.lineSeparator = options.lineSeparator || "\n";
	options.cellSeparator = options.cellSeparator || "|";
	options.minChars = options.minChars || 1;
	options.delay = options.delay || 400;
	options.matchCase = options.matchCase || 0;
	options.matchSubset = options.matchSubset || 1;
	options.matchContains = options.matchContains || 0;
	options.cacheLength = options.cacheLength || 1;
	options.mustMatch = options.mustMatch || 0;
	options.extraParams = options.extraParams || {};
	options.loadingClass = options.loadingClass || "ac_loading";
	options.selectFirst = options.selectFirst || false;
	options.selectOnly = options.selectOnly || false;
	options.maxItemsToShow = options.maxItemsToShow || -1;
	options.autoFill = options.autoFill || false;
	options.width = parseInt(options.width, 10) || 0;
		
	this.each(function() {
		var input = this;
		new jQuery.autocomplete(input, options);
	});

	// Don't break the chain
	return this;
}

jQuery.fn.autocompleteArray = function(data, options) {
	return this.autocomplete(null, options, data);
}

jQuery.fn.indexOf = function(e){
	for( var i=0; i<this.length; i++ ){
		if( this[i] == e ) return i;
	}
	return -1;
};
