/*
 * 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: $Id$
 * Version: 1.2
 * 
 * Changelog :
 *  Version 1.2 By Guillaume Vergnolle (web-opensource.com)
 *  - Add optgroup support
 *  - possibility to choose between span or input as replacement of the select box
 *  - support for jquery change event
 *  - add a max height option for drop down list
 *  Version 1.1 
 *  - Fix IE bug
 *  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
 *---- EDITED AND ADDED TEXTFIELD STYLING SUPPORT!!
 */
 
 
jQuery.fn.extend({
	//for styling selectboxes
	selectbox: function(options) {
		return this.each(function() {
			new jQuery.SelectBox(this, options);
		});
	},
	//for styling textFields
	textfield: function(options) {
		return this.each(function() {
			new jQuery.TextField(this, options);
		});
	}
});

/* pawel maziarz: work around for ie logging */
if (!window.console) {
	var console = {
		log: function(msg) { 
	 	}
	}
}
/* */
	
//TextField Styling
jQuery.TextField = function(selectobj, options) {
	var i = $(selectobj);
	i.addClass("textBoxStyled").after("<span class='textBoxRight'></span>").wrap('<span class="textBox"></span>');
};

jQuery.SelectBox = function(selectobj, options) {
	var opt = options || {};
	opt.inputType = opt.inputType || "input";
	opt.wrapSpan = opt.wrapSpan || "styledSelect";
	opt.inputClass = opt.inputClass || "selectbox";
	opt.containerClass = opt.containerClass || "selectbox-wrapper";
	opt.hoverClass = opt.hoverClass || "current";
	opt.currentClass = opt.currentClass || "selected";
	opt.groupClass = opt.groupClass || "groupname"; //css class for group
	opt.maxHeight = opt.maxHeight || 127; // max height of dropdown list
	opt.loopnoStep = opt.loopnoStep || false; // to remove the step in list moves loop
	opt.onChangeCallback = opt.onChangeCallback || false;
	opt.onChangeParams = opt.onChangeParams || false;
	opt.debug = opt.debug || false;
	
	var cmlThat = selectobj;
	
	var elm_id = selectobj.id;
	//alert($(this).get().attr("class"));
	var active = 0;
	var inFocus = false;
	var hasfocus = 0;
	//jquery object for select element
	var $select = jQuery(selectobj);
	// jquery container object
	var $container = setupContainer(opt);
	//jquery input object 
	var $input = setupInput(opt);
	// hide select and append newly created elements
	$select.hide().before($input).before($container);
	
	$input.after('<span class="selectBoxLeft"></span>').wrap("<span class='"+opt.wrapSpan+"'></span>");
	init();
	
	
	
	function cmlkeyPress($input,th)
	{
		$(th).unbind('keydown');
		$(th).bind('keydown',function(e){
		
			e.stopPropagation();
			
			var code = (e.keyCode ? e.keyCode : e.which);
			if( code!=9 ) e.preventDefault();
		
			switch( code ){
			case 38: // up
				
				moveSelect(-1);
				return false;
				break;
			case 40: // down
				
				moveSelect(1);
				return false;
				break;
			//case 9:  // tab 
			case 13: // return
				
				$('li.'+(opt.hoverClass-1)).trigger('click');
				return false;
				break;
			case 27: //escape
			  hideMe();
			  return false;
			  break;
			 }
			
			
			var k = String.fromCharCode(code);
			
			k = k.toUpperCase();
			
			var ll = $(cmlThat).children('option').length;
			var psh=[];
			var sel=-1;
			var t=0;
			for(var i=0;i<ll;i++)
			{	
				var thi = $(cmlThat).children('option:eq('+i+')');
				var l =($(thi).val()).substr(0,1);
				
				if(l!=undefined)
				{
					if(l.toUpperCase()==k)
					{
						if( thi.attr('selected') ) sel = t;
						psh.push(thi);
						t++;
						
					}
				}
			}
			
			for(var i=0,ll=psh.length;i<ll;i++)
			{
				if(sel>=0 && sel<(ll-1))
				{
					
					//var mid = '#'+$(cmlThat).attr("id")+'_input_'+psh[(sel+1)].val();
					var mid = psh[(sel+1)].index();
					$('li:eq('+(mid)+')',$container).trigger('click');

					break;
				}
				else
				{
					//var mid = '#'+$(cmlThat).attr("id")+'_input_'+psh[0].val();
					var mid = psh[0].index();
					$('li:eq('+(mid)+')',$container).trigger('click');
					break;
				}
			}
			
		});
	}
	
	//$input.parent().parent().children(".selectBoxLeft").click(function(){ $(this).prev("span").children("input").trigger('click');});
	
	
	$input.parent().find('input').focus(function(){
		//	if ($container.not(':visible')) {
		//	inFocus = true;
		//	$container.show();
		//}
		
			cmlkeyPress($input,this);
	});
	
	$input.parent().parent().children("span:not(.selectbox-wrapper)").click(function(){
		//if(!hasfocus){
			hasfocus = 1;
			$container.show();
			$input.parent().find('input').trigger('focus');
			cmlkeyPress($input,this);
		//}
	})
	.parent().parent().focus(function(){
		if ($container.not(':visible')) {
			inFocus = true;
			//$container.show();
			
			cmlkeyPress($input,this);
		}
	})
	.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 !
				$('li.'+opt.hoverClass).trigger('click');
				break;
			case 27: //escape
			  hideMe();
			  break;
		}*/
	})
	.mouseleave(function() { 
		hideMe();
	/*	if ($container.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 {
					$input.parent().focus();
				}
			} else {
				hideMe();
			}
		}*/
	});

	function hideMe() { 
		hasfocus = 0;
		$container.hide(); 
	}
	
	function init() {
		$container.append(getSelectOptions($input.attr('id'))).hide();
		$container.children("ul").wrap("<div class='ul' style='height:"+$container.height()+" px'></div>");
		var width = $input.width()-1+ $input.parent().parent().children(".selectBoxLeft").width();
		if($container.height() > opt.maxHeight){
			$container.width(width +"px");
			//$container.width(parseInt(width)+parseInt($input.css('paddingRight'))+parseInt($input.css('paddingLeft')));
			$container.height(opt.maxHeight);
		} else $container.width(width +"px");
		
		if ($.browser.msie && ($.browser.version <= "6.0")){
				if($container.parent().hasClass("dropdown")==true)
				$container.css("left", ((width)*(-1)-4) +"px");
		}
	}
	
	function setupContainer(options) {
		var container = document.createElement("div");
		$container = jQuery(container);
		$container.attr('id', elm_id+'_container');
		$container.addClass(options.containerClass);
        $container.css('display', 'none');
		
		return $container;
	}
	
	function setupInput(options) {
		if(opt.inputType == "span"){
			var input = document.createElement("span");
			var $input = jQuery(input);
			$input.attr("id", elm_id+"_input");
			$input.addClass(options.inputClass);
			$input.attr("tabIndex", $select.attr("tabindex"));
		} else {
			var input = document.createElement("input");
			var $input = jQuery(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
			$input.css("width", $select.css("width"));
        	}
		return $input;	
	}
	
	function moveSelect(step) {
		var lis = jQuery("li", $container);
		if (!lis || lis.length == 0) return false;
		// find the first non-group (first option)
		firstchoice = 0;
		
		while($(lis[firstchoice]).hasClass(opt.groupClass)) firstchoice++;
		active += step;
    		// if we are on a group step one more time
    		if($(lis[active]).hasClass(opt.groupClass)) active += step;
		//loop through list from the first possible option
		if (active < firstchoice) {
			(opt.loopnoStep ? active = lis.size()-1 : active = lis.size() );
		} else if (opt.loopnoStep && active > lis.size()-1) {
			active = firstchoice;
		} else if (active > lis.size()) {
			active = firstchoice;
		}
		$('li.'+opt.hoverClass).trigger('click');
		//if( active<0 ) return false;
        	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 = $container.get(0);
      
		if(!el){return 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, $container).get(0);
		var ar = (''+li.id).split('_');
		var el = ar[ar.length-1];
		if (opt.onChangeCallback){
        		$select.get(0).selectedIndex = $('li', $container).index(li);
        		opt.onChangeParams = { selectedVal : $select.val() };
			opt.onChangeCallback(opt.onChangeParams);
		} else {
			$select.val(el);
			$select.change();
		}
		if(opt.inputType == 'span') $input.html($(li).html());
		else $input.val($(li).html());
		return true;
	}
	
	// select value
	function getCurrentSelected() {
		return $select.val();
	}
	
	// input value
	function getCurrentValue() {
		return $input.val();
	}
	
	function getSelectOptions(parentid) {
		var select_options = new Array();
		var ul = document.createElement('ul');
		select_options = $select.children('option');
		if(select_options.length == 0) {
			var select_optgroups = new Array();
			select_optgroups = $select.children('optgroup');
			for(x=0;x<select_optgroups.length;x++){
				select_options = $("#"+select_optgroups[x].id).children('option');
				var li = document.createElement('li');
				li.setAttribute('id', parentid + '_' + $(this).val());
				li.innerHTML = $("#"+select_optgroups[x].id).attr('label');
				li.className = opt.groupClass;
				ul.appendChild(li);
				select_options.each(function() {
					var li = document.createElement('li');
					li.setAttribute('id', parentid + '_' + $(this).val());
					li.innerHTML = $(this).html();
					if ($(this).is(':selected')) {
						$input.html($(this).html());
						$(li).addClass(opt.currentClass);
					}
					ul.appendChild(li);
					$(li)
					.mouseover(function(event) {
						hasfocus = 1;
						if (opt.debug) console.log('over on : '+this.id);
						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) {
						var fl = $('li.'+opt.hoverClass, $container).get(0);
						if (opt.debug) console.log('click on :'+this.id);
						$('li.'+opt.currentClass, $container).removeClass(opt.currentClass); 
						$(this).addClass(opt.currentClass);
						setCurrent();
						$select.get(0).blur();
						hideMe();
					});
				});
			}
		} else select_options.each(function() {
			var li = document.createElement('li');
			li.setAttribute('id', parentid + '_' + $(this).val());
			li.innerHTML = $(this).html();
			if ($(this).is(':selected')) {
				$input.val($(this).html());
				$(li).addClass(opt.currentClass);
			}
			ul.appendChild(li);
			$(li)
			.mouseover(function(event) {
				hasfocus = 1;
				if (opt.debug) console.log('over on : '+this.id);
				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) { 
			  	var fl = $('li.'+opt.hoverClass, $container).get(0);
				if (opt.debug) console.log('click on :'+this.id);
				$('li.'+opt.currentClass, $container).removeClass(opt.currentClass); 
				$(this).addClass(opt.currentClass);
				setCurrent();
				$select.get(0).blur();
				hideMe();
			});
		});
		return ul;
	}
};





