// 日本語 UTF-8N LF
//-------------------------------------------------------------
// JavaScript
// jQuery プラグイン
//-------------------------------------------------------------
// Landwarf / Takayuki Onodera
//-------------------------------------------------------------
//
//-------------------------------------------------------------
// プラグイン
//-------------------------------------------------------------
(function($) {
    //---------------------------------------------------------
    // 指定要素内のブロックの高さを揃える
    //---------------------------------------------------------
    $.fn.setHeight = function() {
        if (this.length > 1) {
            var maxHeight = 0;
            this.each(function() {
                var height = $(this).height();
                if (height > maxHeight) maxHeight = height;
            });
            $(this).height(maxHeight);
        //  $(this).height(maxHeight).css("overflow","auto");
        //  $(this).css({'height':strHight + 'px'});
        //  $(this).css({'min-height':strHight + 'px'});
        }
        return this;
    };
    //---------------------------------------------------------
    // 指定要素内の文章に word-break 効果を適用する
    // Usage: $('[search]').breakWords();
    //---------------------------------------------------------
    $.fn.breakWords = function() {
        this.each(function() {
            if (this.nodeType !== 1) { return; }
            if (this.currentStyle && typeof this.currentStyle.wordBreak === 'string') {
                // Lazy Function Definition Pattern, Peter's Blog
                // From http://peter.michaux.ca/article/3556
                this.runtimeStyle.wordBreak = 'break-all';
            } else if(document.createTreeWalker) {
                // Faster Trim in Javascript, Flagrant Badassery
                // http://blog.stevenlevithan.com/archives/faster-trim-javascript
                var trim = function(str) {
                    str = str.replace(/^\s\s*/, '');
                    var ws = /\s/,
                    i = str.length;
                    while (ws.test(str.charAt(--i)));
                    return str.slice(0, i + 1);
                };
                // Lazy Function Definition Pattern, Peter's Blog
                // From http://peter.michaux.ca/article/3556
                // For Opera, Safari, and Firefox
                var dWalker = document.createTreeWalker(this, NodeFilter.SHOW_TEXT, null, false);
                var node,s,c = String.fromCharCode('8203');
                while (dWalker.nextNode()) {
                    node = dWalker.currentNode;
                    // we need to trim String otherwise Firefox will display
                    // incorect text-indent with space characters
                    s = trim( node.nodeValue ).split('').join(c);
                    node.nodeValue = s;
                }
            }
        });
        return this;
    };
    //---------------------------------------------------------
    /**
     * jQuery (PNG Fix) v1.2
     * Microsoft Internet Explorer 24bit PNG Fix
     *
     * The MIT License
     *
     * Copyright (c) 2007 Paul Campbell (pauljamescampbell.co.uk)
     *
     * 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.
     *
     * @param       Object
     * @return      Array
     */
    //---------------------------------------------------------
    $.fn.pngfix = function(options) {
        // Review the Microsoft IE developer library for AlphaImageLoader reference
        // http://msdn2.microsoft.com/en-us/library/ms532969(VS.85).aspx
        // ECMA scope fix
        var elements    = this;
        var settings    = $.extend({
            imageFixSrc:    false,
            sizingMethod:   false
        }, options);
        if(!$.browser.msie || ($.browser.msie &&  $.browser.version >= 7)) {
            return(elements);
        }
        function setFilter(el, path, mode) {
            var fs = el.attr("filters");
            var alpha = "DXImageTransform.Microsoft.AlphaImageLoader";
            if (fs[alpha]) {
                fs[alpha].enabled = true;
                fs[alpha].src = path;
                fs[alpha].sizingMethod = mode;
            } else {
                el.css("filter", 'progid:' + alpha + '(enabled="true", sizingMethod="' + mode + '", src="' + path + '")');
            }
        }
        function setDOMElementWidth(el) {
            if(el.css("width") == "auto" & el.css("height") == "auto") {
                el.css("width", el.attr("offsetWidth") + "px");
            }
        }
        return(
            elements.each(function() {
                // Scope
                var el = $(this);
                if(el.attr("tagName").toUpperCase() == "IMG" && (/\.png/i).test(el.attr("src"))) {
                    if(!settings.imageFixSrc) {
                        // Wrap the <img> in a <span> then apply style/filters,
                        // removing the <img> tag from the final render
                        el.wrap("<span></span>");
                        var par = el.parent();
                        par.css({
                            height:     el.height(),
                            width:      el.width(),
                            display:    "inline-block"
                        });
                        setFilter(par, el.attr("src"), "scale");
                        el.remove();
                    } else if((/\.gif/i).test(settings.imageFixSrc)) {
                        // Replace the current image with a transparent GIF
                        // and apply the filter to the background of the
                        // <img> tag (not the preferred route)
                        setDOMElementWidth(el);
                        setFilter(el, el.attr("src"), "image");
                        el.attr("src", settings.imageFixSrc);
                    }
                } else {
                    var bg = new String(el.css("backgroundImage"));
                    var matches = bg.match(/^url\("(.*)"\)$/);
                    if(matches && matches.length) {
                        // Elements with a PNG as a backgroundImage have the
                        // filter applied with a sizing method relevant to the
                        // background repeat type
                        setDOMElementWidth(el);
                        el.css("backgroundImage", "none");
                        // Restrict scaling methods to valid MSDN defintions (or one custom)
                        var sc = "crop";
                        if(settings.sizingMethod) {
                            sc = settings.sizingMethod;
                        }
                        setFilter(el, matches[1], sc);
                        // Fix IE peek-a-boo bug for internal links
                        // within that DOM element
                        el.find("a").each(function() {
                            $(this).css("position", "relative");
                        });
                    }
                }
            })
        );
    };
})(jQuery);
//-------------------------------------------------------------
// プラグイン
//-------------------------------------------------------------
/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
//-------------------------------------------------------------
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
//-------------------------------------------------------------
// プラグイン
//-------------------------------------------------------------
/*
 * jQuery Cycle Plugin (with Transition Definitions)
 * Examples and documentation at: http://jquery.malsup.com/cycle/
 * Copyright (c) 2007-2010 M. Alsup
 * Version: 2.88 (08-JUN-2010)
 * Dual licensed under the MIT and GPL licenses.
 * http://jquery.malsup.com/license.html
 * Requires: jQuery v1.2.6 or later
$.fn.cycle.defaults = {
    fx:             'fade', // name of transition effect (or comma separated names, ex: fade,scrollUp,shuffle)
    timeout:         4000,  // milliseconds between slide transitions (0 to disable auto advance)
    timeoutFn:       null,  // callback for determining per-slide timeout value:  function(currSlideElement, nextSlideElement, options, forwardFlag)
    continuous:      0,     // true to start next transition immediately after current one completes
    speed:           1000,  // speed of the transition (any valid fx speed value)
    speedIn:         null,  // speed of the 'in' transition
    speedOut:        null,  // speed of the 'out' transition
    next:            null,  // selector for element to use as click trigger for next slide
    prev:            null,  // selector for element to use as click trigger for previous slide
    prevNextClick:   null,  // callback fn for prev/next clicks:    function(isNext, zeroBasedSlideIndex, slideElement)
    prevNextEvent:  'click.cycle',// event which drives the manual transition to the previous or next slide
    pager:           null,  // selector for element to use as pager container
    pagerClick:      null,  // callback fn for pager clicks:    function(zeroBasedSlideIndex, slideElement)
    pagerEvent:     'click.cycle', // name of event which drives the pager navigation
    allowPagerClickBubble: false,  // allows or prevents click event on pager anchors from bubbling
    pagerAnchorBuilder: null, // callback fn for building anchor links:  function(index, DOMelement)
    before:          null,  // transition callback (scope set to element to be shown):     function(currSlideElement, nextSlideElement, options, forwardFlag)
    after:           null,  // transition callback (scope set to element that was shown):  function(currSlideElement, nextSlideElement, options, forwardFlag)
    end:             null,  // callback invoked when the slideshow terminates (use with autostop or nowrap options): function(options)
    easing:          null,  // easing method for both in and out transitions
    easeIn:          null,  // easing for "in" transition
    easeOut:         null,  // easing for "out" transition
    shuffle:         null,  // coords for shuffle animation, ex: { top:15, left: 200 }
    animIn:          null,  // properties that define how the slide animates in
    animOut:         null,  // properties that define how the slide animates out
    cssBefore:       null,  // properties that define the initial state of the slide before transitioning in
    cssAfter:        null,  // properties that defined the state of the slide after transitioning out
    fxFn:            null,  // function used to control the transition: function(currSlideElement, nextSlideElement, options, afterCalback, forwardFlag)
    height:         'auto', // container height
    startingSlide:   0,     // zero-based index of the first slide to be displayed
    sync:            1,     // true if in/out transitions should occur simultaneously
    random:          0,     // true for random, false for sequence (not applicable to shuffle fx)
    fit:             0,     // force slides to fit container
    containerResize: 1,     // resize container to fit largest slide
    pause:           0,     // true to enable "pause on hover"
    pauseOnPagerHover: 0,   // true to pause when hovering over pager link
    autostop:        0,     // true to end slideshow after X transitions (where X == slide count)
    autostopCount:   0,     // number of transitions (optionally used with autostop to define X)
    delay:           0,     // additional delay (in ms) for first transition (hint: can be negative)
    slideExpr:       null,  // expression for selecting slides (if something other than all children is required)
    cleartype:       !$.support.opacity,  // true if clearType corrections should be applied (for IE)
    cleartypeNoBg:   false, // set to true to disable extra cleartype fixing (leave false to force background color setting on slides)
    nowrap:          0,     // true to prevent slideshow from wrapping
    fastOnEvent:     0,     // force fast transitions when triggered manually (via pager or prev/next); value == time in ms
    randomizeEffects:1,     // valid when multiple effects are used; true to make the effect sequence random
    rev:             0,     // causes animations to transition in reverse
    manualTrump:     true,  // causes manual transition to stop an active transition instead of being ignored
    requeueOnImageNotLoaded: true, // requeue the slideshow if any image slides are not yet loaded
    requeueTimeout:  250,   // ms delay for requeue
    activePagerClass: 'activeSlide', // class name used for the active pager link
    updateActivePagerLink: null // callback fn invoked to update the active pager link (adds/removes activePagerClass style)
};
*/
(function(D){var A="Lite-1.0";D.fn.cycle=function(E){return this.each(function(){E=E||{};if(this.cycleTimeout){clearTimeout(this.cycleTimeout)}this.cycleTimeout=0;this.cyclePause=0;var I=D(this);var J=E.slideExpr?D(E.slideExpr,this):I.children();var G=J.get();if(G.length<2){if(window.console&&window.console.log){window.console.log("terminating; too few slides: "+G.length)}return }var H=D.extend({},D.fn.cycle.defaults,E||{},D.metadata?I.metadata():D.meta?I.data():{});H.before=H.before?[H.before]:[];H.after=H.after?[H.after]:[];H.after.unshift(function(){H.busy=0});var F=this.className;H.width=parseInt((F.match(/w:(\d+)/)||[])[1])||H.width;H.height=parseInt((F.match(/h:(\d+)/)||[])[1])||H.height;H.timeout=parseInt((F.match(/t:(\d+)/)||[])[1])||H.timeout;if(I.css("position")=="static"){I.css("position","relative")}if(H.width){I.width(H.width)}if(H.height&&H.height!="auto"){I.height(H.height)}var K=0;J.css({position:"absolute",top:0,left:0}).hide().each(function(M){D(this).css("z-index",G.length-M)});D(G[K]).css("opacity",1).show();if(D.browser.msie){G[K].style.removeAttribute("filter")}if(H.fit&&H.width){J.width(H.width)}if(H.fit&&H.height&&H.height!="auto"){J.height(H.height)}if(H.pause){I.hover(function(){this.cyclePause=1},function(){this.cyclePause=0})}D.fn.cycle.transitions.fade(I,J,H);J.each(function(){var M=D(this);this.cycleH=(H.fit&&H.height)?H.height:M.height();this.cycleW=(H.fit&&H.width)?H.width:M.width()});J.not(":eq("+K+")").css({opacity:0});if(H.cssFirst){D(J[K]).css(H.cssFirst)}if(H.timeout){if(H.speed.constructor==String){H.speed={slow:600,fast:200}[H.speed]||400}if(!H.sync){H.speed=H.speed/2}while((H.timeout-H.speed)<250){H.timeout+=H.speed}}H.speedIn=H.speed;H.speedOut=H.speed;H.slideCount=G.length;H.currSlide=K;H.nextSlide=1;var L=J[K];if(H.before.length){H.before[0].apply(L,[L,L,H,true])}if(H.after.length>1){H.after[1].apply(L,[L,L,H,true])}if(H.click&&!H.next){H.next=H.click}if(H.next){D(H.next).bind("click",function(){return C(G,H,H.rev?-1:1)})}if(H.prev){D(H.prev).bind("click",function(){return C(G,H,H.rev?1:-1)})}if(H.timeout){this.cycleTimeout=setTimeout(function(){B(G,H,0,!H.rev)},H.timeout+(H.delay||0))}})};function B(J,E,I,K){if(E.busy){return }var H=J[0].parentNode,M=J[E.currSlide],L=J[E.nextSlide];if(H.cycleTimeout===0&&!I){return }if(I||!H.cyclePause){if(E.before.length){D.each(E.before,function(N,O){O.apply(L,[M,L,E,K])})}var F=function(){if(D.browser.msie){this.style.removeAttribute("filter")}D.each(E.after,function(N,O){O.apply(L,[M,L,E,K])})};if(E.nextSlide!=E.currSlide){E.busy=1;D.fn.cycle.custom(M,L,E,F)}var G=(E.nextSlide+1)==J.length;E.nextSlide=G?0:E.nextSlide+1;E.currSlide=G?J.length-1:E.nextSlide-1}if(E.timeout){H.cycleTimeout=setTimeout(function(){B(J,E,0,!E.rev)},E.timeout)}}function C(E,F,I){var H=E[0].parentNode,G=H.cycleTimeout;if(G){clearTimeout(G);H.cycleTimeout=0}F.nextSlide=F.currSlide+I;if(F.nextSlide<0){F.nextSlide=E.length-1}else{if(F.nextSlide>=E.length){F.nextSlide=0}}B(E,F,1,I>=0);return false}D.fn.cycle.custom=function(K,H,I,E){var J=D(K),G=D(H);G.css({opacity:0});var F=function(){G.animate({opacity:1},I.speedIn,I.easeIn,E)};J.animate({opacity:0},I.speedOut,I.easeOut,function(){J.css({display:"none"});if(!I.sync){F()}});if(I.sync){F()}};D.fn.cycle.transitions={fade:function(F,G,E){G.not(":eq(0)").css("opacity",0);E.before.push(function(){D(this).show()})}};D.fn.cycle.ver=function(){return A};D.fn.cycle.defaults={timeout:4000,speed:1000,next:null,prev:null,before:null,after:null,height:"auto",sync:1,fit:0,pause:0,delay:0,slideExpr:null}})(jQuery)
//-------------------------------------------------------------
// プラグイン：カラーピッカー
//-------------------------------------------------------------
/**
 * Farbtastic Color Picker 1.2
 * (C)2008 Steven Wittens
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */
jQuery.fn.farbtastic = function (callback) {
  $.farbtastic(this, callback);
  return this;
};
jQuery.farbtastic = function (container, callback) {
  var container = $(container).get(0);
  return container.farbtastic || (container.farbtastic = new jQuery._farbtastic(container, callback));
}
jQuery._farbtastic = function (container, callback) {
  // Store farbtastic object
  var fb = this;
  // Insert markup
  $(container).html('<div class="farbtastic"><div class="color"></div><div class="wheel"></div><div class="overlay"></div><div class="h-marker marker"></div><div class="sl-marker marker"></div></div>');
  var e = $('.farbtastic', container);
  fb.wheel = $('.wheel', container).get(0);
  // Dimensions
  fb.radius = 84;
  fb.square = 100;
  fb.width = 194;
  // Fix background PNGs in IE6
  if (navigator.appVersion.match(/MSIE [0-6]\./)) {
    $('*', e).each(function () {
      if (this.currentStyle.backgroundImage != 'none') {
        var image = this.currentStyle.backgroundImage;
        image = this.currentStyle.backgroundImage.substring(5, image.length - 2);
        $(this).css({
          'backgroundImage': 'none',
          'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=crop, src='" + image + "')"
        });
      }
    });
  }
  /**
   * Link to the given element(s) or callback.
   */
  fb.linkTo = function (callback) {
    // Unbind previous nodes
    if (typeof fb.callback == 'object') {
      $(fb.callback).unbind('keyup', fb.updateValue);
    }
    // Reset color
    fb.color = null;
    // Bind callback or elements
    if (typeof callback == 'function') {
      fb.callback = callback;
    }
    else if (typeof callback == 'object' || typeof callback == 'string') {
      fb.callback = $(callback);
      fb.callback.bind('keyup', fb.updateValue);
      if (fb.callback.get(0).value) {
        fb.setColor(fb.callback.get(0).value);
      }
    }
    return this;
  }
  fb.updateValue = function (event) {
    if (this.value && this.value != fb.color) {
      fb.setColor(this.value);
    }
  }
  /**
   * Change color with HTML syntax #123456
   */
  fb.setColor = function (color) {
    var unpack = fb.unpack(color);
    if (fb.color != color && unpack) {
      fb.color = color;
      fb.rgb = unpack;
      fb.hsl = fb.RGBToHSL(fb.rgb);
      fb.updateDisplay();
    }
    return this;
  }
  /**
   * Change color with HSL triplet [0..1, 0..1, 0..1]
   */
  fb.setHSL = function (hsl) {
    fb.hsl = hsl;
    fb.rgb = fb.HSLToRGB(hsl);
    fb.color = fb.pack(fb.rgb);
    fb.updateDisplay();
    return this;
  }
  /////////////////////////////////////////////////////
  /**
   * Retrieve the coordinates of the given event relative to the center
   * of the widget.
   */
  fb.widgetCoords = function (event) {
    var x, y;
    var el = event.target || event.srcElement;
    var reference = fb.wheel;
    if (typeof event.offsetX != 'undefined') {
      // Use offset coordinates and find common offsetParent
      var pos = { x: event.offsetX, y: event.offsetY };
      // Send the coordinates upwards through the offsetParent chain.
      var e = el;
      while (e) {
        e.mouseX = pos.x;
        e.mouseY = pos.y;
        pos.x += e.offsetLeft;
        pos.y += e.offsetTop;
        e = e.offsetParent;
      }
      // Look for the coordinates starting from the wheel widget.
      var e = reference;
      var offset = { x: 0, y: 0 }
      while (e) {
        if (typeof e.mouseX != 'undefined') {
          x = e.mouseX - offset.x;
          y = e.mouseY - offset.y;
          break;
        }
        offset.x += e.offsetLeft;
        offset.y += e.offsetTop;
        e = e.offsetParent;
      }
      // Reset stored coordinates
      e = el;
      while (e) {
        e.mouseX = undefined;
        e.mouseY = undefined;
        e = e.offsetParent;
      }
    }
    else {
      // Use absolute coordinates
      var pos = fb.absolutePosition(reference);
      x = (event.pageX || 0*(event.clientX + $('html').get(0).scrollLeft)) - pos.x;
      y = (event.pageY || 0*(event.clientY + $('html').get(0).scrollTop)) - pos.y;
    }
    // Subtract distance to middle
    return { x: x - fb.width / 2, y: y - fb.width / 2 };
  }
  /**
   * Mousedown handler
   */
  fb.mousedown = function (event) {
    // Capture mouse
    if (!document.dragging) {
      $(document).bind('mousemove', fb.mousemove).bind('mouseup', fb.mouseup);
      document.dragging = true;
    }
    // Check which area is being dragged
    var pos = fb.widgetCoords(event);
    fb.circleDrag = Math.max(Math.abs(pos.x), Math.abs(pos.y)) * 2 > fb.square;
    // Process
    fb.mousemove(event);
    return false;
  }
  /**
   * Mousemove handler
   */
  fb.mousemove = function (event) {
    // Get coordinates relative to color picker center
    var pos = fb.widgetCoords(event);
    // Set new HSL parameters
    if (fb.circleDrag) {
      var hue = Math.atan2(pos.x, -pos.y) / 6.28;
      if (hue < 0) hue += 1;
      fb.setHSL([hue, fb.hsl[1], fb.hsl[2]]);
    }
    else {
      var sat = Math.max(0, Math.min(1, -(pos.x / fb.square) + .5));
      var lum = Math.max(0, Math.min(1, -(pos.y / fb.square) + .5));
      fb.setHSL([fb.hsl[0], sat, lum]);
    }
    return false;
  }
  /**
   * Mouseup handler
   */
  fb.mouseup = function () {
    // Uncapture mouse
    $(document).unbind('mousemove', fb.mousemove);
    $(document).unbind('mouseup', fb.mouseup);
    document.dragging = false;
  }
  /**
   * Update the markers and styles
   */
  fb.updateDisplay = function () {
    // Markers
    var angle = fb.hsl[0] * 6.28;
    $('.h-marker', e).css({
      left: Math.round(Math.sin(angle) * fb.radius + fb.width / 2) + 'px',
      top: Math.round(-Math.cos(angle) * fb.radius + fb.width / 2) + 'px'
    });
    $('.sl-marker', e).css({
      left: Math.round(fb.square * (.5 - fb.hsl[1]) + fb.width / 2) + 'px',
      top: Math.round(fb.square * (.5 - fb.hsl[2]) + fb.width / 2) + 'px'
    });
    // Saturation/Luminance gradient
    $('.color', e).css('backgroundColor', fb.pack(fb.HSLToRGB([fb.hsl[0], 1, 0.5])));
    // Linked elements or callback
    if (typeof fb.callback == 'object') {
      // Set background/foreground color
      $(fb.callback).css({
        backgroundColor: fb.color,
        color: fb.hsl[2] > 0.5 ? '#000' : '#fff'
      });
      // Change linked value
      $(fb.callback).each(function() {
        if (this.value && this.value != fb.color) {
          this.value = fb.color;
        }
      });
    }
    else if (typeof fb.callback == 'function') {
      fb.callback.call(fb, fb.color);
    }
  }
  /**
   * Get absolute position of element
   */
  fb.absolutePosition = function (el) {
    var r = { x: el.offsetLeft, y: el.offsetTop };
    // Resolve relative to offsetParent
    if (el.offsetParent) {
      var tmp = fb.absolutePosition(el.offsetParent);
      r.x += tmp.x;
      r.y += tmp.y;
    }
    return r;
  };
  /* Various color utility functions */
  fb.pack = function (rgb) {
    var r = Math.round(rgb[0] * 255);
    var g = Math.round(rgb[1] * 255);
    var b = Math.round(rgb[2] * 255);
    return '#' + (r < 16 ? '0' : '') + r.toString(16) +
           (g < 16 ? '0' : '') + g.toString(16) +
           (b < 16 ? '0' : '') + b.toString(16);
  }
  fb.unpack = function (color) {
    if (color.length == 7) {
      return [parseInt('0x' + color.substring(1, 3)) / 255,
        parseInt('0x' + color.substring(3, 5)) / 255,
        parseInt('0x' + color.substring(5, 7)) / 255];
    }
    else if (color.length == 4) {
      return [parseInt('0x' + color.substring(1, 2)) / 15,
        parseInt('0x' + color.substring(2, 3)) / 15,
        parseInt('0x' + color.substring(3, 4)) / 15];
    }
  }
  fb.HSLToRGB = function (hsl) {
    var m1, m2, r, g, b;
    var h = hsl[0], s = hsl[1], l = hsl[2];
    m2 = (l <= 0.5) ? l * (s + 1) : l + s - l*s;
    m1 = l * 2 - m2;
    return [this.hueToRGB(m1, m2, h+0.33333),
        this.hueToRGB(m1, m2, h),
        this.hueToRGB(m1, m2, h-0.33333)];
  }
  fb.hueToRGB = function (m1, m2, h) {
    h = (h < 0) ? h + 1 : ((h > 1) ? h - 1 : h);
    if (h * 6 < 1) return m1 + (m2 - m1) * h * 6;
    if (h * 2 < 1) return m2;
    if (h * 3 < 2) return m1 + (m2 - m1) * (0.66666 - h) * 6;
    return m1;
  }
  fb.RGBToHSL = function (rgb) {
    var min, max, delta, h, s, l;
    var r = rgb[0], g = rgb[1], b = rgb[2];
    min = Math.min(r, Math.min(g, b));
    max = Math.max(r, Math.max(g, b));
    delta = max - min;
    l = (min + max) / 2;
    s = 0;
    if (l > 0 && l < 1) {
      s = delta / (l < 0.5 ? (2 * l) : (2 - 2 * l));
    }
    h = 0;
    if (delta > 0) {
      if (max == r && max != g) h += (g - b) / delta;
      if (max == g && max != b) h += (2 + (b - r) / delta);
      if (max == b && max != r) h += (4 + (r - g) / delta);
      h /= 6;
    }
    return [h, s, l];
  }
  // Install mousedown handler (the others are set on the document on-demand)
  $('*', e).mousedown(fb.mousedown);
    // Init color
  fb.setColor('#000000');
  // Set linked elements/callback
  if (callback) {
    fb.linkTo(callback);
  }
}
//-------------------------------------------------------------
// Copyright(C)Landwarf All right reserved.
//-------------------------------------------------------------

