jQuery(document).ready(function() {
    jQuery(document).click( closeAllComboBox );
    jQuery(document).keydown( keyOnComboBox );
});

// Count of items before scrolling turning ON
var itemsPerScroll = 15;
var qtyOpenSelects = 0;

function createComboFromSelect(selectBox, callBack) {
    // Select selectBox from doc & hide it:
    selectBox = jQuery('#'+selectBox); selectBox.hide();

    var selBoxId        = selectBox.get(0).id;
    var stdSelected     = selectBox.get(0).options[selectBox.get(0).selectedIndex].text;

    // Creating combo layer:
    var layer = jQuery('<div id="combo-'+selBoxId+'" class="comboBox-layer">').insertAfter(selectBox);

    // Creating div:
    var text  = jQuery('<div class="comboBox-text">' + stdSelected + '</div>').appendTo(layer);

    // Creating drop down arrow:
    var arrow = jQuery('<div class="comboBox-arrow">').appendTo(layer);

    // Creating drop down list:
    var dlist = jQuery('<div class="comboBox-list">').appendTo(layer).css('display', 'none');

    // Setting the select id to combo layer 4 ! keep in mind:
    layer.attr('selId', selBoxId);
    
    // Creating options & option events:
	var elem = selectBox.get(0).getElementsByTagName("*");
    for(var i=0; i<elem.length; i++){
		if(elem[i].getAttribute("label")){
			jQuery('<div class="comboBox-group-item">').appendTo(dlist).html(elem[i].getAttribute("label"));
		}else{
			jQuery('<div class="comboBox-item">').appendTo(dlist).html(elem[i].text).attr('location',elem[i].value).click(function()
		{
		        text.html(jQuery(this).html());
		        closeAllComboBox();
		        if(text.html() != '') {
		            jQuery('option', selectBox).selected = false;
//		            jQuery('option:contains("'+text.html()+'")', selectBox).get(0).selected = true;
                    jQuery('option', selectBox).each( function () {
                        if (this.innerHTML == text.html()) {
                            this.selected = true;
                        }
                    });

					if(callBack && jQuery.trim($j(this).attr('location')).length > 0) callBack($j(this).attr('location'));
		        }
		    }).mouseover(function() {
		        jQuery('#combo-'+selBoxId+' .comboBox-item-sel').attr('class', 'comboBox-item');
		        jQuery(this).attr('class', 'comboBox-item-sel');
		    });
		}
	}
	
    
    setComboBoxHeight(selectBox, dlist);

    // Binding click event to arrow image:
    arrow.click(function(e) {
        if( dlist.css('display') == 'none' ) {
            openCurComboBox(arrow, dlist, text.html(), true);
            killEventHandlers(e);
        }
        else closeAllComboBox();
    });
    text.click( function(e) { arrow.click(); killEventHandlers(e); } );
}

function setComboBoxHeight(selectBox, dlist) {
    if( selectBox.get(0).options.length < itemsPerScroll ) dlist.css('height', (selectBox.get(0).options.length * 16) + 'px');
    else dlist.css('height', (itemsPerScroll * 16) + 'px');
}

function deleteOptionsFromCombo(selectBox) {
    argLength  = deleteOptionsFromCombo.arguments.length;
    argContent = deleteOptionsFromCombo.arguments;
    if( argLength < 2 ) return false;
    
    var selectBox = jQuery( '#'+selectBox );
    var layer = jQuery( 'div#combo-'+selectBox.get(0).id );
    
    for(var i=1; i<argLength; i++) {
//        jQuery('.comboBox-item:contains("'+argContent[i]+'")', layer).remove();
        jQuery('.comboBox-item', layer).each( function() {
            if (jQuery(this).html() == argContent[i]) jQuery(this).remove();
        });
//        jQuery('option:contains("'+argContent[i]+'")', selectBox).remove();
        jQuery('option', selectBox).each( function() {
            if (jQuery(this).html() == argContent[i]) jQuery(this).remove();
        });
    }

    var dlist = jQuery('.comboBox-list', layer);
    setComboBoxHeight(selectBox, dlist);

    selectBoxIEfix( selectBox );
}

function leaveOptionsInCombo(selectBox) {
    argLength  = leaveOptionsInCombo.arguments.length;
    argContent = leaveOptionsInCombo.arguments;
    if( argLength < 2 ) return false;

    var selectBox = jQuery( '#'+selectBox );
    var options = jQuery('option', selectBox);
    var layer = jQuery( 'div#combo-'+selectBox.get(0).id );

    for(var i=0; i<options.length; i++) {
        if( !isInArray(argContent, options.eq(i).text()) ) {
            options.eq(i).remove();
//            jQuery('.comboBox-item:contains("'+options.eq(i).text()+'")', layer).remove();
            jQuery('.comboBox-item', layer).each( function () {
                if (this.text == options.eq(i).text()) jQuery(this).remove();
            });
        }
    }

    var dlist = jQuery('.comboBox-list', layer);
    setComboBoxHeight(selectBox, dlist);

    selectBoxIEfix( selectBox );
}

