/*!
 * 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)
 */
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 = {};
	opt.inputClass = options.inputClass || "selectbox";
	opt.containerClass = options.containerClass || "selectbox-wrapper";
	opt.hoverClass = options.hoverClass || "current";
	opt.currentClass = options.selectedClass || "selected";
	opt.debug = options.debug || false;
    opt.wrapper = options.wrapper || '';
    opt.callback = options.callback || false;

    var elm_id = selectobj.id;
	var active = 0;
	var inFocus = false;
	var hasfocus = 0;
	//jquery object for select element
	var $select = $(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);

    var root = opt.wrapper;

    function hideAll() {
        $('.boxOpen').removeClass('boxOpen');
        hasfocus = 0;
    }

    function toggleRoot(e) {
        var target = $(root).find('.selectbox-wrapper');

        if ($(root).hasClass('boxOpen')) {
            hideAll();
			if ($.browser.msie) {
				$('#relativeBox').css('position', 'relative');
			}

		} else {
            hideAll();
            $(root).addClass('boxOpen');
        }
    }

	init();

    function init() {
        var ul, val;

        window.onblur = hideAll;

        ul = document.createElement('ul');
		$select.children('option').each(function(i) {
			var li = document.createElement('li'), optVal = $(this).html(); optVal = optVal.replace('&amp;', '&');
            $(li).attr('id', $input.attr('id') + '_' + $(this).val()).html(optVal);

            if ($(this).is(':selected')) {
                $input.val(optVal).addClass(opt.currentClass);
			}

            if (i === $select.children('option').length - 1) {
                li.className = 'last';
            }

            $(ul).append(li);
		});

        function focusItem(e) {
			e.stopPropagation();
            e.preventDefault();

            $(this).siblings().removeClass(opt.currentClass);
            $(this).addClass(opt.currentClass);

            setCurrent();
            //$select.change();
            $select.get(0).blur();
            //toggleRoot();
        }

        $container.append(ul).find('li')
            .mouseover(function() {
				$(this).addClass(opt.hoverClass);
			})
			.mouseout(function() {
				$(this).removeClass(opt.hoverClass);
			})
            .focus(focusItem)
            .click(focusItem);

        if ($(root).find('option:selected').length) {
            val = $(root).find('option:selected').val();
            $('#_input_'+ val).addClass('selected');
        }
    }

    var inputVal = $('#myselectbox_input').val();
	$input
	.click(function(e){
		//for IE to display search dropdown in front of album tiles
		if ($.browser.msie) {
			$('div.albumList').removeClass('popOver');
	//for IE6 to display search dropdown in front of recommendation dropdown on home page and album sorter on artist page 
			if (e.target.id == "_input") {
				$('#selectViewWrapper, #relativeBox').css('position', 'relative');
			} else {
				$('#selectViewWrapper, #relativeBox').css('position', 'static');
			}
		}

		toggleRoot(e);
    })
	.blur(function(e){
         window.setTimeout(hideAll, 200);
		//setting album sorter on artist page back to relative positioning
		if ($.browser.msie) {
			window.setTimeout(function(){$('#relativeBox').css('position', 'relative')}, 200);
		}

	})
    .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
			  toggleRoot();
		      event.preventDefault(); //keeps IE from removing selected value
			  break;
		}
	});



	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 =  $container.find("li");
		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);

		$(lis).eq(active).addClass(opt.hoverClass);
	}

	function scroll(list, active) {
        var el = $(list[active]).get(0);
        var list = $container.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 = $container.find("li." + opt.currentClass).get(0);
		var ar = li.id.split('_');
		var el = ar[ar.length - 1];
		$select.val(el);

        if ($('li:last', $container).get(0) == li) {
            li.className = 'selected';
            $(li.previousSibling).addClass('last');
        } else {
            $container.find("li:last").addClass('last').siblings().removeClass('last');

        }

        var val = $(li).html();
        val = val.replace('&amp;', '&');

        $input.val(val);
		return true;
	}

	// select value
	function getCurrentSelected() {
		return $select.val();
	}

	// input value
	function getCurrentValue() {
		return $input.val();
	}
};

function runSelectbox() {
	if( $('#myselectbox').length > 0){
		$('#myselectbox').selectbox({
            wrapper     : '#search'
        });
	}
};

