/**
 * jQuery.ScrollTo - Easy element scrolling using jQuery.
 * Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 * Date: 5/25/2009
 * @author Ariel Flesler
 * @version 1.4.2
 *
 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
 */
;(function(d){var k=d.scrollTo=function(a,i,e){d(window).scrollTo(a,i,e)};k.defaults={axis:'xy',duration:parseFloat(d.fn.jquery)>=1.3?0:1};k.window=function(a){return d(window)._scrollable()};d.fn._scrollable=function(){return this.map(function(){var a=this,i=!a.nodeName||d.inArray(a.nodeName.toLowerCase(),['iframe','#document','html','body'])!=-1;if(!i)return a;var e=(a.contentWindow||a).document||a.ownerDocument||a;return d.browser.safari||e.compatMode=='BackCompat'?e.body:e.documentElement})};d.fn.scrollTo=function(n,j,b){if(typeof j=='object'){b=j;j=0}if(typeof b=='function')b={onAfter:b};if(n=='max')n=9e9;b=d.extend({},k.defaults,b);j=j||b.speed||b.duration;b.queue=b.queue&&b.axis.length>1;if(b.queue)j/=2;b.offset=p(b.offset);b.over=p(b.over);return this._scrollable().each(function(){var q=this,r=d(q),f=n,s,g={},u=r.is('html,body');switch(typeof f){case'number':case'string':if(/^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(f)){f=p(f);break}f=d(f,this);case'object':if(f.is||f.style)s=(f=d(f)).offset()}d.each(b.axis.split(''),function(a,i){var e=i=='x'?'Left':'Top',h=e.toLowerCase(),c='scroll'+e,l=q[c],m=k.max(q,i);if(s){g[c]=s[h]+(u?0:l-r.offset()[h]);if(b.margin){g[c]-=parseInt(f.css('margin'+e))||0;g[c]-=parseInt(f.css('border'+e+'Width'))||0}g[c]+=b.offset[h]||0;if(b.over[h])g[c]+=f[i=='x'?'width':'height']()*b.over[h]}else{var o=f[h];g[c]=o.slice&&o.slice(-1)=='%'?parseFloat(o)/100*m:o}if(/^\d+$/.test(g[c]))g[c]=g[c]<=0?0:Math.min(g[c],m);if(!a&&b.queue){if(l!=g[c])t(b.onAfterFirst);delete g[c]}});t(b.onAfter);function t(a){r.animate(g,j,b.easing,a&&function(){a.call(this,n,b)})}}).end()};k.max=function(a,i){var e=i=='x'?'Width':'Height',h='scroll'+e;if(!d(a).is('html,body'))return a[h]-d(a)[e.toLowerCase()]();var c='client'+e,l=a.ownerDocument.documentElement,m=a.ownerDocument.body;return Math.max(l[h],m[h])-Math.min(l[c],m[c])};function p(a){return typeof a=='object'?a:{top:a,left:a}}})(jQuery);

/*
 * SpicySelect jQuery Plugin
 *
 * http://github.com/paulelliott/jquery-spicyselect
 *
 * Copyright (c) 2009 Paul Elliott (paul@codingfrontier.com)
 *
 * Dual licensed under the MIT (MIT-LICENSE.txt) and GPL (GPL-LICENSE.txt) licenses.
 */