function selectBoxIEfix(selectBox) {
    // reset display status of selectBox in IE
    if( jQuery.browser.msie ) {
        selectBox.css('display', '');
        selectBox.css('display', 'none');
    }
}

function isInArray(arr, text) {
    var inArray = false;
    for(var i=0; i<arr.length; i++) {
        if( arr[i] != Object && arr[i] == text ) {
            inArray = true;
            break;
        }
    }
    return inArray;
}

function openCurComboBox(arrow, dlist, textVal, chSel) {
    qtyOpenSelects++;
    dlist.css('display', '');
    arrow.attr('class', 'comboBox-arrow-down');
    if(chSel) {
        jQuery('.comboBox-item-sel', dlist.parent()).attr('class', 'comboBox-item');
        if( textVal != undefined) {
//            jQuery('.comboBox-item:contains("'+textVal+'")', dlist.parent()).attr('class', 'comboBox-item-sel');
            jQuery('.comboBox-item', dlist.parent()).each( function () {
                if (this.innerHTML == textVal) jQuery(this).attr('class', 'comboBox-item-sel');
            });
        }
        else {
            jQuery('.comboBox-item', dlist.parent()).eq(0).attr('class', 'comboBox-item-sel');
        };
        scrollDList(dlist);
    }
}

function closeAllComboBox() {
    qtyOpenSelects=0;
    jQuery('.comboBox-layer .comboBox-list:visible').css('display', 'none');
    jQuery('.comboBox-layer .comboBox-arrow-down').attr('class', 'comboBox-arrow');
}

function scrollDList(dlist) {
    var items = jQuery('div', dlist);
    var item  = jQuery('.comboBox-item-sel', dlist);
    var itemPos = 0;
    for(var i=0; i<items.size(); i++)
    if( items.get(i).innerHTML == item.html() ) itemPos = i;
    dlist.get(0).scrollTop = 11*itemPos-33;
}

function keyOnComboBox(e) {

    if (qtyOpenSelects == 0) 
       return;

    var dlist = jQuery('.comboBox-layer .comboBox-list:visible');
    var arrow = jQuery('.comboBox-layer .comboBox-arrow-down');
    var elem  = jQuery('.comboBox-item-sel', dlist);
    var selectBox = jQuery( '#'+dlist.parent().attr('selId') );
    
    var text  = jQuery('.comboBox-layer:has(.comboBox-arrow-down) div.comboBox-text');
    
    // Check is this autocompleter or comboBox
    var autocomplete = false;
    if( text.size() < 1 ) {
        autocomplete = true;
        text = jQuery('.comboBox-layer:has(.comboBox-arrow-down) input');
    }
    
    // If exists opened comboBoxes - catching keyboard shortcuts:
    if( dlist.length > 0 ) {
    switch( e.keyCode ) {
        case 38:
            // If pressed UP button, then move selection up:
            if( elem.length > 0 && elem.prev().length > 0) {
                elem.attr('class', 'comboBox-item');
                elem.prev().attr('class', 'comboBox-item-sel');
            }
            else {
                elem.attr('class', 'comboBox-item');
                jQuery('.comboBox-item:first', dlist).attr('class', 'comboBox-item-sel');
            }
            scrollDList(dlist);
            killEventHandlers(e);
            break;
        case 40:
            // If pressed DOWN button, then move selection up:
            if( elem.length > 0 && elem.next().length > 0) {
                elem.attr('class', 'comboBox-item');
                elem.next().attr('class', 'comboBox-item-sel');
            }
            else {
                elem.attr('class', 'comboBox-item');
                jQuery('.comboBox-item:last', dlist).attr('class', 'comboBox-item-sel');
            }
            scrollDList(dlist);
            killEventHandlers(e);
            break;
        case 13:
            // If pressed ENTER button, then move selects option & close drop down:
            if( autocomplete )
                text.attr('value', elem.text());
            else
                text.html( elem.text() );
            jQuery('option', selectBox).selected = false;
//            jQuery('option:contains("'+elem.text()+'")', selectBox).get(0).selected = true;
            jQuery('option', selectBox).each( function () {
                if (this.text == elem.text()) this.selected = true;
            });

            dlist.css('display', 'none');
            arrow.attr('class', 'comboBox-arrow');
            killEventHandlers(e);
            break;
        case 27:
            // If pressed ESC button, then just close drop down:
            dlist.css('display', 'none');
            arrow.attr('class', 'comboBox-arrow');
            killEventHandlers(e);
            break;
    }
    }
}

function killEventHandlers(e) {
    if(e && e.preventDefault)
        e.preventDefault();
    else if(window.event)
        window.event.returnValue=false;
    e.stopPropagation();
}
