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) {
        }
    }
}
/* */
var selectNum = 0;
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.selectedClass || "selected"
    opt.debug = opt.debug || false;

    var elm_id = selectobj.id;
    var active = 0;
    var inFocus = false;
    var hasfocus = 0;
    var $select = jQuery(selectobj);
    $select.hide();

    var $_width_css = (parseInt($select.css('width')) > 40) ? parseInt($select.css('width')):40 ;
    var $_select_width = ($_width_css ? $_width_css : $select.width());

    var $input = setupInput(opt);
    $select.after($input);

    var $container = setupContainer(opt);
    $input.after($container);
    
    $container.parent().css({
        'z-index':100 - selectNum
    });
    $container.parent().addClass('select_text_box');
    selectNum ++;
    
    init();

    $input
    .click(function(event){
        $container.toggle();
    })
    .focus(function(){

        })
    .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 !
                jQuery('li.'+opt.hoverClass).trigger('click');
                break;
            case 27: //escape
                hideMe();
                break;
        }
    })
    .blur(function(event) {
        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.safari){ // check for safari too - workaround for webkit
                if(document.activeElement.getAttribute('id') ==null || document.activeElement.getAttribute('id').indexOf('-container')==-1){//.indexOf('_container')==-1){
                    hideMe();
                } else {
                    $input.focus();
                }

            }
        }
    })
    ;

    function hideMe() {
        hasfocus = false;
        $container.hide();
    }

    function init() {
        $container.append(getSelectOptions($input.attr('id'))).hide();
        var width = $input.css('width');
    }

    function setupContainer(options) {
        var container = document.createElement("div");
        $container = jQuery(container);
        $container.attr('id', elm_id+'-container');
        var offset = $input.position();
        if (opt.debug) console.log('over on : '+ $input.width());
        $container.css({
            'left':offset.left+'px',
            'width':$_select_width + 'px'
        });
        $container.addClass(options.containerClass);
        
        return $container;
    }

    function setupInput(options) {
        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_width + 'px'
        });
        
        return $input;
    }

    function moveSelect(step) {
        var lis = jQuery("li", $container);
        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 = $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(li) {
        // var li=jQuery("li."+opt.currentClass, $container).get(0);
        var ar = li.id.split('-');
        var el = ar[ar.length-1];

        //$select.val($select.children('option').eq(el).attr('value'));
        $select.get(0).selectedIndex = el;
        $select.trigger('change');
		
        //linkage set
        linkageSet($select.attr('id'));

        getStrToInput(jQuery(li).html());
        
        return true;
    }

    function getStrToInput(value){
        value = jQuery.trim(value.replace(new RegExp('&nbsp;', 'g'), ' '));
        //add title
        if(value.replace(new RegExp('&nbsp;', 'g'), ' ').length>0){
            $input.attr('title', value.replace(new RegExp('&nbsp;', 'g'), ' '));
        }
        
        if(value.length * 6 > $_select_width-26){
            var strlen = parseInt(($_select_width-26)/6);
            var tmpDots = '';
            if(value.length > strlen)
                tmpDots = '...';
            $input.val(value.substring(0,strlen) + tmpDots);
        }else{
            $input.val(value);
        }
    }

    // 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');
        var rowNumber = 15;
        var rowHeight = 18;
        var subLiWidth = $_select_width;

        jQuery(ul).css('min-width',$_select_width);
        jQuery(ul).css('width',$_select_width);

        if($select.children('option').length>rowNumber){
            jQuery(ul).css({
                'overflow':'auto',
                'height': rowNumber * rowHeight +'px'
            });
            subLiWidth = subLiWidth - 17 ;
        }
        $select.children('option').each(function() {
            var li = document.createElement('li');
            li.setAttribute('id', parentid + '-' + $select.children('option').index(this));

            //add title
            var selectText=jQuery.trim(jQuery(this).html().replace(new RegExp('&nbsp;', 'g'), ' '));
            if(selectText.length>0){
                li.setAttribute('title', selectText);
            }
            
            li.innerHTML = selectText;
            if (jQuery(this).is(':selected')) {
            	
                getStrToInput(jQuery(this).html());
                jQuery(li).addClass(opt.currentClass);
            }
            jQuery(li).css('width',subLiWidth);
            ul.appendChild(li);
            
            jQuery(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 = jQuery('li.'+opt.hoverClass, $container).get(0);
                if (opt.debug) console.log('click on :'+this.id);
                jQuery('#' + elm_id + '-container' + ' li.'+opt.currentClass).removeClass(opt.currentClass);
				
                jQuery(this).addClass(opt.currentClass);
                setCurrent(this);
                $select.get(0).blur();
                hideMe();
            });
        });
        
        
        return ul;
    }

    function linkageSet(mainObjId){
        
		if(mainObjId == 'country'){
            removeSelect('#region_id');
            shippingRegionUpdater.update();
            removeSelect('#region_id');

            if(shippingRegionUpdater.regions[jQuery('#country').val()] === undefined){
                removeSelect('#region_id');
                jQuery('#region').show();
            }else{
                jQuery('#region').hide();
                jQuery('#region_id-container').remove();
                jQuery('#region_id').selectbox();
            }

        }else if(mainObjId == 'billing:country_id'){
			
			removeSelect('#billing\\:region_id');
            billingRegionUpdater.update();
            removeSelect('#billing\\:region_id');

            if(billingRegionUpdater.regions[jQuery('#billing\\:country_id').val()] === undefined){
                removeSelect('#billing\\:region_id');
                jQuery('#billing\\:region').show();
            }else{
				jQuery('#billing\\:region').hide();
                jQuery('#billing\\:region_id-container').remove();
                jQuery('#billing\\:region_id').selectbox();
            }
		}else if(mainObjId == 'shipping:country_id'){
			
			removeSelect('#shipping\\:region_id');
            shippingRegionUpdater.update();
            removeSelect('#shipping\\:region_id');

            if(shippingRegionUpdater.regions[jQuery('#shipping\\:country_id').val()] === undefined){
                removeSelect('#shipping\\:region_id');
                jQuery('#shipping\\:region').show();
            }else{
				jQuery('#shipping\\:region').hide();
                jQuery('#shipping\\:region_id-container').remove();
                jQuery('#shipping\\:region_id').selectbox();
            }
        }else if(mainObjId.indexOf("attribute")>=0){
			var attributeId = parseInt(mainObjId.replace(/[a-z]*/, ''));
			var nextAttrId=attributeId+1;
			var newObjId="attribute"+nextAttrId;
			
			removeSelect('#'+newObjId);
			spConfig.configureElement($(mainObjId));
			jQuery('#'+newObjId).selectbox();
			
		}
    }
};

function removeSelect(selectid){
    if(jQuery(selectid + '-input')){
        jQuery(selectid + '-input').hide();
        jQuery(selectid + '-input').remove();
    }
    if(jQuery(selectid + '-container')){
        jQuery(selectid + '-container').remove();
    }
}
