/*
 * jQuery selectbox plugin
 *
 * Copyright (c) 2007 Sadri Sahraoui (brainfault.com)
 * Licensed under the GPL license and MIT:
 *   http://www.opensource.org/licenses/GPL-license.php
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * The code is inspired from Autocomplete plugin (http://www.dyve.net/jquery/?autocomplete)
 *
 * Revision: jQncIdjQnc
 * Version: 1.0
 * 
 * Changelog :
 *  Version 1.0
 *  - Support jQuery noConflict option
 *  - Add callback for onChange event, thanks to Jason
 *  - Fix IE8 support
 *  - Fix auto width support
 *  - Fix focus on firefox dont show the carret
 *  Version 0.6
 *  - Fix IE scrolling problem
 *  Version 0.5 
 *  - separate css style for current selected element and hover element which solve the highlight issue 
 *  Version 0.4
 *  - Fix width when the select is in a hidden div   @Pawel Maziarz
 *  - Add a unique id for generated li to avoid conflict with other selects and empty values @Pawel Maziarz
 */
 
var jQnc = jQuery.noConflict();

jQuery.fn.extend({
	selectbox: function(options) {
		return this.each(function() {
			new jQuery.SelectBox(this, options);
		});
	}
});


/* pawel maziarz: work around for ie logging */
if (!window.console) {
	var console = {
		log: function(msg) { 
	 }
	}
}
/* */

