/*
 * Custom Select - jQuery plugin
 *
 * Copyright (c) 2008 bushimichi bushimichi@gmail.com
 *
 * Dual licensed under
 * the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.gnu.org/licenses/gpl.html) licenses.
 *
 * Version: 0.2  2009/07/22  IE6,IE7 bug fix
 *
 */


jQuery(function($){

$.cs = {

  version: 0.2

 ,className: 'customSelect'

 ,init: function(elm){
    var h_optgroup = '';
    elm.find('optgroup')
          .each(function(i, optgroup){
            h_optgroup += $.cs.createOptgroup($(optgroup));
          })
          .end()
        .find('> option')
          .each(function(i, option){
            h_optgroup += $.cs.createCancel($(option));
          })
          .end()
        .before($.cs.createPulldown(h_optgroup))
        ;
  }

 ,createOptgroup: function(optgroup){
    var h_option = optgroup.attr('label') ? '<label>' + optgroup.attr('label') + '</label>' : '';
    optgroup.find('option').each(function(i, option){
      option = $(option);
      h_option += $.cs.createOption(option);
    })
    return '<li>' + h_option + '</li>';
  }

 ,createOption: function(option){
    return '<div><input type="button" value="' + option.text() + '" v="' + option.val() + '"></div>';
  }

 ,createCancel: function(option){
    return '<li class="cancel"><div><input type="button" value="キャンセル" v=""></div></li>';
 }

 ,createPulldown: function(str){
   return '<span><ul>' + str + '</ul></span>';
 }

 ,onSelectClick: function(e){
   $.cs.onClose();
   $(this).focus()
          .attr('disabled',true)
          .blur()
            .prev('span')
              .find('ul.' + $.cs.className).show();
   // IE6
   if($.browser.msie && $.browser.version == '6.0'){
     $.cs.adIe6($(this));
   }
   // event stop
   $.cs.eventStop(e);
 }
 ,onOptionClick: function(e){
   var elm = $(this);
   var p = $(this).parents('span')
                    .find('input[type=button]')
                      .attr('on', '0')
                      .css({'background-color':elm.attr('background-color'), color:elm.attr('color')})
//                      .mouseout()
                      .end()
                    .next('select')
                      .val(elm.attr('v') || '')
                    ;
   $.cs.onClose();
   $(this).parents('span').next('select').trigger('change');

   if(elm.attr('v')){
     elm.mouseover()
        .attr('on', '1')
     ;
     $.cs.onMouseover.apply(elm);
   }
   $.cs.eventStop(e);
 }

 ,onClose: function(){
   $('ul.' + $.cs.className).hide();
   $('select.'+ $.cs.className).attr('disabled', false);
   if($.browser.msie && $.browser.version == '6.0'){
     $('select[ie6=1]').css('visibility','visible');
   }
 }

 ,onMouseover: function(e){
   var elm = $(this);
     elm.css({'background-color': 'navy', 'color': 'white'});
 }
 ,onMouseout: function(e){
   var elm = $(this);
   if(elm.attr('on') == '1'){
     // on
   }else{ // off
     elm.css({'background-color':elm.attr('background-color'), color:elm.attr('color')});
   }
 }

 ,setSize:{
   row: function(ul){
    var h = (ul.find('li.cancel').size() > 0) ? -18 : 0;
    ul.find('li').not('.cancel').height(ul.height() + (($.browser.msie) ? 0 : h));

   }
  ,col: function(ul){
   //  ul.find('li').width(ul.width());
   }
 }

 ,setLabel: function(ul){
   var w = [];
   ul.find('> li > label').each(function(i, label){
     w[w.length] = $(label).width() + (($.browser.msie) ? 7 : 0);
   }).css({width: Math.max.apply(null,w)});
 }

 // event stop
 ,eventStop: function(e){
    if ($.browser.msie) {
        keycode = event.keyCode;
        ctrl  = event.ctrlKey;
        shift = event.shiftKey;
        event.returnValue  = false;
        event.cancelBubble = true;
    }else{
        keycode = e.which;
        ctrl  = typeof e.modifiers == 'undefined' ? e.ctrlKey  : e.modifiers & Event.CONTROL_MASK;
        shift = typeof e.modifiers == 'undefined' ? e.shiftKey : e.modifiers & Event.SHIFT_MASK;
        e.preventDefault();
        e.stopPropagation();
    }
    return false;
  }

  ,adIe6: function(el){
    var ul = el.prev('span').find('> ul');
    var ofg = $.extend(ul.offset(),{w:ul.width(),h:ul.height()});

    $('select')
      .not(el)
       .each(function(i, elm){
          elm = $(this);
          ofe = $.extend(elm.offset(),{w:elm.width(),h:elm.height()});

          if( (ofg.left > ofe.left + ofe.w)
           || (ofg.top  > ofe.top + ofe.h)
           || (ofg.left + ofg.w < ofe.left)
           || (ofg.top + ofg.h < ofe.top)){

           }else{
             elm.css('visibility','hidden')
                .attr('ie6',1);
           }
       });
  }

}

//
// style setting
//
$.cs.style = function(){
  var css = {

    span: {position:'absolute', width:'100%'}

   ,ul:   {row:{'font-size':'12px',position:'absolute', margin:0, padding:0, 'line-height':'18px', 'list-style':'none', border:'solid 1px #666666', 'background-color':'#ffffff'}
          ,col:{'font-size':'12px',position:'absolute', margin:0, padding:0, 'line-height':'18px', 'list-style':'none', border:'solid 1px #666666', 'background-color':'#ffffff'}
          }

   ,li:   {row:{margin:'0 0 0 -1px', padding: 0,'border-left':'1px dotted #666666',  float:'left', 'text-align': 'center'}
          ,col:{margin:'-1px 0 0 0', padding: 0,'border-top' :'1px dotted #666666',  clear:'both'}
          }

   ,label:{row:{margin:0, 'text-align':'center', display:'block', 'border-bottom':'1px #999999 solid', padding:'0 3px', color: '#666666', 'background-color':'transparent'}
          ,col:{margin:0, 'text-align':'center', display:'block', 'border-right' :'1px #999999 solid', padding:'0 3px', color: '#666666', 'background-color':'transparent', float:'left'}
          }

   ,div:  {row:{margin:0, padding:'0 2px 0 3px'}
          ,col:{margin:0, padding:'0 2px 0 3px', float:'left'}
          }

   ,button:{'background-color':'transparent','border':'none',cursor:'pointer',margin:0,padding:0,height:'18px',color:'black'}

   ,cancel:{clear:'both',margin:0,padding:0,'border-top':'1px dotted #666666'}
 }
 return css;
}

//
$.fn.cs = function(opt){
  opt = opt || {};

  var css = $.cs.style();
  $.each(opt.style || {},function(i, style){
    if(style.row || style.col){
      $.each(style,function(j, order){
        css[i][j] = $.extend(css[i][j], order);
      });
    }else{
      css[i] = $.extend(css[i], style);
    }
  });

  $(this).each(function(i, elm){
    elm = $(elm);
    var order = elm.attr('order') || 'row';

    // render
    elm.before($.cs.init(elm))
       .mousedown($.cs.onSelectClick)
       .addClass($.cs.className)
       ;

    // ul wrap
    var span = elm.prev('span').css(css.span).width($('body').width() * 2);

    // pulldown panel
    var ul =
      span
        .find('> ul')
          .css($.extend(css.ul[order], {top: elm.height() + (($.browser.msie) ? 4 : 2)}))
          .addClass($.cs.className)

          .find('> li')
            .not('.cancel').css(css.li[order])
              .end()

            .find('> label') .css(css.label[order])
              .end()
            .find('> div').css(css.div[order])
              .find('> input[type=button]').css(css.button)
                .attr({'background-color':css.button['background-color'], color:css.button['color'], on:'0'})
                .hover($.cs.onMouseover, $.cs.onMouseout)
                .click($.cs.onOptionClick)
                .filter('[v=' + elm.val() + '][v!=""]')
                  .css({'background-color': 'navy', 'color': 'white'})
                  // .mouseover()
                  .attr('on', '1')
                  .end()
                .end()
              .end()
            .end()
        ;

    // adjust li
    $.cs.setSize[order](ul);
    $.cs.setLabel(ul);

    // cancel btn
    ul.find('> li.cancel').css(css.cancel)
          .find('input[type=button]')
            .css({width:ul.find('> li.cancel').width()});

    // adjust width
    span.width(ul.width() + elm.width());

    //
    ul.hide();

  });
}

// It cancels by the screen click.
  $(document).click(function(e){
    if($(e.target).hasClass($.cs.className)){
      return $.cs.eventStop(e);
    }else{
      $.cs.onClose();
    }
  });

});


