/* 
 * Multiselect - Emad Messiha
 */
var multiSelectShown = false;
var mouseOnMultiSelect = false;

jQuery(function(){

    jQuery('#' + MULTISELECT_OUTPUT).attr('name',MULTISELECT_OUTPUT);
    
    window.onclick = function(){
        if(multiSelectShown && !mouseOnMultiSelect){
            jQuery('#' + MULTISELECT_ID).hide();
            multiSelectShown = false;
        }
    };

    jQuery('#' + MULTISELECT_ID + ',#' + MULTISELECT_ID + '_button').mouseover(function(){
        mouseOnMultiSelect = true;
    });
    jQuery('#' + MULTISELECT_ID + ',#' + MULTISELECT_ID + '_button').mouseout(function(){
        mouseOnMultiSelect = false;
    });

    jQuery('#' + MULTISELECT_ID + '_button').attr('innerHTML',MULTISELECT_NO_SELECTION);
    jQuery('#' + MULTISELECT_ID + '_button').show();
    jQuery('#' + MULTISELECT_ID + '_button').click(function(){
        if(multiSelectShown)
        {
            jQuery('#' + MULTISELECT_ID).hide();
            multiSelectShown = false;
        }
        else
        {
            jQuery('#' + MULTISELECT_ID).show();
            multiSelectShown = true;
        }
    });

    jQuery('input[type=checkbox]','#' + MULTISELECT_ID).click(function(){
       

        if(this.id == MULTISELECT_ALL_ID)
        {
            if(jQuery('#' + MULTISELECT_ALL_ID).attr('checked'))
            {
                jQuery('input[type=checkbox]','#' + MULTISELECT_ID).attr('checked',true);
            }
            else
            {
                jQuery('input[type=checkbox]','#' + MULTISELECT_ID).attr('checked',false);
            }
        }
    
        checkSelected();
    });

    checkSelected();
});

function checkSelected()
{
    var selectedItems = new Array();
    var selectedItemsText = new Array();

    jQuery('input[type=checkbox]','#' + MULTISELECT_ID).each(function(){

        if(this.id != MULTISELECT_ALL_ID)
        {
            if(jQuery(this).attr('checked'))
            {
                selectedItems.push(jQuery(this).val());
                selectedItemsText.push(jQuery(this).attr('title'));
            }
        }
    });

    jQuery('#' + MULTISELECT_OUTPUT).val(selectedItems.join(','));
    jQuery('#' + MULTISELECT_ID + '_button').attr('title',selectedItemsText.join(MULTISELECT_SEPERATOR));
    if(selectedItems.length)
    {
        jQuery('#' + MULTISELECT_ID + '_button').attr('innerHTML',selectedItems.length + MULTISELECT_SELECTED);
    }
    else
    {
        jQuery('#' + MULTISELECT_ID + '_button').attr('innerHTML',MULTISELECT_NO_SELECTION);
    }

    if(selectedItems.length + 1 == jQuery('input[type=checkbox]','#' + MULTISELECT_ID).length)
    {
        jQuery('#' + MULTISELECT_ALL_ID).attr('checked',true);
    }
    else
    {
        jQuery('#' + MULTISELECT_ALL_ID).attr('checked',false);
    }
}
