﻿/*
 * jQuery Modality pagination plugin
 * http://modality.com
 *
 * Creator: Nathan Wilkinson
 * Version: 0.1
 */
(function($){
  $.fn.dropdownmask = function(options){
    var opts = $.extend({
      zIndex:10
    }, options);
  
    return this.each(function(){
      var dd = $(this);
      var handle = $('<div class="ddmask-handle"></div>');
      var list = $('<ul class="ddmask-list"></ul>');
      
      for(var i=0; i<$(this).find('option').length; i++){
        list.append('<li><a href="javascript:void(0);">' + $(this).find('option:eq(' + i + ')').text() + '</a></li>');
      }
      
      handle.css({
        left:dd.offset().left,
        top:dd.offset().top,
        width:dd.width(),
        height:dd.height(),
        lineHeight:dd.height() + 'px',
        zIndex:opts.zIndex
      });
      
      list.css({
        left:dd.offset().left,
        top:dd.offset().top + parseInt(dd.height(),10) + 2,
        zIndex:opts.zIndex + 1
      });
      
      if (dd.find('option:selected').length > 0) {
        selectIndex(dd.find('option').index(dd.find('option:selected')));
      } else {
        selectIndex(0);
      }
      
      dd.after(list).after(handle);
      dd.hide();
      
      handle.bind('click focus', function(){
        list.show();
      });
      
      list.find('a').bind('click', function(){
        var index = list.find('a').index(this);
        selectIndex(index);
      }).bind('mouseover', function(){
        list.find('a').removeClass('on');
      });
      
      $(document).click(function(e){
        if (!$(e.target).closest('.ddmask-handle,.ddmask-list').length)
          list.hide();
      });
      
      function selectIndex(index){
        handle.text(list.find('a:eq(' + index + ')').text());
        list.find('a').removeClass('on');
        list.find('a:eq(' + index + ')').addClass('on');
        dd.find('option:selected').removeAttr('selected');
        dd.find('option:eq(' + index + ')').attr('selected','selected');
        dd.change();
        list.hide();
      }
    });
  };
})(jQuery);