jQuery.fn.numeric = function(decimal, callback)
{
	decimal = decimal || ".";
	callback = typeof callback == "function" ? callback : function(){};
	this.keypress(
		function(e)
		{
			var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
			// allow enter/return key (only when in an input box)
			if(key == 13 && this.nodeName.toLowerCase() == "input")
			{
				return true;
			}
			else if(key == 13)
			{
				return false;
			}
			var allow = false;
			// allow Ctrl+A
			if((e.ctrlKey && key == 97 /* firefox */) || (e.ctrlKey && key == 65) /* opera */) return true;
			// allow Ctrl+X (cut)
			if((e.ctrlKey && key == 120 /* firefox */) || (e.ctrlKey && key == 88) /* opera */) return true;
			// allow Ctrl+C (copy)
			if((e.ctrlKey && key == 99 /* firefox */) || (e.ctrlKey && key == 67) /* opera */) return true;
			// allow Ctrl+Z (undo)
			if((e.ctrlKey && key == 122 /* firefox */) || (e.ctrlKey && key == 90) /* opera */) return true;
			// allow or deny Ctrl+V (paste), Shift+Ins
			if((e.ctrlKey && key == 118 /* firefox */) || (e.ctrlKey && key == 86) /* opera */
			|| (e.shiftKey && key == 45)) return true;
			// if a number was not pressed
			if(key < 48 || key > 57)
			{
				/* '-' only allowed at start */
				if(key == 45 && this.value.length == 0) return true;
				/* only one decimal separator allowed */
				if((key == decimal.charCodeAt(0) && this.value.indexOf(decimal) != -1) || (key == ",".charCodeAt(0) && this.value.indexOf(",") != -1))
				{
					allow = false;
				}
				
				// check for other keys that have special purposes
				if(
					key != 8 /* backspace */ &&
					key != 9 /* tab */ &&
					key != 13 /* enter */ &&
					key != 35 /* end */ &&
					key != 36 /* home */ &&
					key != 37 /* left */ &&
					key != 39 /* right */ &&
					key != 46 /* del */
				)
				{
					allow = false;
				}
				else
				{
					// for detecting special keys (listed above)
					// IE does not support 'charCode' and ignores them in keypress anyway
					if(typeof e.charCode != "undefined")
					{
						// special keys have 'keyCode' and 'which' the same (e.g. backspace)
						if(e.keyCode == e.which && e.which != 0)
						{
							allow = true;
						}
						// or keyCode != 0 and 'charCode'/'which' = 0
						else if(e.keyCode != 0 && e.charCode == 0 && e.which == 0)
						{
							allow = true;
						}
					}
				}
				// if key pressed is the decimal and it is not already in the field    && this.value.indexOf(decimal) == -1) || (key == ",".charCodeAt(0) && this.value.indexOf(",") == -1))
				if(  (key == decimal.charCodeAt(0) || key == ",".charCodeAt(0) )  && ( this.value.indexOf(decimal) == -1 && this.value.indexOf(",") == -1 )    )
				{
					allow = true;
				}
			}
			else
			{
				allow = true;
			}
			return allow;
		}
	)
	.blur(
		function()
		{
			var val = jQuery(this).val();
			if(val != "")
			{
				var re = new RegExp("^\\d+$|\\d*" + decimal + "| , \\d+");
				if(!re.exec(val))
				{
					callback.apply(this);
				}
			}
		}
	);
	return this;
}

