var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();


Autocomplete = Class.create();
Autocomplete.prototype = {
	initialize: function (element, container, ajaxurl, form, submitform) {
		this.timer = new Timer(this);
		this.timerid = null;
		this.element = $(element);
		this.container = $(container);
		this.element.setAttribute("autocomplete", "off");
		
		this.more_results_selected = false;
		this.last_value = "";
		this.list_nodes = [];
		this.current_selection_index = -1;
		this.previous_selection_index = this.current_selection_index;
		this.parent_form = document.forms[form];
		
		this.ajaxurl = ajaxurl;
		this.submitform = submitform;
		
		if( BrowserDetect.browser == "Explorer" && BrowserDetect.version > 5.5 && BrowserDetect.version < 7 )
			this.useDivShim = true;
		else
			this.useDivShim = false;
		
		if( this.useDivShim == true ) {
			
			
			var divShimId = "AuotCompleteDivShim";
			this.divShim = document.getElementById(divShimId);
			
			if( !this.divShim ) {
			
				var strDivShim = '<iframe id="AuotCompleteDivShim" src="javascript:false;" scrolling="no" frameborder="0" style="position:absolute; display:block; z-index:100; display:none"></iframe>';
				document.write( strDivShim );
			}
			
			this.divShim = document.getElementById(divShimId);
			this.divShimStyle = this.divShim.style
			this.divShimStyle.filter = 'progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)';
		}
		
		//this.intRequestCount = 0;
		//this.intRequestCountReceived = 0;

		Event.observe(this.element, 'keydown', this.keyDown.bindAsEventListener(this), false);
		Event.observe(this.element, 'keyup', this.keyPressed.bindAsEventListener(this), false);
		//Event.observe(this.element, 'blur', this.inputLostFocus.bindAsEventListener(this), false);
		Event.observe(this.element, "focus", this.onFocus.bindAsEventListener(this), false);
		//Event.observe(this.parent_form, 'submit', this.processSubmit.bindAsEventListener(this), false);
		Event.observe(document.body, 'click', this.inputLostFocus.bindAsEventListener(this), false);
	},

	sanitizeQuery: function (query) {
		var sanitized_query = query;
		sanitized_query = sanitized_query.replace(/[\&]/g,'');
		return escape(sanitized_query);
	},

	processSubmit: function () {

	},

	closeList: function () {
		this.list_nodes = [];
		this.current_selection_index = -1;
		this.previous_selection_index = this.current_selection_index;
		this.container.style.display = "none";
		
		if( this.useDivShim == true ) {
			this.divShimStyle.display = "none";
		}
	},

	listNodeClicked: function (e) {
		var node = Event.element(e);
		var prepop = node.getAttribute('prepop');
		if (!prepop) {
			node = node.parentNode;
		}
		prepop = node.getAttribute('prepop');
		var saved_last_value = this.last_value;
		this.last_value = node.innerHTML.replace(/<.*?>/g, '');
		
		var aryPrePop = prepop.split("|")
		
		for( var i=0; i < aryPrePop.length; i+=2 )
		{
			if( aryPrePop[i] == "Eval" )
			{
				eval( aryPrePop[i+1] );
			}
			else
			{
				if( this.parent_form.elements[aryPrePop[i]] ) {
					this.parent_form.elements[aryPrePop[i]].value = aryPrePop[i+1];
				}			
			}
		}
		
		this.closeList();
		
		Event.stop(e);
		
		if( this.submitform == true )
		{
			this.parent_form.submit();
		}
		
	},

	listNodeFocusedWithMouse: function (e) {
		var node = Event.element(e);
		var url = node.getAttribute('prepop');
		if (!url) {
			node = node.parentNode;
		}
		var node_index = this.list_nodes.indexOf(node);

		this.previous_selection_index = this.current_selection_index;
		if (this.previous_selection_index >= 0 && this.previous_selection_index < this.list_nodes.length) {
			this.list_nodes[this.previous_selection_index].className = "normal";
		}
		this.current_selection_index = node_index;
		this.list_nodes[this.current_selection_index].className = "focused";
	},

	inputLostFocus: function (e) {
		this.last_value = "";
		this.closeList();
	},
	
	onFocus: function(e) {
		this.watchKeyStrokes();
	},

	keyPressed: function (e) {
		switch (e.keyCode) {
		case Event.KEY_ESC:
			this.element.value = this.last_value;
			this.last_value = "";
			this.closeList();
			return;
			break;
		case Event.KEY_RETURN:
			this.closeList();
			return;
			break;
		case Event.KEY_LEFT:
		case Event.KEY_RIGHT:
			return;
			break;
		case Event.KEY_UP:
		case Event.KEY_DOWN:
			if (this.container.style.display == "none") {
				return;
			}
			this.previous_selection_index = this.current_selection_index;
			if (this.previous_selection_index >= 0 && this.previous_selection_index < this.list_nodes.length) {
				this.list_nodes[this.previous_selection_index].className = "normal";
			}

			switch (e.keyCode) {
				case Event.KEY_UP:
				this.current_selection_index--;
				if (this.current_selection_index < 0) {
					this.current_selection_index = -1;
					this.element.value = this.last_value;
				}
				break;
				case Event.KEY_DOWN:
				this.current_selection_index++;
				if (this.current_selection_index >= this.list_nodes.length) {
					this.current_selection_index = this.list_nodes.length - 1;
				}
				break;
			}

			if (this.current_selection_index >= 0 && this.current_selection_index < this.list_nodes.length) {
				var selected_node = this.list_nodes[this.current_selection_index];
				selected_node.className = "focused";
				this.container.scrollTop = selected_node.offsetTop;
			}
			return;
			break;
		}
		this.watchKeyStrokes();
	},
	
	keyDown: function (e) {
		switch (e.keyCode) {
		case Event.KEY_RETURN:
			
			var selected_node = this.list_nodes[this.current_selection_index];
			
			if( selected_node )
			{
				var prepop = selected_node.getAttribute('prepop');
				
				var aryPrePop = prepop.split("|");
				
				for( var i=0; i < aryPrePop.length; i+=2 )
				{
					if( aryPrePop[i] == "Eval" )
					{
						eval( aryPrePop[i+1] );
					}
					else
					{
						if( this.parent_form.elements[aryPrePop[i]] ) {
							this.parent_form.elements[aryPrePop[i]].value = aryPrePop[i+1];
						}
					}
				}
				
				Event.stop(e);
				
				this.closeList();
				
				if( this.submitform == true )
				{
					this.parent_form.submit();
				}
			}
			
			return;
			break;
		}
	},

	ajaxRequestCompleted: function (originating_request) {
		
		document.form1.strStatus.value = "";
		
		var strResponse = originating_request.responseText;
		
		/*if( strResponse.substring( 0, 13 ) == "RequestCount:" )
		{
			var intRequestCountCurrent = parseInt( strRequestCount = strResponse.substring( 14, strResponse.indexOf( ";" ) - 1 ) );
			
			//if( this.intRequestCount != intRequestCountCurrent ) {
				//strResponse = intRequestCountReceived + "|" + intRequestCountCurrent + "|" + strResponse;
				//return;
			//}
			
			//this.intRequestCountReceived = intRequestCountCurrent;
			strResponse = strResponse.substring( strResponse.indexOf( ";" ) + 1, strResponse.length );
		}*/
		
		this.container.innerHTML = strResponse;
		this.list_nodes = $A(this.container.getElementsByTagName('div'));
		if (this.list_nodes.length) {
			for (var i = 0; i < this.list_nodes.length; i++) {
				var node = this.list_nodes[i];
				node.onmousedown = this.listNodeClicked.bindAsEventListener(this);
				node.onmouseover = this.listNodeFocusedWithMouse.bindAsEventListener(this);
			}
			this.container.style.display = "block";
			
			var DivRef = this.container;

			var pos = findPos( this.element );
			
			DivRef.style.top = pos[1] + this.element.offsetHeight + "px";
			DivRef.style.left = pos[0] + "px";
			
			//=======================================================================================
			DivRef.style.height = 'Auto';
			
			if (DivRef.offsetHeight > 200)
			{
				DivRef.style.height = '200px';
			}
			//=======================================================================================
			
			if( this.useDivShim == true ) {
				this.divShimStyle.width = DivRef.offsetWidth + 'px';
				this.divShimStyle.height = DivRef.offsetHeight + 'px';
				this.divShimStyle.top = DivRef.style.top;
				this.divShimStyle.left = DivRef.style.left;
				this.divShimStyle.display = "block";
			}
		}
		else {
			this.closeList();
		}

		this.loading = false;
		if (this.element.value != this.last_value && this.more_results_selected == false ) {
			this.watchKeyStrokes();
		}
		
		this.more_results_selected = false;
	},

	watchKeyStrokes: function () {
		
		document.form1.strStatus.value = "loading... please wait";
		
		this.timer.clearTimeout( this.timerid );

		if (this.loading) {
			return;
		}
		if (this.element.value.replace(/^\s+|\s+$/, '').length < 0) {
			this.closeList();
			return;
		}
		
		//this.timerid = this.timer.setTimeout("sendRequest", 400);
		this.sendRequest();
	},
	
	sendRequest: function () {
		this.loading = true;
		this.last_value = this.element.value;

		var aryUrl = this.ajaxurl.split("?");

		var url = aryUrl[0];
		var params = aryUrl[1] + '&q=' + this.sanitizeQuery(this.element.value);
		
		if( this.more_results_selected == true ) {
			params += '&more=Y';
		}
		
		this.intRequestCount += 1;
		params += '&RequestCount=' + this.intRequestCount;
		
		var d = new Date();
		
		params += '&Time=' + d.getTime();
		
		
		/*=======================================================================================================*/
		//var source_field = this.container;
		var populated_fields = '';
		var delimiter = '';
		
		//if (source_field != 'ProductSubCategories_1')
		//{
			var fields = new Array(3,67,63,53,52,50,51,56,57,54,55,61,60,59,62);
			
			for (var i=0; i < fields.length; i++)
			{
				var field_name = 'Products_' + fields[i];
				var field_value = document.form1.elements['strProducts_' + fields[i]].value;
				
				if (field_value.length > 0)// && field_name != source_field)
				{
					populated_fields += delimiter + field_name + '=' + field_value
					delimiter = '|';
				}
			}
		//}
		
		params = params + '&PF=' + populated_fields;
		//alert(params);
		/*=======================================================================================================*/
		
		var ajax_request = new Ajax.Request(url, {
				method: 'get',
				parameters: params,
				onComplete: this.ajaxRequestCompleted.bind(this)
			}
		);
	}
}