(function($) {
  $.fn.extend({
    spicyselect: function(user_settings) {
      //Override the default settings with the user settings
      var settings = $.extend({
        defaultText: "",
        animate: true,
        label_markup: "<a></a>",
        label_text_selector: "> a",
		scroll_to_bottom: false
      }, user_settings);

      //Iterate through all the selects being masked
      return this.each(function() {
        //Get and move the select box off the screen
        var selectBox = $(this).css({
          position: 'absolute',
          left: '-9999px'
        }).focus(function() {
          $("#" + $(this).data("mask_id")).addClass('focus');
        }).blur(function() {
          //IE goes crazy with this for some reason
          if (!$.browser.msie) {
            hideMask($("#" + $(this).data("mask_id")), settings);
          }
        });
        var selectOptions = $("> *", this);

        //Create and store the id for the masking ol
        var maskId = selectBox.attr('id') + '_mask';
        selectBox.data("mask_id", maskId);

        //Insert the basic structure for the mask into the DOM right after the select
        selectBox.after("<div id='" + maskId + "'><div></div><ol></ol></div>");
        var selectMask = $("#" + maskId).addClass("spicyselect").addClass(selectBox.attr("class")).focus(function() {
          selectMask.addClass("focus");
        });
        selectMask.find("> div").html(settings.label_markup);
        selectMask.data("select_id", selectBox.attr("id"));
        var label = selectMask.find("> div " + settings.label_text_selector);

        //Handle the keypress events
        selectBox.keydown(function(e) {
          //If the keypress was not ctrl, alt, or command and not a tab or enter, send it to the mask instead
          if (e.which != 9 && !e.altKey && !e.ctrlKey && !e.metaKey) {
            //if the down arrow was pressed, show the list
            if (e.which == 40) { //if the down arrow was pressed
              if (selectMask.find("> ol").is(":hidden")) {
                showMask(selectMask, settings);
              } else {
                var current = selectMask.find(".current");
                if (current.length == 0) { //If none are selected, select the first one.
                  selectMask.find("li:first").addClass("current");
                } else if (!selectMask.find("li:last").is(".current")) { //If the last one is selected, do nothing
                  //If any other one is selected, move it down one.
                  var currentIndex = selectMask.find("li").index(current);
                  selectMask.find("li:eq(" + (currentIndex + 1) + ")").addClass("current");
                  current.removeClass("current");
                }
              }
            } else if (e.which == 38 && selectMask.find("> ol").is(":visible")) { //if the up arrow is pressed
              //If the first one is selected, do nothing
              //If any other one is selected, move it up one.
              var current = selectMask.find(".current");
              var currentIndex = selectMask.find("li").index(current);
              selectMask.find("li:eq(" + (currentIndex - 1) + ")").addClass("current");
              current.removeClass("current");
            } else if (e.which == 27) { //if escape is pressed
              hideMask(selectMask, settings);
            } else if ((e.which == 13 || e.which == 32) && selectMask.find("> ol").is(":visible")) { //enter or spacebar is pressed
              //select the current option
              selectOption(selectMask, label, selectMask.find("li.current"));
              hideMask(selectMask, settings);
            } else if (e.which == 13) {
              //allow enter to pass through to the form if the the options are not visible.
            } else {
              showMask(selectMask, settings);
              keyhandler(selectMask, e);
            }

            return false;
          }
        });

        //If the first option has no value, assume it to be the default.
        if (selectOptions.length && !selectOptions[0].value) {
          settings.defaultText = selectOptions[0].text;
          selectOptions = selectOptions.slice(1);
        }
        label.text(settings.defaultText);

        //Iterate over the children of the select
        var options = selectMask.find("> ol").hide();
        selectOptions.each(function() {
          var option = $(this);

          //For an optgroup...
          if (option.is("optgroup")) {
            //Put the optgroup into a new ol
            var optgroup = $("<ol></ol>");
            optgroup.append(createLi(option));

            //Iterate over the options contained within and put them in the ol
            $("option", option[0]).each(function() {
              optgroup.append(createLi($(this)));
              $(this).is(":selected") && label.text(this.text);
            });

            options.append(optgroup);
          } else {
            if (!this.value) {
              //A valueless option is considered to be the default value
              settings.defaultText = this.text;
            } else {
              //Write an option with a blue into the ol
              options.append(createLi(option));
            }
          }

          //If the option was selected, use its label for display
          option.is(":selected") && label.text(option.text());
        });

        //Toggle the the ol if the display anchor is clicked
        selectMask.find("> div").click(function() {
          //Whenever the spicyselect is clicked, put focus to the underlying select
          selectBox.focus().click();

          if (selectMask.find("> ol").is(":visible")) {
            hideMask(selectMask, settings);
          } else {
            showMask(selectMask, settings);
          }
          return false;
        });

        //When the user selects an option from the list
        selectMask.find("ol li").live('click', function() {
          if ($(this).is(".optgroup_label")) return false;
          var mask = $(this).addClass("current").closest("div");
          selectOption(mask, label, $(this));
          hideMask(mask, settings);
        }).mouseover(function() {
          selectMask.find("ol li.current").removeClass("current");
          $(this).addClass("current");
        });

        //Disable selection of any text within selectMask
        selectMask.bind('select mousedown', function() { return false; });
      });
    }
  });

  function hideMask(mask, settings) {
    settings.animate && mask.find("> ol").slideUp("fast") || mask.find("> ol").hide();
    mask.removeClass("focus");
  }

  function showMask(mask, settings) {
    mask.find(".current").removeClass("current");
    settings.animate && mask.find("> ol").slideDown("fast") || mask.find("> ol").show();
    mask.addClass("focus");
	
	if (settings.scroll_to_bottom) {
		setTimeout(function(){
			$(window).scrollTo(9999,0);
		}, 300);
	}
  }

  function selectOption(mask, label, option) {
    if (option.length > 0) {
      label.text(option.text());
      $("#" + mask.data("select_id")).val(option.data("value")).change();
    }
  }

  function keyhandler(mask, e) {
    //Append the new character to the search data and store it
    if (e.which == 8 || e.which == 46) {
      mask.data("search_data", "");
    } else {
      var searchData = ((mask.data("search_data") || "") + String.fromCharCode(e.which)).toLowerCase();
      mask.data("search_data", searchData);
      mask.find("li.current").removeClass("current");
      mask.find("li").each(function() {
        var element = $(this);
        if (!element.hasClass("optgroup_label") && element.text().toLowerCase().match(searchData)) {
          element.addClass("current");
          return false;
        }
      });
    }
  }

  //Create an li for the mask from an option or optgroup
  function createLi(option) {
    var text = option.is("optgroup") ? option.attr("label") : option.text();
    var li = $("<li>" + text + "</li>").addClass(option.attr('class'));
    li.attr("style", option.attr('style'));
    option.is("optgroup") && li.addClass("optgroup_label");
    li.data('value', option.val());
    return li;
  }

  //Lame hack for IE
  if (1) {
  
    //If the user clicks off the select, hide it
    $("*").live('click', function(e) {
		
		flag = e.clientX ? true : false;

		if (flag) {
		  if ($(this).closest('.spicyselect').length == 0) {
			hideMask($(".spicyselect"), {
			  defaultText: "",
			  animate: true,
			  label_markup: "<a></a>",
			  label_text_selector: "> a"
			});
		  }
		 }
    });
  }

})(jQuery);

