/* Copyright (c) 2009  Octave & Octave http://www.octaveoctave.com
 * Licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * Copyright notice and license must remain intact for legal use
 * nicyform 1.0
 * Version: 1.0 (June 1, 2009)
 * Requires: jQuery 1.3+
 */

(function($) {

    $.fn.nicyform = function(options) {

        var opts = $.extend({}, $.fn.nicyform.defaults, options);
        var selectItem = opts.title;
        var container = $(this)
        

        function create() { 
            
            /* ---------------------------------------------------------------------------- /
             * MULTISELECT */
                
            if(opts.type=="multiselect")
            {
                // init
                var originalElement = $(this);
                var nicyElement = $('<div class="nicy-multiselect"></div>');
                var nicySelectedContainer = $('<div class="selectedContainer"></div>');
                var nicySelectedActions = $('<div class="actions"><span class="count"></span><a href="#" class="remove-all">Remove All</a></div>');
                var nicySelectedList = $('<ul class="selectedList"></ul>');
                var nicyAvailableContainer = $('<div class="availableContainer">');
                var nicyAvailableActions = $('<div class="actions"><input type="text" class="search" name="multiselect-search" value="" /><a href="#" class="add-all">Add All</a></div>');
                var nicyAvailableList = $('<ul class="availableList"></ul>');
                var nbSelected = 0;
                
                function updateCount(nicyElement, nbSelected) {
                    if(nbSelected <= 1) {
                        $(nicyElement).find('.count').empty().append(nbSelected+' item selected');
                        if(nbSelected==0) {
                            $(nicyElement).prev().find('option[value=]').attr('selected','selected');
                        }
                    }
                    else $(nicyElement).find('.count').empty().append(nbSelected+' items selected');
                }       
                        
                // generate
                $(originalElement).find('option:selected').not('[value=]').each(function() {
                    $(nicySelectedList).append('<li><a href="#" rel="'+$(this).val()+'"><span class="icon"></span>'+$(this).text()+'</a></li>');
                    nbSelected = nbSelected + 1;
                });             
                
                updateCount(nicySelectedActions, nbSelected);           
                
                $(originalElement).find('option').not(':selected').not('[value=]').each(function() {
                    $(nicyAvailableList).append('<li><a href="#" rel="'+$(this).val()+'"><span class="icon"></span>'+$(this).text()+'</a></li>');
                });
                
                // displaying
                $(originalElement).hide();
                $(nicySelectedContainer)
                    .append(nicySelectedActions)
                    .append(nicySelectedList);
                $(nicyAvailableContainer)
                    .append(nicyAvailableActions)
                    .append(nicyAvailableList);
                $(nicyElement)
                    .append(nicySelectedContainer)
                    .append(nicyAvailableContainer)
                    .insertAfter(originalElement);  
                    
                // events
                $(nicyElement).find('li a').bind('click', function() {
                    if($(this).parent().parent().hasClass('availableList')) {
                        $(this).parent().prependTo(nicySelectedList); 
                        $(originalElement).find('option[value='+$(this).attr('rel')+']').attr("selected", "selected");
                        nbSelected = nbSelected + 1; 
                    }
                    else
                    {
                        $(this).parent().prependTo(nicyAvailableList);
                        $(originalElement).find('option[value='+$(this).attr('rel')+']').removeAttr("selected");
                        nbSelected = nbSelected - 1;
                    }
                    updateCount(nicyElement, nbSelected);
                    return false;
                });
                
                $(nicyElement).find('.add-all').bind('click', function() {
                    $(nicyAvailableList).find('li').each(function() {
                        $(nicySelectedList).append(this);
                        $(originalElement).find('option[value='+$(this).find('a').attr('rel')+']').attr("selected", "selected");
                        nbSelected = nbSelected + 1;
                    }); 
                    updateCount(nicyElement, nbSelected);
                    return false;
                });                 
                
                $(nicyElement).find('.remove-all').bind('click', function() {
                    $(nicySelectedList).find('li').each(function() {
                        $(nicyAvailableList).append(this);
                        $(originalElement).find('option[value='+$(this).find('a').attr('rel')+']').removeAttr("selected");
                        nbSelected = 0;
                    }); 
                    updateCount(nicyElement, nbSelected);
                    return false;
                });
                
                // taken from John Resig's liveUpdate script
                $(nicyElement).find('.search').bind('keyup', function() {
                    var input = $(this);
                    var rows = nicyAvailableList.children('li'),
                        cache = rows.map(function(){
                            return $(this).text().toLowerCase();
                        });
                    var term = $.trim(input.val().toLowerCase()), scores = [];
                    if (!term) {
                        rows.show();
                    } else {
                        rows.hide();
                        cache.each(function(i) {
                            if (this.indexOf(term)>-1) { scores.push(i); }
                        });
                        $.each(scores, function() {
                            $(rows[this]).show();
                        });
                    }
                });             
            }
                        
            
            /* ---------------------------------------------------------------------------- /
             * BOUTON */
                
            if(opts.type=="button")
            {
                var button = $(this);
                opts.title =  $(button).val();
                
                var link = '<a href="#" class="btn ' + opts.shape + '"><span class="btn-style';
                if(opts.bgcolor) { link = link + ' btn-bg-' + opts.bgcolor; }
                if(opts.txtcolor) { link = link + ' btn-txt-' + opts.txtcolor; }
                if(opts.iconcolor) { link = link + ' btn-icon-' + opts.iconcolor; }
                link = link + '" style="' + $(button).attr('style') + '">';
                if(opts.icon)
                {
                    link = link + '<span class="btn-icon ' + opts.icon + '">'
                    if(opts.notext)
                    {
                        link = link + opts.title;
                    }
                    else
                    {
                        link = link + '</span> ' + opts.title;
                    }                   
                }
                else
                {
                    link = link + opts.title;
                }
                link = link + '</span></a>';
                link = $(link);
                
                link.bind('click', function() {
                    $(button).click();
                    return false;
                });
                
                $(button).hide().after(link);   
            }
                        
            /* ---------------------------------------------------------------------------- /
             * BOUTON ON-OFF */
                
            else if(opts.type=="boolean")
            {
            
                var selectItem = $(this).find('option:selected').val()
                if($(this).attr('selected')){
                    selectItem = $(this).attr('selected')
                }

                var select = $('<span class="switch-' + selectItem + '">' + selectItem + '</span>');
                
                
                // events click     
                select.bind("click", function(){
                        if($(this).hasClass('switch-1'))
                        {
                            $(this).removeClass('switch-1').addClass('switch-0').empty().append('Offline');
                            $(this).prev().find('option[value=0]').attr('selected', 'selected');
                        }
                        else
                        {
                            $(this).removeClass('switch-0').addClass('switch-1').empty().append('Online');
                            $(this).prev().find('option[value=1]').attr('selected', 'selected');                                
                        }
                        if(opts.onChange)
                            { 
                            opts.onChange($(this).prev()) 
                            }
                    });             

                $(this).hide().after(select);
                    
            }
            
            
            /* ---------------------------------------------------------------------------- /
             * BOUTON AJOUT D'ITEMS */
                            
            else if(opts.type=="new-item")
            {
                var button = $(this);

                $(this).bind("click", function() {

                    var type = $(this).attr('rel');
                    $(this).hide().before('<input type="text" name="newItem" class="text-mini" value="" style="float:left; margin-right:10px"/> <a class="btn new-item-submit" href="#" onclick="return false;"><span class="style">Add</span></a>')
                        

                    $('.new-item-submit').bind("click", function() { 
                        var msg = 'OK';
                
                        if(opts.onChange)
                            { 
                                var response = opts.onChange($(this).parent().find('input'), 'add') 
                            }
                        
                        if(response.msg == 'OK')
                        {

                            if(type=="checkbox")
                            {
                                var newItem = $(this).parent().parent().find('ul').append('<li><input class="check" value="" name="'+ opts.title +'-'+ response.id +'" type="checkbox" checked="checked" /> '+ response.value +'</li>');
                            }
                            else
                            {
                                var newItem = $(this).parent().parent().find('ul').append('<li><input type="hidden" name="'+ opts.title +'-'+ response.id +'" value="'+ response.value +'" /> '+ response.value +' - <a class="del-item" href="#" onclick="return false;">Remove</a></li>');
                                
                            }
                            
                            $(newItem).find('.del-item').bind("click", function() {
                                
                                var response = opts.onChange($(this).parent().find('input'), 'del')
                                if(response.msg == 'OK')
                                {
                                    $(this).parent().remove();
                                    alert(response.value + ' item has been deleted!')
                                }
                                else
                                {
                                    alert(response.msg);
                                }
                            }); 
                            
                            
                            $(button).find('.style').html('<span class="icon plus"></span> Add Item again?');
                            $(button).show();
                            $(this).parent().find('input').remove();
                            $(this).remove();
                        }
                        else
                        {
                            alert(response.msg);
                        }
                    })

                });     
                
                $(button).parent().parent().find('.del-item').bind("click", function() {
                    
                    var response = opts.onChange($(this).parent().find('input'), 'del')
                    if(response.msg == 'OK')
                    {
                        $(this).parent().remove();
                        alert(response.value + ' item has been deleted!')
                    }
                    else
                    {
                        alert(response.msg);
                    }
                }); 
        
            }
            
            
            /* ---------------------------------------------------------------------------- /
             * SELECT LIST (list, list-tiny) */
            
            else if((opts.type=="list") || (opts.type=="list-tiny"))
            {           
                var options = $('<ul class="list" style="display:none;"></ul>');
                
                $(this).find('option').each(function(){
                        if($(this).attr('selected')) {
                            selectItem = $(this).text();
                        }                       
                            
                        options.append($('<li><a href="#" onclick="return false;" title="'+ $(this).attr('value') +'">'+ $(this).text() +'</a></li>'))
                    })
                var select = $('<div><span>'+ selectItem +'</span></div>');
                var dropdown = $('<div class="select-'+ opts.type +'" style="' + $(this).attr('style') + '"><div>'+ select.html() + '</div><ul class="list" style="display:none;">' + options.html() + '</ul></div>');  
                
                $(this).hide().after(dropdown);

                $('ul.list').each(function() {
                    var largeur = $(this).parent().css("width");
                    $(this).css('width', largeur);
                });
                
                //events are written here
                dropdown.find('div')
                    .bind('mousedown', function(){
                        $('.select-list ul, .select-list-tiny ul').css('display', 'none').parent().find('div').css('z-index', '1');
                        $(this).css('z-index', '3');
                        $(this).next().css('z-index', '2').css('display', 'block');
                    })
                dropdown.find('ul')
                    .bind('mouseover', function(){
                        $(this).css('display', 'block');
                    })
                    .bind('mouseout', function(){
                        $(this).css('display', 'none');
                    });
                dropdown.find('ul li')
                    .bind('click', function(){
                        var choice = $(this).text();
                        $(this).parent().parent().find('div span').text(choice);
                        $(this).parent().css('display', 'none');
                        $(this).parent().parent().find('div').css('z-index', '1');
                        var value = $(this).find('a').attr('title');
                        $(this).parent().parent().prev().find('option[value='+ value +']').attr('selected', 'selected').change();
                        if(opts.onChange)
                            { 
                            opts.onChange($(this).parent().parent().prev()); 
                            }
                    })  
            }
            
            else {
                //do nothing
            }
        
        }
        
        return $(this).each(create);

                    
    }; // end nicyform


    $.fn.nicyform.defaults = {
        title: "title",
        type: "list",
        shape: "btn-normal",
        bgcolor: "gray",
        txtcolor: "black",
        iconcolor: "black"
    };
          
})(jQuery);