jQuery.fn.rollover = function(direction)
{
	var overflag;
	var i = $(this);
	var t = $(".hoverShow", "#tooltipContainer");
	i.hover(function(event){
		var i = $(this);
		var myoff = i.offset();
		//if(i.children("span").hasClass("remanufactured")==true)
		//{
		//	t = $(".hoverShow.remanufactured");
		//}
		//else if(i.children("span").hasClass("used")==true){
		//	t = $(".hoverShow.used"); }
		//t = $(".hoverShow");
		//t.appendTo(i);
		if(direction=="right")
			t.css({"margin-left": 0,"top":myoff.top,"left":myoff.left+(i.outerWidth()-10)}).stop(true,true).fadeIn(100);		 
		if(direction=="left")
		{
			t.css({"margin-left":($(this).width()-8),"left": (-1)*i.parent().outerWidth()-3 }).stop(true,true).fadeIn(100);
		}
		if(direction=="bottom")
		{
			t.css({"margin-left":($(this).width()-8)*(-1),"left": (myoff.left+(-1)*(i.width()/2)),"top":(myoff.top+(i.outerHeight()-5)) }).stop(true,true).fadeIn(100);
		}
		//t = i.children('.hoverShow');
	},
	function(event){
		//alert( $(event.originalEvent.srcElement).attr("class") );
				t.stop(true,true).fadeOut(100);	
	});
}

jQuery.fn.bulletize = function(){
	var i = $(this);
	var count = i.children(".item").length;
	var kept = count;
	i.append('<div class="bulletLinks"></div>');
	i.children(".item:eq(0)").addClass("active");
	while((count--)>0)
		i.children('.bulletLinks').append('<a href="javascript:void(0)" class="bullet">'+(count+1)+'</a>');	

	i.find("a.bullet:last").addClass("active");
	i.find("a.bullet").click( function(){
		if($(this).hasClass('active')==true) return 0;
		$(this).addClass('active').siblings('a.bullet').removeClass('active');	
		var myIndex = kept-$(this).index()-1;
		
		$(this).parent().siblings(".active").fadeOut(300).removeClass('active').parent().children(".item:eq("+(myIndex)+")").fadeIn(400).addClass("active");
		
	});
}