// The constructor should be called with
// the parent object (optional, defaults to window).

function Timer(){
    this.obj = (arguments.length)?arguments[0]:window;
    return this;
}

// The set functions should be called with:
// - The name of the object method (as a string) (required)
// - The millisecond delay (required)
// - Any number of extra arguments, which will all be
//   passed to the method when it is evaluated.

Timer.prototype.setInterval = function(func, msec){
    var i = Timer.getNew();
    var t = Timer.buildCall(this.obj, i, arguments);
    Timer.set[i].timer = window.setInterval(t,msec);
    return i;
}
Timer.prototype.setTimeout = function(func, msec){
    var i = Timer.getNew();
    Timer.buildCall(this.obj, i, arguments);
    Timer.set[i].timer = window.setTimeout("Timer.callOnce("+i+");",msec);
    return i;
}

// The clear functions should be called with
// the return value from the equivalent set function.

Timer.prototype.clearInterval = function(i){
    if(!Timer.set[i]) return;
    window.clearInterval(Timer.set[i].timer);
    Timer.set[i] = null;
}
Timer.prototype.clearTimeout = function(i){
    if(!Timer.set[i]) return;
    window.clearTimeout(Timer.set[i].timer);
    Timer.set[i] = null;
}

// Private data

Timer.set = new Array();
Timer.buildCall = function(obj, i, args){
    var t = "";
    Timer.set[i] = new Array();
    if(obj != window){
        Timer.set[i].obj = obj;
        t = "Timer.set["+i+"].obj.";
    }
    t += args[0]+"(";
    if(args.length > 2){
        Timer.set[i][0] = args[2];
        t += "Timer.set["+i+"][0]";
        for(var j=1; (j+2)<args.length; j++){
            Timer.set[i][j] = args[j+2];
            t += ", Timer.set["+i+"]["+j+"]";
    }}
    t += ");";
    Timer.set[i].call = t;
    return t;
}
Timer.callOnce = function(i){
    if(!Timer.set[i]) return;
    eval(Timer.set[i].call);
    Timer.set[i] = null;
}
Timer.getNew = function(){
    var i = 0;
    while(Timer.set[i]) i++;
    return i;
}

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		}
		while (obj = obj.offsetParent);
	}
	return [curleft,curtop];
}