jQuery.SelectBox = function(selectobj, options) {
	
	var opt = options || {};
	opt.inputClass = opt.inputClass || "selectbox";
	opt.containerClass = opt.containerClass || "selectbox-wrapper";
	opt.hoverClass = opt.hoverClass || "current";
	opt.currentClass = opt.currentClass || "selected";
    opt.onChangeCallback = opt.onChangeCallback || false;
    opt.onChangeParams = opt.onChangeParams || false;
	opt.debug = opt.debug || false;
	
	var elm_id = selectobj.id;
	var active = 0;
	var inFocus = false;
	var hasfocus = 0;
	//jquery object for select element
	var gVselect = jQuery(selectobj);
	// jquery container object
	var gVcontainer = setupContainer(opt);
	//jquery input object 
	var gVinput = setupInput(opt);
	// hide select and append newly created elements
	//gVselect.hide().before(gVinput).before(gVcontainer);
	
	gVselect.hide().before(gVinput);
	
	console.log(gVinput);
	gVcontainer.css({top: gVinput.position().top + gVinput.height() + 10, left: gVinput.position().left});
	jQnc("div.contact-form").append(gVcontainer);
	
	init();
	
	gVinput
	.click(function(){
    if (!inFocus) {
		  gVcontainer.toggle();
		}
	})
	.focus(function(){
	   if (gVcontainer.not(':visible')) {
	       inFocus = true;
	       gVcontainer.show();
           gVcontainer.focus();
	   }
	})
	.keydown(function(event) {	   
		switch(event.keyCode) {
			case 38: // up
				event.preventDefault();
				moveSelect(-1);
				break;
			case 40: // down
				event.preventDefault();
				moveSelect(1);
				break;
			//case 9:  // tab 
			case 13: // return
				event.preventDefault(); // seems not working in mac !
				jQnc('li.'+opt.hoverClass).trigger('click');
				break;
			case 27: //escape
			  hideMe();
			  break;
		}
	})
	.blur(function() {
		if (gVcontainer.is(':visible') && hasfocus > 0 ) {
			if(opt.debug) console.log('container visible and has focus')
		} else {
		  // Workaround for ie scroll - thanks to Bernd Matzner
            if((jQuery.browser.msie && jQuery.browser.version.substr(0,1) < 8) || jQuery.browser.safari){ // check for safari too - workaround for webkit
                if(document.activeElement.getAttribute('id').indexOf('_container')==-1){
                    hideMe();
                } else {
                    gVinput.focus();
                }
            } else {
                hideMe();
            }
		}
	});

	function hideMe() { 
		hasfocus = 0;
		gVcontainer.hide(); 
	}
	
	function init() {
		gVcontainer.append(getSelectOptions(gVinput.attr('id'))).hide();
		var width = gVinput.css('width');
		console.log(jQuery(gVcontainer));
		gVcontainer.width(width);
    }
	
	function setupContainer(options) {
		var container = document.createElement("div");
		gVcontainer = jQuery(container);
		gVcontainer.attr('id', elm_id+'_container');
		gVcontainer.addClass(options.containerClass);
        gVcontainer.css('display', 'none');
		return gVcontainer;
	}
	
	function setupInput(options) {
		var input = document.createElement("input");
		var gVinput = jQuery(input);
		gVinput.attr("id", elm_id+"_input");
		gVinput.attr("type", "text");
		gVinput.addClass(options.inputClass);
		gVinput.attr("autocomplete", "off");
		gVinput.attr("readonly", "readonly");
		gVinput.attr("tabIndex", gVselect.attr("tabindex")); // "I" capital is important for ie
        gVinput.css("width", gVselect.css("width"));
		return gVinput;	
	}
	
	function moveSelect(step) {
		var lis = jQuery("li", gVcontainer);
		if (!lis || lis.length == 0) return false;
		active += step;
    //loop through list
		if (active < 0) {
			active = lis.size();
		} else if (active > lis.size()) {
			active = 0;
		}
        scroll(lis, active);
		lis.removeClass(opt.hoverClass);

		jQuery(lis[active]).addClass(opt.hoverClass);
	}
	
	function scroll(list, active) {
      var el = jQuery(list[active]).get(0);
      var list = gVcontainer.get(0);
      
      if (el.offsetTop + el.offsetHeight > list.scrollTop + list.clientHeight) {
        list.scrollTop = el.offsetTop + el.offsetHeight - list.clientHeight;      
      } else if(el.offsetTop < list.scrollTop) {
        list.scrollTop = el.offsetTop;
      }
	}
	
	function setCurrent() {	
		var li = jQuery("li."+opt.currentClass, gVcontainer).get(0);
		var ar = (''+li.id).split('_');
		var el = ar[ar.length-1];
		//gVselect.val(el);
        gVselect.get(0).selectedIndex = jQnc('li', gVcontainer).index(li);
		gVinput.val(jQnc(li).html());
        opt.onChangeParams = { selectedVal : gVselect.val() };
        if (opt.onChangeCallback) opt.onChangeCallback(opt.onChangeParams);
		return true;
	}
	
	// select value
	function getCurrentSelected() {
		return gVselect.val();
	}
	
	// input value
	function getCurrentValue() {
		return gVinput.val();
	}
	
	function getSelectOptions(parentid) {
		var select_options = new Array();
		var ul = document.createElement('ul');
		gVselect.children('option').each(function() {
			var li = document.createElement('li');
			li.setAttribute('id', parentid + '_' + jQnc(this).val());
			li.innerHTML = jQnc(this).html();
			if (jQnc(this).is(':selected')) {
				gVinput.val(jQnc(this).html());
				jQnc(li).addClass(opt.currentClass);
			}
			ul.appendChild(li);
			jQnc(li)
			.mouseover(function(event) {
				hasfocus = 1;
				if (opt.debug) console.log('over on : '+this.id);
				jQuery(event.target, gVcontainer).addClass(opt.hoverClass);
			})
			.mouseout(function(event) {
				hasfocus = -1;
				if (opt.debug) console.log('out on : '+this.id);
				jQuery(event.target, gVcontainer).removeClass(opt.hoverClass);
			})
			.click(function(event) {
			  var fl = jQnc('li.'+opt.hoverClass, gVcontainer).get(0);
				if (opt.debug) console.log('click on :'+this.id);
				jQnc('li.'+opt.currentClass, gVcontainer).removeClass(opt.currentClass); 
				jQnc(this).addClass(opt.currentClass);
				setCurrent();
				//gVselect.change();
				gVselect.get(0).blur();
				hideMe();
			});
		});
		return ul;
	}
	
	
	
};
