/*
jQuery customSelects Plugin
  * Version 1.0
  * 04-30-2010
  * URL: http://github.com/mdbiscan/customSelects
  * Author: M.Biscan
  * requires jQuery1.4.2
  
  Copyright (c) 2010 M.Biscan

  Permission is hereby granted, free of charge, to any person obtaining
  a copy of this software and associated documentation files (the
  "Software"), to deal in the Software without restriction, including
  without limitation the rights to use, copy, modify, merge, publish,
  distribute, sublicense, and/or sell copies of the Software, and to
  permit persons to whom the Software is furnished to do so, subject to
  the following conditions:

  The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
(function($){
  $.fn.customSelects = function(options) { 
    var settings = $.extend({}, $.fn.customSelects.defaults, options); 
    
    return this.each(function(index) {
      var $select = $(this),
          $options = $select.children(),
          $label = $('label[for=' + $select.attr('id') + ']'),
          $container = $('<div>').addClass('customSelects_container'),
          $title = $('<div>').addClass('customSelects_title'),
          $list = $('<ul>').addClass('customSelects_list');

      ///////////
      // Setup //
      ///////////
      buildCustomSelectOptions($options, $list);
      var $items = $list.children();
      
      $container
        .css({ position:'relative' })
        .attr('tabindex', $select.attr('tabindex'));
      
      if($select.attr('id') != '') {
        $container.attr('id', 'customSelect_' + $select.attr('id'));
      }
      if($select.css('display') == 'none') {
        $container.hide();
      }
      
      if($select.attr('multiple')) {
        $title.text($label.text()); 
      } else {
        $title.text($.data($options.filter(':selected'), 'data', $options.filter(':selected').text())); 
      }
      $title.appendTo($container);

      $list
        .css({
          position:'absolute',
          zIndex:settings.zIndex
        })
        .hide()
        .appendTo($container);
      
      if(!$select.attr('multiple')) { 
        $items
          .eq($options.filter(':selected').index())
          .addClass('selected');
      }
       
      $([$title, $list]).each(function() {
        unselectableText(this);
      }); 
        
      if($select.attr('disabled') == true || $select.hasClass('disabled')) {
        $container.addClass('disabled');
      }
      
      $select
        .before($container)
        .appendTo($container)
        .removeAttr('tabindex')
        .hide();
      
      ////////////
      // Events //
      //////////// 
      $container.focusin(function() {
        $(this).addClass('focus');
      }).focusout(function() {
        $(this).removeClass('focus');
      });
      
      $title.click(function(event) {         
        if(!$container.hasClass('disabled')) {
          if($list.hasClass('opened')) {
            closeList();
          } else {
            openList();
          }
        }
      }).hover(
        function() {
          $container.addClass('over');
        },
        function() {
          $container.removeClass('over');
          setTimeout(function() {
            if(!$container.hasClass('over')) {
              closeList();
            }
          }, 250);
        }
      );
    
      $list.hover(
        function() {
          $container.addClass('over');
        },
        function() {
          $container.removeClass('over');
          setTimeout(function() {
            if(!$container.hasClass('over')) {
              closeList();
            }
          }, 250);
        }
      );
    
      $items.mousedown(function(event) { 
        if($select.attr('multiple') == true) {
          selectMultipleItems($select, $options, $items, this, $title);
          event.stopPropagation();
        } else {
          selectItem($select, $options, this, $list, $title);
        }
      }).mouseenter(function() {
        hoverOver($items, this);
      });
      
      ///////////////////////
      // Private functions //
      ///////////////////////      
      function buildCustomSelectOptions(options, list) {
        var data;
        $(options).each(function() {
          data = $.data(this, 'option', $(this).text());
          $('<li>').text(data).appendTo($(list));
        });
      };
      
      function openList() {        
        if($.browser.msie && $.browser.version <= '7.0') {
          $list.appendTo('body');
          positionFix();
        }
        
        $list.slideDown(settings.speed, function() {
          $(this).addClass('opened');
          $list.scrollTop(0);
        });

        $container.addClass('active');
      };
      
      function closeList() {      
        var items = $list.children(); 
          
        $list.slideUp(settings.speed, function() {
          $(this).removeClass('opened');
          $container.removeClass('active');
          items.removeClass('hover');
          
          if($.browser.msie && $.browser.version <= '7.0') {
            $(this).appendTo($container);
          }
        });
      };
      
      function selectItem(select, options, item, list, title) {
        var value = $.data(item, 'text', $(item).text());
        
        var selected = $(list).find('.selected');
        selected.removeClass('selected');

        $(item).addClass('selected');
        $(title).text($(item).text());
        
        $(options)
          .eq($(item).index())
          .attr({selected:'selected'});

        closeList();
        $(select).trigger('change');
      };
      
      function selectMultipleItems(select, options, items, item, title) {
        var index = $(item).index();
        
        if($(item).hasClass('selected')) {
          $(item).removeClass('selected');
          $(options).eq(index).removeAttr('selected');
        } else {
          $(item).addClass('selected');
          $(options).eq(index).attr({selected:'selected'});
        }
        
        var updatedTitle = [];
        $(options).filter(':selected').each(function(index) {
          updatedTitle.push($(this).html()); 
          if(!$(this).eq(0) || $(this).eq(index+1) == options.length) {
            updatedTitle.push(', ');
          }
        });
        
        if($(options).filter(':selected').length == 0) {
          var labelText = $('label[for=' + $(select).attr('id') + ']').text();
          $(title).text(labelText);
        } else {
          $(title).text(updatedTitle.toString());
        }
        
        $(select).trigger('change');
      };
      
      function hoverOver(items, item) {
        $(items).removeClass('hover');
        $(item).addClass('hover');
      };
      
      // Fixes text select when clicking into an element
      function unselectableText(target) {
        $(target).css({
          '-moz-user-select':'none',
          '-khtml-user-select':'none',
          'user-select':'none'
        });

  			if($.browser.msie) {
  				$(target).each(function() {
  					this.ondrag = function() {
  						return false;
  					};
  				});
  				
  				$(target).each(function() {
  					this.onselectstart = function() {
  						return (false);
  					};
  				});
  			} else if($.browser.opera) {
  				$(target).attr('unselectable', 'on');
  			}
      };
      
      // fixes IE6/7 positioning bug
      function positionFix() {
        var top = $container.offset().top + $container.innerHeight() + 2,
            left = $container.offset().left,
            width = $container.innerWidth();
        
        $list.css({
          left:left,
          top:top,
          width:width
        });
      };
      
      // Remote Update for public functions
      function remoteUpdate(select, value, string) {
        var options = $(select).children(),
            title = $(select).parent().find('.customSelects_title');
        
        options.each(function() {
          var val;
          if(string == 'value') {
            val = $(this).val();
          } else if(string == 'text') {
            val = $(this).text();       
          }
          
          if(value == val) {
            $(this).attr({selected:'selected'});
          }
        });
        
        var selectedOptionHTML = options.filter(':selected').html(),
            listItems = $(select).parent().find('li');
        
        listItems.each(function() {
          if($(this).html() == selectedOptionHTML) {
            var selectedText = $(this).html();
                     
            $(this).addClass('selected');
            title.text(selectedText);
          } else {
            $(this).removeClass('selected');
          }
        });
        
        $(select).trigger('change');
      };
      
      // function moveUp(trigger, item) {
      //   $(trigger).removeClass('stopDown');
      //   
      //   if($items.filter(':first').hasClass('hover')) {
      //     $(trigger).addClass('stopUp');
      //   }
      //   
      //   if(!$(trigger).hasClass('stopUp')) {
      //     var prevItem = $(item).prev();
      //     
      //     scrollList(prevItem);
      //     hoverOver(prevItem);
      //   }
      // };
      // 
      // function moveDown(trigger, item) {
      //   $(trigger).removeClass('stopUp');
      //   
      //   if($items.filter(':last').hasClass('hover')) {
      //     $(trigger).addClass('stopDown');
      //   }
      //   
      //   if(!$(trigger).hasClass('stopDown')) {
      //     var nextItem = $(item).next();  
      //     
      //     scrollList(nextItem);
      //     hoverOver(nextItem);
      //   }
      // };
      // 
      // function scrollList(item) {
      //   var height = $(item).innerHeight(),
      //       scrollBy = $(item).index();
      //       
      //   $list.scrollTop(height*scrollBy);
      // }

      //////////////////////
      // Public functions //
      //////////////////////
      $.fn.customSelects.enableSelect = function(select) {
        var container = $(select).parent();
        container.removeClass('disabled');
        $(select).removeClass('disabled');
      };
      $.fn.customSelects.disableSelect = function(select) {
        var container = $(select).parent();
        container.addClass('disabled');
        $(select).addClass('disabled');
      };
      $.fn.customSelects.resetSelect = function(select) {
        var container = $(select).parent(),
            firstOption = $(select).children().filter(':first'),
            title = $(container).find('.customSelects_title'),
            value = firstOption.text();
        
        firstOption.attr({selected:'selected'});
        title.html(value);
      };
      $.fn.customSelects.remoteUpdateSelectByValue = function(select, value) {
        remoteUpdate(select, value, 'value');
      };
      $.fn.customSelects.remoteUpdateSelectByText = function(select, text) {
        remoteUpdate(select, text, 'text');
      };
      // Useful for selects that are updated via Ajax
      $.fn.customSelects.rebuildList = function(select) {
        var container = $(select).parent(),
            title = container.find('.customSelects_title'),
            list = container.find('ul'),
            options = $(select).children(),
            selectedOption = options.filter(':selected').text();
        
        if($(select).is(':visible')) {
          $(select).hide();
        }
        list.empty();
        buildCustomSelectOptions(options, list);
        title.text(selectedOption);
        
        var items = list.children();
        items.mousedown(function() { 
          if($(select).attr('multiple')) {
            selectMultipleItems(select, options, items, this, title);
            event.stopPropagation();
          } else {
            selectItem(select, options, this, list, title);
          }
        }).mouseenter(function() {
          hoverOver(items, this);
        });
      };
      $.fn.customSelects.returnCustomSelectTitle = function(select) {
        var title = $(select).parent().find('.customSelects_title');
        return title;
      };
    });
  };

  ////////////////////
  // Default optons //
  ////////////////////
  $.fn.customSelects.defaults = {
    zIndex:100,
    speed:100
  };
})(jQuery);
