/*
 * jQuery selectbox plugin
 *
 * Copyright (c) 2007 Sadri Sahraoui (brainfault.com)
 * Licensed under the GPL license:
 *   http://www.gnu.org/licenses/gpl.html
 *
 * The code is inspired from Autocomplete plugin (http://www.dyve.net/jquery/?autocomplete)
 *
 * Revision: $Id$
 * Version: 0.3
 */
jQuery.fn.extend({
	selectbox: function(options) {
		return this.each(function() {
			new jQuery.SelectBox(this, options);
		});
	}
});

jQuery.SelectBox = function(selectobj, options) {
	
	var opt = options || {};
	opt.inputClass = opt.inputClass || "selectbox";
	opt.containerClass = opt.containerClass || "selectbox-wrapper";
	opt.hoverClass = opt.hoverClass || "selected";
	opt.debug = opt.debug || false;
	var opened = false;
	var elm_id = selectobj.id;
	var active = -1;
	var inFocusListe = false;
	var inFocus = false;
	var hasfocus = 0;
	// list des keycode
	var tblKey = {65:"a", 66:"b", 67:"c", 68:"d", 69:"e", 70:"f", 71:"g", 72:"h", 73:"i", 74:"j", 75:"k", 76:"l", 77:"m", 78:"n", 79:"o", 80:"p", 81:"q", 82:"r", 83:"s", 84:"t", 85:"u", 86:"v", 87:"w", 88:"x", 89:"y", 90:"z"};
	//jquery object for select element
	var $select = $(selectobj);
	// jquery container object
	var $container = setupContainer(opt);
	var containH = $container.height();
  //jquery input object 
	var $input = setupInput(opt);
	//txt save for drop down select with keyboard
	var keydownTxt = "";
	//cooldown to empty keydownTxt
	var keydownTimeId = 0;
	// hide select and append newly created elements
	$select.hide().before($input).before($container);
	
	init();
	
	$input
	.click(function(){
		$(this).parent('.nes_select-skin-block').css('z-index', '99');
		$(this).parent('.nes_skin-registration').css('z-index', '99');
		if (opened) {
			hideMe();
		}else{
			opened = true;
			$container.show()
		}

		if (!inFocus) {
		  $container.toggle();
		}
		
	})
	.focus(function(){
		$(this).parent('.nes_select-skin-block').css('z-index', '99');
		$(this).parent('.nes_skin-registration').css('z-index', '99');
	   if ($container.not(':visible')) {
	       inFocus = true;
	       $container.show();
	   }
	})
	.keydown(function(event) {	   
		switch(event.keyCode) {
			case 38: // up
				event.preventDefault();
				moveSelect(-1);
				setCurrent();
				break;
			case 40: // down
				event.preventDefault();
				moveSelect(1);
				setCurrent();
				break;
			//case 9:  // tab 
			case 13: // return
				event.preventDefault(); // seems not working in mac !
				setCurrent();
				hideMe();
				break;
			default:
				if(event.keyCode>64 && event.keyCode<91){
					var lis = $("li", $container);
					if (!lis) return;
					var lisIndex=[];
					keydownTxt += tblKey[event.keyCode];
					if (keydownTimeId > 0)
						clearTimeout(keydownTimeId);
					keydownTimeId = setTimeout(function(){keydownTxt = "";}, 1000);
					lis.filter(function(i){
						var $$ = $(this);
						var txtLi = $$.text();
						txtLi = txtLi.substr(0, keydownTxt.length).toLowerCase();
						if(txtLi == keydownTxt){
							lisIndex.push(i);
						}
					});
					if(lisIndex.length > 0) {
						active = lisIndex[0];
						lis.removeClass(opt.hoverClass);
						$(lis[active]).addClass(opt.hoverClass);
						setCurrent();
					}
				}
        break;
		}
	})
	.blur(function() {
		if ($container.is(':visible') && (hasfocus > 0 || inFocusListe==true)) {
			if(opt.debug) console.log('container visible and has focus')
		} else {
			if(contextPage!='quickorder'){
				hideMe(false);	
			}
		}
	});
	$container.mouseenter(function(){
		inFocusListe=true;
	})
	.mouseleave(function (){
		inFocusListe=false;
		setTimeout(function ()
		{
			if(inFocusListe==false)
				hideMe(false);
		},1000);
	})
	.blur(function (){
		
		if ($container.is(':visible') && (hasfocus > 0 || inFocusListe==true)) {
			if(opt.debug) console.log('container visible and has focus')
		} else {
			if(contextPage!='quickorder'){
				hideMe(false);	
			}
		}
	})
	;
	//document.body.onselectstart = function() {console.log(hasfocus);console.log($container);console.log(inFocusListe);return false;}

	function hideMe(andSubmit) { 
		$container.parent('.nes_select-skin-block').css('z-index', '0');
		$container.parent('.nes_skin-registration').css('z-index', '0');
		hasfocus = 0;
		$container.hide(); 
		opened = false;
		if(contextPage=='list' && $('#nes_colLeft').hasClass('nes_listMachine')){
			if(andSubmit==null)
			{	
				paramToQuery();
				//$('.nes_innerSwitchListMachine > form > p > a').css('visibility','visible');
			}
		}
		if(contextPage=='quickorder' && $('#nes_colMid .nes_colMid-small').hasClass('nes_quickOrderMachines')){
			paramToQueryQo();
		}
		if(contextPage=='registrationMP'  && andSubmit==null && $select[0].id=="Country"){
			loadSelectStors__regMachPos($select.val());
		}
		if(contextPage=='formRegistration' && $container.parents('li').hasClass('customerForm_country')) {
			setTimeout(	
				function(){
					if(andSubmit==null)
					{
						toRegistration();
					}
				}
				, 100
			);
		}
		if(contextPage == "registration"){
			if($('#Display').length) {
				var valEl = $container.next('select').val();
				var locPath = window.location.pathname;
				var detPet=false;
				//var locPath = "https://localhost:9002/uk/en/orders/detail/lastThreeOrders/2367209";
				if(locPath.indexOf('/detail/')!=-1)
					detPet=true;
				locPath = locPath.replace('/detail/', '/list/');
				
				locPath = locPath.replace('/#order', '');
				if(locPath.lastIndexOf('/')==locPath.length-1){
					locPath = locPath.slice(0, -1);
				}
				var locAPath = [];
				locAPath = locPath.split('/');
				locAPath.pop();
				if(detPet)
					locAPath.pop();
				var newLoc = '';
				for ( i = 0; i < locAPath.length;i++) {
					if(i != 0)
					newLoc += locAPath[i]+'/';
				}
				window.location.href = window.location.protocol +'//'+ window.location.host +'/'+ newLoc + valEl + "/#order";
			}
		}
		if(andSubmit==null)
		{
			if($select.attr('class').indexOf('nes_linkUpdFromBag')!=-1)
			{
				BagController.initDTOobj($select.attr('tag'));
				BagController.UpdToBag($select);
			}
		}
	}
	
	function toRegistration(){
		var $$ = $container;
		var countryParam = $$.next('select').val();
		var contextParam = $$.parents('fieldset');
		//var typeParam =  $('li input[name$=addressType]:checked', contextParam).attr('value');
		var typeParam = $('li input[name$=addressType]:checked').val();
		queryRegistration(typeParam, countryParam, contextParam);
	}
	
	function init() {
		$container.append(getSelectOptions()).hide();
		var width = $input.width()
		$container.width(width);
    }
	
	function setupContainer(options) {
		var container = document.createElement("div");
		$container = $(container);
		$container.attr('id', elm_id+'_container');
		$container.addClass(options.containerClass);
		
		return $container;
	}
	
	function setupInput(options) {
		var input = document.createElement("input");
		var $input = $(input);
		$input.attr("id", elm_id+"_input");
		$input.attr("type", "text");
		$input.addClass(options.inputClass);
		$input.attr("autocomplete", "off");
		$input.attr("readonly", "readonly");
		//$input.attr("tabIndex", $select.attr("tabindex")); // "I" capital is important for ie
		
		return $input;	
	}
	
	function moveSelect(step) {
		var lis = $("li", $container);
		if (!lis) return;

		active += step;

		if (active < 0) {
			active = 0;
		} else if (active >= lis.size()) {
			active = lis.size() - 1;
		}

		lis.removeClass(opt.hoverClass);

		$(lis[active]).addClass(opt.hoverClass);
	}
	
	function setCurrent() {
		var li = $("li."+opt.hoverClass, $container).get(0);
		var el = li.id;
		$container.scrollTop(0);
		var liP = $(li).position();
		$container.scrollTop(liP.top);
		$select.val(el);
		$input.val($(li).html().replace('&amp;', '\u0026'));
		if($input.val() != 0)
			$input.addClass('blackSelected');
		else
			$input.removeClass('blackSelected');
		return true;
	}
	
	// select value
	function getCurrentSelected() {
		return $select.val();
	}
	
	// input value
	function getCurrentValue() {
		return $input.val();
	}
	
	function getSelectOptions() {
		var select_options = new Array();
		var ul = document.createElement('ul');
		$select.children('option').each(function() {
			var li = document.createElement('li');
			li.setAttribute('id', $(this).val());
			li.innerHTML = $(this).html();
			if ($(this).is(':selected')) {
				$input.val($(this).html());
				$(li).addClass(opt.hoverClass);
			}
			ul.appendChild(li);
			$(li)
			.mouseover(function(event) {
				hasfocus = 1;
				if (opt.debug) console.log('out on : '+this.id);
				$container.find('li').removeClass(opt.hoverClass);
				jQuery(event.target, $container).addClass(opt.hoverClass);
			})
			.mouseout(function(event) {
				hasfocus = -1;
				if (opt.debug) console.log('out on : '+this.id);
				jQuery(event.target, $container).removeClass(opt.hoverClass);
			})
			.click(function(event) {
				if (opt.debug) console.log('click on :'+this.id);
				$(this).addClass(opt.hoverClass);
				setCurrent();
				hideMe();
			});
		});
		return ul;
	}
	
};
