/* *  ***  *   *    *
 * *  *    *   *   * *
 ***  **   *   *   * *
 * *  *    *   *   * *
 * *  ***  **  **   *

 passionate & creative about javascript? 
 email to jobs@sharedcopy.com !*/


/* code is (c) sharedcopy.com unless otherwise stated */

if (window.Prototype && parseFloat(Prototype.Version) < 1.5) {
  try {
    (function() {
      var collection = document.getElementsByTagName("script");
      for (var x = 0; x < collection.length; x++) {
        if (collection[x].src.match(/prototype/)) collection[x].src = "/javascripts/prototype-1.6.js";
      }
      var html = window.document.childNodes[1].innerHTML;
      var form = document.createElement('form');
      form.action = "http://sharedcopy.com/k/create"; form.method = "post";
      var input = document.createElement('input');
      input.name = "copy[url]"; input.value = window.location;
      form.appendChild(input);
      input = document.createElement('input');
      input.name = "copy[html]"; input.value = html;
      form.appendChild(input);
      document.body.appendChild(form); form.submit();
    })();
  } catch (e) {
    //
  }
}

/*
 * Example configuration that augments the core library to
 * do custom actions required by business logic.
 */
if (window.shcp && shcp.toolbar) {
  shcp.debug("exists!");
  (function() {
    jQuery('#k_deleteme').remove();
    jQuery(jQuery("script[id='k_script']")[1]).remove();
  })();
  eval("return");
}

if (document.contentType && !document.contentType.match(/HTML/i)) {
  (function() {
    var form = document.createElement('form');
    form.style.display = 'none';
    form.method = "POST";
    form.action = "http://sharedcopy.com/k/create";
    var input = document.createElement('input');
    input.name = "copy[url]";
    input.value = window.location.href;
    form.appendChild(input);
    input = document.createElement('input');
    input.name = "copy[html]";
    if (document.contentType.match(/image/i)) {
      input.value = "<img src='" + window.location.href + "'/>";
    } else {
      input.value = "<html>" + document.documentElement.innerHTML + "</html>";
    }
    form.appendChild(input);
    document.body.appendChild(form);
    form.submit();
  })();
}
if (window.SharedCopy) window.SharedCopy_ext = window.SharedCopy;
window.SharedCopy = {
  /* 
   * When this is executed,
   * - all libraries are available
   * - about load the configured shcp library
   */
  before_load: function() {
    this.startTime = new Date(); 
    shcp.debug("loading...");
    if (SharedCopy.config.copy_exist) {
      shcp.unset_click_areas = function() { }
      SharedCopy.config.toolbarcss = {};
      SharedCopy.on_ready = jQuery(document).ready;
      sharedcopy_dot_comjQuery = jQuery;
      sharedcopy_dot_comUtil = Util;
      shcp.on_k_mouseup_kmode_text = shcp.stickynote.render_form;
      shcp.count_stickies = function() { return jQuery('#karea .k_sticky, #karea > div > img').length; };
      shcp.unlock = function() { };
      shcp.lock = function() { };

      // proper DOM ready() when copy exists
      var old_shcp_on_ready = shcp.on_ready;
      shcp.on_ready = function(doc, fn) { jQuery(doc).ready(function() { old_shcp_on_ready(doc, fn); }); };
    }
    shcp.debug("before_load", jQuery('#karea'), jQuery('#k_script').siblings(), SharedCopy.on_ready);
    
    // embed
    jQuery('.k_deleteme').remove();
    jQuery('.sharedcopy_widget blockquote.cited').css('height', '');

    window.onbeforeunload = function (evt) {
      var has_unsaved_deletes = (shcp.deleted_comments ? shcp.deleted_comments.urls[0] : false);
      for (var index = 0; has_unsaved_deletes || index < shcp.k_count_history.length; index++) {
        if (has_unsaved_deletes || jQuery('.k_coupling' + shcp.k_count_history[index])[0]) {
          message = "You have unsaved changes."
          if (typeof evt == 'undefined') evt = window.event;
          if (evt) evt.returnValue = message;
          return message;
        }
      }
    }
    
    shcp.get_unique_domid = function(prefix) {
      var num = 0;
      while (document.getElementById(prefix + num)) num += 1;
      return prefix + num;
    }
    
    shcp.remember_dimensions = function (query) {
      jQuery(query).each(function(index, element) {
        try {
          var jelement = jQuery(element);
          var dimension = "shcp_dimension_" + jelement.width() + "x" + jelement.height();
          jelement.addClass(dimension);
        } catch (e) {
          // ignore
        }
      });
    }
    
    SharedCopy.update_comments_count = function() {
      // update "5 comments" label
      var count = jQuery('#k_toolbar_list > ol > li').length;
      if (count < 1) {
        jQuery('#karea #k_comments_showhide').hide();
      } else {
        jQuery('#karea #k_comments_showhide').show();
      }      
      jQuery('#k_comments_label').html(Util.pluralize(count, "comment"));      
    }

    SharedCopy.list_related_comments = function(json_array, start_offset) {
      var process_size = 5;
      var toolbar = jQuery('#k_toolbar_list');
      start_offset = start_offset || 0;
      while (start_offset-- > 0) { json_array.shift(); }
      jQuery.each(json_array, function(index, comment) {
        if (index > process_size || !comment)  return;

        var first_comment = false;
        var container_ol = toolbar.children('.related_comments' + comment.copy_id);
        if (! container_ol[0]) {
          first_comment = true;
          container_ol = jQuery('<ol class="k_make_remove related_comments related_comments' + comment.copy_id + '"></ol>');
          toolbar.append(container_ol);
        }
        var content_html = Util.supplant(SharedCopy.config.html.comment_li_body, {
          content_css: "comment_body comment_body" + index,
          link_css: "",
          tag_name: (comment.is_quote ? 'blockquote' : 'p'),
          body_url: comment.url,
          body: comment.body
        });

        var container_li = container_ol.children('.related_comment' + comment.posting_id);
        if (! container_li[0]) {
          var li_html = Util.supplant(SharedCopy.config.html.comment_li, {
            li_id: "",
            li_class: 'k_make_remove related_comment related_comment' + comment.posting_id + (first_comment ? ' first_comment' : ''),
            user_url: (comment.user_id ? SharedCopy.config.url_base + "/~" + comment.user_login : comment.url),
            user_name: comment.user_login,
            user_picture_url: SharedCopy.config.url_base + "/photos/users/" + (comment.user_id ? comment.user_login : 'guest') + ".png",
            datetime: comment.datetime
          });
          container_li = jQuery(li_html).appendTo(container_ol);
        }
        jQuery(content_html).appendTo(jQuery('.content .text', container_li));
      });
      
      SharedCopy.update_comments_count();
      if (json_array.length > process_size) {
        setTimeout(function() {
          SharedCopy.list_related_comments(json_array, process_size + 1);
        }, 300);
      } else {
        shcp.set_all_timestamp_diff_in_words();
      }
    }

    shcp.toolbar.common_buttons.save_button = {
      html: {
        id: 'k_button_save',
        label: "Save", 
        title: "Save to sharecopy.com and optionally share with a friend",
        css_class: ''
      },
      events: {
        self: {
          click: function(state, evt) {
            jQuery('.k_draggable .stickynote_ok').click();
            setTimeout(function() {
              jQuery('#karea form').each(function(index, form) { 
                (!form.onsubmit || form.onsubmit()) && form.submit();
              });
            }, 500);
          }
        }
      }
    };

    shcp.toolbar.render = Util.surround_method(shcp.toolbar.render, {
      before: function() {
        // if copy exist, will need to wait until "shcp.toolbar.render" to do buttons stuff
        if (SharedCopy.config.copy_exist && !SharedCopy.config.copy_owner && !SharedCopy.config.copy_writable) {
          SharedCopy.config.buttons = []
        } else {
          var buttons_string = SharedCopy.config.buttons_string;
          if (! buttons_string.match(/shcp.toolbar.common_buttons.line/)) {
            if (buttons_string.match(/shcp.toolbar.common_buttons.arrow_button/)) {
              shcp.toolbar.common_buttons.write.events.mousemove = shcp.toolbar.common_buttons.arrow_button.events.mousemove;
              shcp.toolbar.common_buttons.color_button.events.mousemove = shcp.toolbar.common_buttons.arrow_button.events.mousemove;
            }
          }
          // string parsing, not json; otherwise hafta use eval() !
          SharedCopy.config.buttons = jQuery.map(buttons_string.split(/,\s*/), function(part, index) {
            var current_container = window;
            jQuery.each(part.split(/\.+/), function(index, segment) {
              current_container = (current_container && current_container[segment]) ? current_container[segment] : null;
            });
            return current_container;
          });
          SharedCopy.config.buttons_keys = {};
          jQuery.each(SharedCopy.config.buttons, function(index, button) {
            if (button.html.label != 'Save') {
              var character = button.html.label.charAt(0);
              SharedCopy.config.buttons_keys[character] = function() {
                jQuery('#' + button.html.id).focus().click();
              }
            }
          });
        }
      }
    });
    
    // http://www.mister-pixel.com/#Content__state=is_that_simple
    try {
      document.execCommand("BackgroundImageCache", false, true);
    } catch(err) {}
    
    if (window.SharedCopy_ext && window.SharedCopy_ext.before_load) window.SharedCopy_ext.before_load();
  },

  /* 
   * When this is executed,
   * - core libraries are all loaded and ready
   * - toolbar is just about to appear
   */
  on_document_loaded: function() {
    var window_ht = jQuery(window).height() - 30;
    var body_ht = jQuery('body').height();
    SharedCopy.welcome = SharedCopy.config.embedded ? null : jQuery('<div id="k_welcome" class="k_make_remove"></div>').css({
      position: 'absolute', 
      top: (jQuery(window).scrollTop() + 10) + 'px',
      right: '10px',
      width: (jQuery(window).width() - 30) + 'px',
      height: window_ht + 'px',
      opacity: "0.8", 
      filter: "alpha(opacity=80)",
      border: '5px #DDEEDD solid',
      background: '#FFFFFF'
    }).appendTo(document.body).append(jQuery('#k_deleteme'));
    if (body_ht < window_ht) jQuery('body').height(window_ht);

    function name2input(link_element) {
      var value = link_element.title.split(/@/)[0];
      if (value == 'guest') value = "Your name";
      var input_element = jQuery('<input type="text" tabindex="1" value="' + value + '" />');
      jQuery(link_element).replaceWith(input_element);
      input_element[0].to_name = function() {
        shcp.debug(input_element.parents('.k_sticky'), jQuery('textarea', input_element.parents('.k_sticky')));
        jQuery('textarea', input_element.parents('.k_sticky')).focus(); 
        if (input_element.val() != "") {
          shcp.user.name = SharedCopy.config.user_name = input_element.val().replace(/^\s+|\s+$/g, '');
        }
        input2name(input_element);
        return true; 
      };
      input_element.select().focus().blur(input_element[0].to_name);
    }
    function update_guest_commentli(version) {
      version = version || parseInt("0" + SharedCopy.config.copy_version);
      var time_ago_span = jQuery('#page_comment' + version + ' .user span').remove();
      var new_user_link = jQuery('<span class="user">"' + shcp.user.name + '" </span>').append(time_ago_span);
      jQuery('#page_comment' + version + ' .user').replaceWith(new_user_link);
      jQuery('#page_comment' + version + ' .content .photo').html(Util.supplant('<img src="{url_base}/photos/users/guest.png" title="{user_name}" class="user_photo" alt="{user_name}" />', {
        url_base: SharedCopy.config.url_base,
        user_name: shcp.user.name
      }));
      jQuery('#page_comment' + version + ' blockquote.comment_body').each(function(index, ele) {
        var className = (ele.className || "").split(/\s+/)[0];
        jQuery('.k_highlight.' + className).each(function(index, span) {
          span.title = shcp.user.name + '@' + span.title.split('@')[1];
        });
      });
    }
    function input2name(input_element) {
      var version = parseInt("0" + SharedCopy.config.copy_version);
      update_guest_commentli(version);

      var link_element_html = Util.supplant('<span class="a k_version{version}" title="{user_name}@{user_ip} {user_clock}">"{user_name}" says...</span>', {
        version: version,
        user_name: shcp.user.name,
        user_ip: shcp.user.ip,
        user_clock: shcp.user.clock
      });
      jQuery('#karea .k_panel_top span.a.k_version' + version).unbind('click').replaceWith(link_element_html);
      if (input_element) input_element.replaceWith(link_element_html);
      jQuery('#karea .k_panel_top span.a.k_version' + version).click(function() { name2input(this); return false; });
    }
    if (!SharedCopy.config.user_name || SharedCopy.config.user_name == 'guest') {
      if (SharedCopy.config.guest_name) {
        shcp.user.name = SharedCopy.config.user_name = SharedCopy.config.guest_name;
      }
      shcp.stickynote.render_form = Util.surround_method(shcp.stickynote.render_form, {
        after: function() {
          if (!SharedCopy.config.user_name || SharedCopy.config.user_name == 'guest') {
            name2input(jQuery('#' + this.return_value + ' .k_panel_top a')[0]);
          } else {
            input2name(jQuery('#' + this.return_value + ' .k_panel_top a'));
          }
        }
      });
      SharedCopy.list_page_comment = Util.surround_method(SharedCopy.list_page_comment, {
        after: function() {
          update_guest_commentli();
        }
      });
    }

    shcp.debug("on_document_loaded", jQuery('#karea'), jQuery('#k_script').siblings());
    jQuery('#karea').each(function(index,karea) { karea.className = 'shcp_x0d63b'; });
    if (SharedCopy.config.copy_exist) {
      if (document.getElementById('k_name_value'))
        document.getElementById('k_name_value').value = SharedCopy.config.copy_name;
      if (document.getElementById('k_version_value'))
        document.getElementById('k_version_value').value = SharedCopy.config.copy_version;
      if (shcp.count_stickies() > 0) {
        var expression = "expression((document.body.clientWidth - " + parseInt(document.body.style.width) + ") + \"px\")";
        document.body.style.cssText = document.body.style.cssText + "; margin-right: " + expression + "; ";
      }
      jQuery("A.k_anchor_text").each(function(ele) {
        if (ele.href) ele.href = ele.href.substring(ele.href.indexOf('#'));
      });
      
    }
    if (window.SharedCopy_ext && window.SharedCopy_ext.on_document_loaded) window.SharedCopy_ext.on_document_loaded();
  },

  /* 
   * When this is executed,
   * - toolbar has been rendered
   */
  after_load:  function() { 
    shcp.debug("loaded!", (new Date() - this.startTime), "ms taken");
    if (SharedCopy.config.buttons.length < 1) jQuery( "#k_toolbar_buttons" ).html( '<span class="hint" style="float: right; margin: 1px 6px; color: #f0f0f0;">comments closed</span><br style="clear: right;" />');
    
    if (typeof(shcp) == 'undefined') shcp = {};

/* ref_element has title attribute containing timestamp string 
 *
 * e.g. batch update can be like
 * jQuery('#karea span.ago').each(function() { shcp.set_html_as_timestamp_diff_in_words(this); })
 */
shcp.set_html_as_timestamp_diff_in_words = function(ref_element, set_element) {
  var timestamp_string = shcp.attribute_title_value(ref_element).replace(/^.*xxx /, "");
  var timestamp = new Date(); timestamp.setTime(Date.parse(timestamp_string));
  jQuery(set_element || ref_element).html(shcp.timestamp_diff_in_words(timestamp.toGMTString()) + " ago");
};

shcp.set_all_timestamp_diff_in_words = function(jelements) {
  (jelements || jQuery('#karea span.ago')).each(function() { 
    shcp.set_html_as_timestamp_diff_in_words(this); 
  });
};

shcp.timestamp_diff_in_words = function(str_value, base_value) {
  if (! base_value) {
    var timenow = (new Date()).getTime();
  } else {
    var timenow = Date.parse(base_value);
  }  
  var timethen = Date.parse(str_value);
  var diff_minutes = (timenow - timethen) / 1000 / 60;
  return shcp.minutes_diff_in_words(diff_minutes);
};

shcp.minutes_diff_in_words = function(diff_minutes) { 
  function qualified_num(num, unit) {
    return parseInt(num) + " " + unit + (num >= 2 ? "s" : "");
  }

  if (diff_minutes == 0) {
    return "";
  } else if (diff_minutes < 1) {
    return "less than a minute";
  } else if (diff_minutes < 60) {
    return qualified_num(diff_minutes, "minute");
  } else if (diff_minutes < 1440) {
    return qualified_num((diff_minutes / 60), "hour");
  } else if (diff_minutes < 43200) {
    return qualified_num((diff_minutes / 1440), "day");
  } else {
    return "about " + qualified_num((diff_minutes / 43200), "month");
  }
};

shcp.attribute_title_value = function(element) {
  var value = (element.title || (element.attributes["title"] && element.attributes["title"].nodeValue));
  if (value && value.match(/^title=/)) {
    value = value.replace(/^title='(.*)\'>/, '$1')
  }
  return value;
};

    
    function getContentType() {
      return document.contentType || 'text/html'
    }

    function getCharacterSet() {
      return document.characterSet || document.charset || 'utf-8';
    }

    function setValues( values ) {
      for (var selector in values) {
        var ele = document.getElementById(selector);
        if (ele)
          ele.value = values[ selector ];
        else
          shcp.debug("bad ele", selector, ele);
      }
    }

    function getDoctype() {
      if (document.doctype)
        return Util.supplant('<!DOCTYPE HTML PUBLIC "{publicId}" "{systemId}">', {
          publicId: document.doctype.publicId,
          systemId: document.doctype.systemId
        });

      if (document.compatMode == 'CSS1Compat')
        // IE6 returns null for document.doctype
        return '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">';

      if (document.compatMode == 'BackCompat')
        return '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">';

      // if not, supplant will leave a {doctype} string
      return "";
    }

    function getHtmlValue() {
      return Util.supplant("{doctype}\n<html>\n{content}\n</html>", {
        doctype: getDoctype(),
        content: jQuery("html")[0].innerHTML
      });
    }
    
    function get_position(ele, div_id) {
      if (!div_id) div_id = shcp.get_unique_domid("secretdiv");
      var html = "<div style='position: relative; left: 0; top: 0px;' id='" + div_id + "' />";
      if (ele.childNodes) {
        jQuery(html).insertBefore(ele.childNodes[0]);
      } else {
        jQuery(ele).append(html);
      }
      var placeholder = jQuery('#' + div_id);
      var value = placeholder.offset();
      placeholder.remove();
      return value;
    }
    
    /* its important to set the stage ONCE; so everyone can comms with no discrepancies */
    function fix_documentwidth() {
      var style_field = document.getElementById('k_body_style_value');
      var width_field = document.getElementById('k_width_value');
      if (style_field) {
        if (style_field.value != '') {
          shcp.debug("already has k_body_style: " + style_field.value);
        } else {
          params = { "width":jQuery('html body')[0].offsetWidth, "margin-left": get_position(document.body).left };
          style_field.value = Util.supplant( "width: {width}px; margin-left: {margin-left}px; " +
            "margin-right: expression((document.body.clientWidth - {width}) + 'px'); ", params);
          shcp.debug("remember k_body_style: " + style_field.value);
          jQuery('html body').css(params);
        }
        shcp.debug("fix_documentwidth", "style");
        return style_field.value;
        
      } else if (width_field) {
        if ((width_field.value * 1) > 1) {
          //alert("already has width: " + width_field.value);
        } else {
          width_field.value = Graphics.getInnerSize().x;
          //alert("remember width: " + width_field.value);
        }
        shcp.debug("fix_documentwidth", "width");
        return "margin-right: expression((document.body.clientWidth - " + 
             width_field.value + ") + 'px'); width: " + ((width_field.value * 1) - 8) + "px; ";
        // tested between FF2 and IE6    
      } else {
        // unsupported copy
        shcp.debug("fix_documentwidth", "fail");
        return ""
      }
    }
    
    function k_no_external_js() {
      // remove all javascript code except ours
      var list = jQuery("script").filter( function () { return typeof( this.id ) != "string" || !this.id.match(/^k_script/); });
      
      list.each( function (i) {
        shcp.debug("remove js: " + this.innerHTML.substring(0, 80));
        if (this.src && this.tagName.toLowerCase() != "embed") {
          this.removeAttribute("src"); // IE-friendlier than "src = '#'"
        }
        if (this.href) {
          this.removeAttribute("href"); // IE-friendlier than "src = '#'"
        }
        jQuery(this).remove();
      });
      return list.length;
    }
    
    function changePageTitle() {
      var title_ele = document.getElementsByTagName("title");
      if (title_ele) {
        title_ele = title_ele[0];
        if (title_ele && title_ele.text) {
          title_ele.text = "SharedCopy of " + title_ele.text;
        } else {
          if (! title_ele) {
            title_ele = document.createElement("title");
            document.body.appendChild(title_ele);
          }
          title_ele.text = "SharedCopy: " + window.location.host;
        }
      }
    }

    function submit_k_form() {
      jQuery("iframe", document).filter(function(a, b) { return this.src.match(/firebug/); }).addClass("k_make_remove");

      var custom_fields = jQuery('#karea #custom_toolbar input,#karea #custom_toolbar textarea').hide().remove();
      jQuery(".k_make_blank").html("&nbsp;");
      jQuery('.k_make_remove,.ui-resizable-handle,#karea #custom_toolbar').each(function(index, ele) { ele.parentNode && ele.parentNode.removeChild(ele); });
      
      jQuery('.ui-resizable').removeClass('ui-resizable');
      jQuery('.ui-draggable').removeClass('ui-draggable');
      
      if (jQuery('#karea .k_sticky, #karea > div > img').length > 0) {
        // when the first stickies are introduced, that's when 
        // we need to ensure width for absolute position's integrity
        fix_documentwidth();
      }

      setValues({
        "k_html_value"          : ""
      });

      k_no_external_js();
      setValues({
        "k_content_type_value"        : getContentType(),
        "k_charset_value"             : getCharacterSet(),
        "k_k_count_value"             : shcp.k_count,
        "k_deleted_comment_urls_value": (shcp.deleted_comments ? shcp.deleted_comments.urls.toString() : ''),
        "k_html_value"                : getHtmlValue(),
        "k_user_login_value"          : shcp.user.name
      });

      shcp.k_count_history = []; // removes popup that blocks user from leaving page unsaved
    	jQuery('#k_toolbar_buttons').html('<div ' + 
    	  'style="color: #000; font-size: 1.5em; padding: 10px 15px;">' + 
    	  'Saving...' + 
    	  '</div>');
      custom_fields.appendTo('#karea form');
      jQuery(document.body || document).css('cursor', 'wait');
      return true;
    }
    // fix broken stickies (Internet Explorer?) with wrong parent (#k_toolbar) instead of (#karea)
    jQuery('#karea #k_toolbar .k_sticky').parent().appendTo('#karea');
    // fix old copies, remove old page_comments summary
    jQuery('#k_toolbar_list > li').remove();
    // fix old copies, updating CSS classname, and add width if missing
    jQuery('#karea .k_shadow.k_hover.k_draggable > div').addClass('k_sticky').each(function(index, ele) { 
      if (ele.style && ! ele.style.width) {
        ele.parentNode.style.width = '252px';
        ele.style.width = '250px';
      }
    });
    // fix old copies, moving the IMG into a wrapper span[@style='float: right']
    jQuery('.k_sticky').each(function(index, notediv) {
      var old_buttons = jQuery('.k_panel_top > img', notediv)
      if (old_buttons[0]) {
        // move to new structure
        jQuery(old_buttons[0]).addClass("minimize_button");
        var parent = old_buttons[0].parentNode;
        var span = jQuery("<span style='float: right;'></span>").appendTo(parent);
        span.append(old_buttons);
        parent.appendChild(document.createElement('br'));
      }
    });
    
    function remove_page_comment_li(jelements) {
      if (jelements && jQuery('.comment_body', jelements).length < 1) {
        var grandparents = jelements.parent();
        shcp.debug("jelements.remove", jelements);
        jelements.remove();
        if (grandparents.children().length < 1) {
          shcp.debug("grandparents.remove", grandparents);
          grandparents.remove();
        }
        SharedCopy.update_comments_count();
      } else {
        shcp.debug("no remove", (jelements ? jQuery('.comment_body', jelements).length : null), jelements);
      }
    }
    shcp.toolbar.remove = Util.surround_method(shcp.toolbar.remove, {
      before: function(index) {
        this.li_page_comment = jQuery('#karea #page_comments .k_coupling' + index).parents('li.page_comment');
        shcp.debug("shcp.toolbar.remove", [index, this.li_page_comment]);
      },
      after: function(index) {
        shcp.debug("shcp.toolbar.remove", [index, this.li_page_comment]);
        if (this.li_page_comment) remove_page_comment_li(this.li_page_comment);
      }
    });
    
    ///
    (function() {
      // add close button to all sticky notes
      function add_close_button() {
        // get all sticky notes
        jQuery('.k_sticky').each(function(index, notediv) {
          var jnotediv = jQuery(notediv);
          // we need this anchor, hence not diving 
          // directly into ".k_sticky .k_panel_top"
          var anchor = jnotediv.children('a')[0].name;
          jQuery('.k_panel_top > span:last', notediv).each(function(index, top_panel) {
            var jtop_panel = jQuery(top_panel);
            jtop_panel.append("\n" + Util.supplant(SharedCopy.config.html.sticky_note_close, { url_basepath: SharedCopy.config.url_basepath }));
            jtop_panel.children('.close_button')[0].onclick = null;
            jtop_panel.children('.close_button').click(function(evt) {
              if (confirm("Remove this comment?\n\nComment will be deleted permanently only when you save.")) {
                shcp.remove_stickynote(this);
                shcp.deleted_comments.addUrl(anchor);
              }
            });
          });
        });
      }

      function DeletedComments() {
        this.addUrl = function (url) {
          this.urls.push(url);
        }

        this.toString = function() {
          return this.urls.join(',');
        }

        this.urls = [];
      }
      shcp.deleted_comments = new DeletedComments();
      if (SharedCopy.config.copy_owner) add_close_button();
    })();
    ///
    
    setTimeout(function() {
      if (! jQuery('#karea #k_comments_showhide')[0]) {
        jQuery(SharedCopy.config.html.comments_showhide).appendTo('#k_toolbar_inner');
      }
      
      jQuery('#k_comments_label_row').html(
        '<a id="k_comments_label" href="#" onclick="return false;">no comments</a>'
      ).siblings().remove();
      if (jQuery('#k_toolbar_list #page_comments li')[0]) {
        jQuery('#k_comments_label_row').append(" &middot; " +
          Util.supplant(SharedCopy.config.html.comments_rss, { 
            rss_url: SharedCopy.config.feed_url,
            url_base: SharedCopy.config.url_base 
          })
        );
      };
      
      var toolbar = jQuery('#k_toolbar');
      var toolbar_label = jQuery('#karea #k_comments_label');
      var toolbar_list = jQuery('#karea #k_toolbar_list');
      toolbar_list.hide();
      toolbar.removeClass('k_sunken').addClass('k_shadow');
      toolbar_label.removeClass('down').click(function() {
        toolbar.toggleClass('k_sunken').toggleClass('k_shadow');
        toolbar_label.toggleClass('down');
        var ele = toolbar_list.toggle();        
        if (ele.css('display') == 'block') {
          var position = get_position(toolbar[0]);
          toolbar.css({ position: 'absolute', top: position.top, left: position.left});
          if (window.onscroll) window.onscroll;
          if (window.onresize) window.onresize;
        } else {
          shcp.toolbar.position_toolbar();
        }
        return false;
      });
      SharedCopy.update_comments_count();
      
      shcp.stickynote.on_ok = Util.surround_method(shcp.stickynote.on_ok, { 
        before: function(ele) {
          var parent = jQuery(ele).parents('.k_sticky').parent()[0];
          var input = jQuery('.k_panel_top input', parent)[0];
          if (input) input.to_name();
        },
        after: function(ele) {
          var parent = jQuery(ele).parents('.k_sticky').parent()[0];
          var matched = null;
          if (parent && (matched = parent.id.match(/\D+(\d+)$/))) {
            matched = matched[1];
          }
          if (this.return_value) SharedCopy.list_page_comment(this.return_value, false, matched);
        }
      });
      
      shcp.highlight_selected = Util.surround_method(shcp.highlight_selected, {
        after: function(ele) {
          if (this.return_value) SharedCopy.list_page_comment(shcp.Hilite.selectedText, true);
        }
      });
      
      shcp.toolbar.exec_undo = Util.surround_method(shcp.toolbar.exec_undo, {
        before: function(k_count) {
          this.parents = jQuery('.k_coupling' + k_count).parents('li.page_comment');
        },
        after: function(k_count) {
          remove_page_comment_li(this.parents);
          this.parents = null;
        }
      });
      
      jQuery('#karea form').each(function(index, form) {
        form.className = 'shcp_x59e80a8e5230f9f147c35dc88';
        form.action = SharedCopy.config.url_base + "/k/save";
        form.method = "POST";
        form.onsubmit = submit_k_form;
        
        var form_fields = ["content_type", 
                           "charset", 
                           "name", 
                           "k_count", 
                           "version", 
                           "deleted_comment_urls", 
                           "html", 
                           "body_style", 
                           "url", 
                           "tag_string", 
                           "writable",
                           "user_login",
                           "ticket_from",
                           "buttons_string",
                           "api"];
        jQuery.each(form_fields, function(index, field_name) {
          var input_id = "k_" + field_name + "_value";
          if (jQuery("#karea #" + input_id + ",#karea form input[name='" + field_name + "']")[0]) {
            // older form fields have slightly different input[@id], so we check for @id and @name
          } else {
            jQuery("<input type='hidden' style='display:none' name='" + field_name + "' id='" + input_id + "' />").appendTo(form);
          }
        });
      });

      if (jQuery("#karea form input[name='url']").val() == '') {
        jQuery("#karea form input[name='url']").val(window.location.href);
        changePageTitle();
        jQuery('#k_toolbar_inner #k_toolbar_footer').remove();
        jQuery('#k_toolbar_inner').append("<div id='k_toolbar_footer' " + 
          "style='text-align: left; padding-top: 5px; color: #ffffff; font-size: 12px; font-weight: bold; '>" + 
          "Click anywhere on this page to comment!" + 
        "</div>");
        shcp.remove_toolbar = function() { window.location = window.location.href; };
      } else {
        jQuery('#k_toolbar_inner #k_toolbar_footer').remove();
        var original_url = jQuery("#karea form input[name='url']").val();
        jQuery('#k_toolbar_inner').append(Util.supplant(SharedCopy.config.html.toolbar_footer, {
          original_url: original_url,
          help_url: SharedCopy.config.url_base + '/public/contact'
        }));
        shcp.remove_toolbar = function() { window.location = original_url; };
      }
      
      if (jQuery("#karea form input[name='api']")[0]) {
        jQuery("#karea form input[name='api']").val(SharedCopy.config.param_id);
      }
      
      if (jQuery("#karea form input[name='buttons_string']").val() == '') {
        jQuery("#karea form input[name='buttons_string']").val(SharedCopy.config.buttons_string);
      }
      
      if (window.SharedCopyExtender) {
        if (window.SharedCopyExtender.on_document_loaded) window.SharedCopyExtender.on_document_loaded();
      } else if (SharedCopy.iframe_mode) {
        // don't load related
      } else if (SharedCopy.config.user_email) {
        // don't load related
      } else {
        function loadjs(url, id, className, callback_fn) {
          SharedCopy.onJSON = callback_fn;
          var script=document.createElement('script');
          if (id) script.id = id;
          if (className) script.className = className;
          script.src= url +
            (SharedCopy.onJSON ? '&callback=SharedCopy.onJSON' : '') +
            '&r=' + Math.random() + 
            '';
          document.body.appendChild(script);
          return script;
        }

        var related_js = SharedCopy.config.url_base + 
          '/javascripts/related?url=' + encodeURIComponent(window.location.href);
        if (SharedCopy.config.param_id) related_js = related_js + '&id=' + encodeURIComponent(SharedCopy.config.param_id);
        loadjs(related_js, 'k_script_related', 'k_make_remove');
        var sticky_parents = jQuery('.k_sticky').parent();
        sticky_parents.css('z-index', 1000000); // old copies' stickies has bigger zindex
        shcp.stickynote.make_resizable_draggable(sticky_parents);
        
        // add REPLY links to each existing sticky note
        jQuery('.k_sticky .k_panel_bottom').append('<a class="k_make_remove" href="#">reply</a>').children('img').remove();
        
        // add BEHAVIORS to REPLY links
        function on_click_reply(evt) {
          var sticky = jQuery(this).parents('.k_shadow');
          var reply_class = "replyto_" + sticky[0].id;
          var combined_height = 0;
          jQuery('.' + reply_class).each(function(index, ele) {
            combined_height += jQuery(ele).height();
          });

          window.k_count += 1;
          var divId = shcp.stickynote.render_form({ 
            x: (sticky.offset().left),  y: ((jQuery(this).offset().top - 1) + combined_height)
            // x: (sticky.offset().left + 10), y: (sticky.offset().top + sticky.height() + combined_height)
            }, {verb: 'replies'});
          jQuery('#' + divId).addClass(reply_class);

          // jQuery(this).unbind('click').remove();
          evt.stopPropagation();
          return false;
        }
        jQuery('.k_sticky .k_panel_bottom a.k_make_remove').click(on_click_reply);
        
        // add ANCHOR lines to each existing sticky note without an anchor line
        jQuery('.k_sticky').parent().each(function(index, ele) {
          var num = null;
          if (ele.id && (num = ele.id.match(/\d+/)[0])) {
            var line_id = 'line' + num;
            if (! document.getElementById(line_id)) {
              var position = jQuery('.k_sticky', ele).offset();
              position = new Graphics.Point(position.left, position.top);
              var lineObj = shcp.render_drawing(line_id, 'line', num);
              Graphics.draw(lineObj, position, position, 'line');
            }
          }
        });
      }
      
      shcp.remember_dimensions('img');
      if (SharedCopy.config.param_t) jQuery("input[name='tag_string']").val(SharedCopy.config.param_t);
      jQuery("#karea form input[name='writable']").val(SharedCopy.config.copy_writable ? "1" : "0");
      
      var target = jQuery('#k_toolbar');
      var animate_params = { height: target.height() + 'px', width: target.width() + 'px' }
      if (SharedCopy.config.copy_exist) animate_params.left = target.offset().left + 'px';
      if (SharedCopy.welcome) {
        SharedCopy.welcome.animate(animate_params, 600, 'swing', function() { SharedCopy.welcome.remove(); SharedCopy.welcome = null; });
      }
      if (SharedCopy.config.swap_submit) SharedCopy.tickets.swap_submit();
      
      if (! SharedCopy.config.copy_exist) {
        setTimeout(function() {
          jQuery.each(jQuery("input[name='tag_string']").val().split(/\s+/), function(index, item) {
            shcp.debug(index, item);
            if (item == '/save') shcp.toolbar.common_buttons.save_button.events.self.click();
          });
        }, 800);
      } else {
        jQuery("input[name='tag_string']").val(SharedCopy.config.tag_string);
      }
    }, 100);
    
    jQuery(document).keydown(function(evt) {
      if (typeof evt == 'undefined') evt = window.event;
      if (evt.ctrlKey || evt.altKey || evt.metaKey) {
        // skip other meta
      } else if ((evt.originalTarget || evt.target).tagName.match(/textarea|input/i)) {
        // skip input
      } else if (evt.shiftKey) {
        var charCode = evt.keyCode ? evt.keyCode : evt.which;
        var fn = SharedCopy.config.buttons_keys[String.fromCharCode(charCode)];
        if (fn) {
          fn();
          return false;
        }
      }
      return true;
    });
    if (document.activeElement) jQuery(document.activeElement).blur(); // current webpage input element having focus? blur!
    
    shcp.debug("after_load", jQuery('#karea'), jQuery('#k_script').siblings());
    if (window.SharedCopy_ext && window.SharedCopy_ext.after_load) window.SharedCopy_ext.after_load();
  },
  
  list_page_comment: function(content, is_quote, k_count) {
    k_count = k_count || shcp.k_count;
    var version = parseInt("0" + document.getElementById('k_version_value').value);
    var toolbar = jQuery('#k_toolbar_list');
    var container_ol = toolbar.children('#page_comments');
    var first_comment = false;
    if (! container_ol[0]) {
      first_comment = true;
      container_ol = jQuery('<ol id="page_comments"></ol>');
      if (toolbar.children()[0]) {
        container_ol.insertBefore(toolbar.children()[0]);
      } else {
        toolbar.append(container_ol);
      }
    }
    var content_html = Util.supplant(SharedCopy.config.html.comment_li_body, {
      content_css: ("k_coupling" + k_count + " comment_body"),
      link_css: ("k_anchor_text textv" + version + " k_sticky" + version),
      tag_name: (is_quote ? 'blockquote' : 'p'),
      body_url: "#shcp" + k_count,
      body: content
    });
    
    var li_id = 'page_comment' + version;
    var container_li = container_ol.children('#' + li_id);
    if (! container_li[0]) {
      var li_html = Util.supplant(SharedCopy.config.html.comment_li, {
        li_id: li_id,
        li_class: 'page_comment' + (first_comment ? ' first_comment' : ''),
        user_url: SharedCopy.config.url_base + "/~" + shcp.user.name,
        user_name: shcp.user.name,
        user_picture_url: SharedCopy.config.url_base + "/photos/users/" + shcp.user.name + ".png",
        datetime: (new Date()).toGMTString()
      });
      container_li = jQuery(li_html).appendTo(container_ol);
      jQuery('span.ago', container_li).each(function() { shcp.set_html_as_timestamp_diff_in_words(this); });
    }
    jQuery(content_html).appendTo(jQuery('.content .text', container_li));
    SharedCopy.update_comments_count();
  },
  debugging: false,
  
  tickets: {
    swap_submit: function(selector) {
      jQuery('#karea form').each(function(index, form) {
        shcp.debug("Swapping submit with ", form);
        SharedCopy.tickets.old_submit = form.onsubmit;
        function new_submit() {
          SharedCopy.tickets.render_getemailtoresponse(function(value) {
            jQuery('input#k_ticket_from_value').val(value);
            form.onsubmit = SharedCopy.tickets.old_submit;
            setTimeout(function() { form.onsubmit(); form.submit(); }, 100);
            return false;
          });
          return false;
        }
        form.onsubmit = new_submit;
      });
    },
    render_getemailtoresponse: function(onsubmit, oncancel) {
      (function($){
        // http://test.learningjquery.com/center.html
        $.fn.position_center = function(options) {
          var pos = {
            sTop : function() {
              return window.pageYOffset || document.documentElement && document.documentElement.scrollTop ||	document.body.scrollTop;
            },
            wHeight : function() {
              return window.innerHeight || document.documentElement && document.documentElement.clientHeight || document.body.clientHeight;
            }
          };
          return this.each(function(index) {
            if (index == 0) {
              var $this = $(this);
              var elHeight = $this.height();
              var elTop = pos.sTop() + (pos.wHeight() / 2) - (elHeight / 2);
              $this.css({
                position: 'absolute',
                margin: '0',
                top: elTop,
                left: (($(window).width() - $this.width()) / 2) + 'px'
              });
            }
          });
        };
      })(jQuery);
      if (jQuery('#getemailtoresponse').length > 0) return false;
      var form = jQuery(
        '<form id="getemailtoresponse">' + "\n" +
        '<label for="getemailtoresponse_textfield">' + "\n" +
        'Enter your email to track this feedback:' + "\n" +
        '</label>' + "\n" +
        '<input type="text" name="email" value="" id="getemailtoresponse_textfield" />' + "\n" +
        '<input type="submit" id="getemailtoresponse_ok" value="Ok" /> or' + "\n" +
        '<a href="" id="getemailtoresponse_cancel">Cancel</a>' + "\n" +
        '</form>'
      ).
      appendTo(document.body).
      position_center();
      var input = form.children('input#getemailtoresponse_textfield');
      function submit_function(evt) {
        var value = input.val();
        if (value.match(/^\S+\@\S+\.\w+/)) {
          form.remove();
          if (onsubmit) return onsubmit(value);
        } else {
          alert("Oops, please enter a valid email address?");
          return false;
        }
      }
      form.submit(submit_function);
      form.children('input#getemailtoresponse_ok').click(submit_function);
      form.children('a#getemailtoresponse_cancel').click(function() {
        var value = input.val();
        form.remove();
        if (oncancel) return oncancel(value);
      });
      input.focus().click(function(ele) { input.focus(); });
    }
  },
  /*
   * Other custom properties
   */
  config: {
    copy_exist: false, 
    copy_owner: false,
    copy_writable: true,
    copy_name: null,
    copy_version: null,
    tag_string: null,
    feed_url: null,
    param_t: null,
    param_id: null,    
    url_base:     "http://sharedcopy.com",
    url_basepath: "http://sharedcopy.com/sharedcopy-core-js",
    css_href:     "http://sharedcopy.com/stylesheets/k.css?2",
    user_name: "guest",
    guest_name: null,
    user_ip: "38.107.xxx.xxx",
    embedded: false,
    allow_click: false,
    swap_submit: false,
    default_button: "k_button_write",
    buttons_string: "shcp.toolbar.common_buttons.pointer, shcp.toolbar.common_buttons.write, shcp.toolbar.common_buttons.mark, shcp.toolbar.common_buttons.line, shcp.toolbar.common_buttons.box, shcp.toolbar.common_buttons.undo, SharedCopy.button_1377_77dcfe66b36ea375953804c3e5c39544, SharedCopy.button_1_587ba288f62c0e25d64e1df2229f5b7f, shcp.toolbar.common_buttons.save_button",
    cursors: {
      button_1_587ba288f62c0e25d64e1df2229f5b7f: "crosshair",
      button_1377_77dcfe66b36ea375953804c3e5c39544: "auto",

    	k_button_arrow:  'crosshair',
    	k_button_color:  'crosshair',
    	k_button_write:  'crosshair',
    	k_button_line:   'crosshair',
    	k_button_box:    'crosshair',
    	k_button_circle: 'crosshair'
    },
    show_toolbar: true
  }
};

/* JsButton ["shcp.toolbar.common_buttons.pointer", "shcp.toolbar.common_buttons.write", "shcp.toolbar.common_buttons.mark", "shcp.toolbar.common_buttons.line", "shcp.toolbar.common_buttons.box", "shcp.toolbar.common_buttons.undo", "shcp.toolbar.common_buttons.save_button", "SharedCopy.button_1_587ba288f62c0e25d64e1df2229f5b7f", "SharedCopy.button_1377_77dcfe66b36ea375953804c3e5c39544"] */

SharedCopy.button_1_587ba288f62c0e25d64e1df2229f5b7f = {
  html: {
    id: "button_1_587ba288f62c0e25d64e1df2229f5b7f",
    label: "Delete",
    title: "Click on any part of the webpage to remove",
    style: "background: url(http://sharedcopy.com/images/icons/famfamfam/silk/layout_delete.png) no-repeat top;",
    css_class: ''
  },
  events: {
  mousedown: function(state, evt) {
    var target = evt.target;
    jQuery(target).fadeOut('slow', function() { jQuery(this).remove(); });
    return false;
  },
  mouseover: function(state, evt) {
    var target = evt.target;
    if (!target.old_bg) target.old_bg = jQuery(target).css('background');
    jQuery(target).css('background', 'rgb(255, 255, 128)');
  },
  mouseout: function(state, evt) {
    var target = evt.target;
    jQuery(target).css('background', target.old_bg || '');
  }
}


};

SharedCopy.button_1377_77dcfe66b36ea375953804c3e5c39544 = {
  html: {
    id: "button_1377_77dcfe66b36ea375953804c3e5c39544",
    label: "Edit",
    title: "Modify data on a webpage, press ESC to finish editing",
    style: "background: url(http://sharedcopy.com/images/icons/famfamfam/silk/page_white_edit.png) no-repeat top;",
    css_class: ''
  },
  events: {
  mousedown: function() { return true; },
  mousemove: function() { return true; },
  mouseup: function() { return true; },
  click: function() { return true; },
  self: {
    click: function(evt) {
      document.body.contentEditable = true;
      document.designMode = 'on';
      jQuery(document).keypress(function(e){
        var key = window.event ? event.keyCode : e.keyCode;
        var esc = window.event ? 27 : e.DOM_VK_ESCAPE;
        if (key == esc){
          document.designMode = 'off';
          document.body.contentEditable = false;
          jQuery('div#k_toolbar_buttons button#k_button_point').click();
          jQuery('#k_button_point').click();
          return true;
        }
      });
    }
  }
}

};


/* include: jquery-1.3.2.min.js */
/*
 * jQuery JavaScript Library v1.3.2
 * http://jquery.com/
 *
 * Copyright (c) 2009 John Resig
 * Dual licensed under the MIT and GPL licenses.
 * http://docs.jquery.com/License
 *
 * Date: 2009-02-19 17:34:21 -0500 (Thu, 19 Feb 2009)
 * Revision: 6246
 */
(function(){var l=this,g,y=l.jQuery,p=l.$,o=l.jQuery=l.$=function(E,F){return new o.fn.init(E,F)},D=/^[^<]*(<(.|\s)+>)[^>]*$|^#([\w-]+)$/,f=/^.[^:#\[\.,]*$/;o.fn=o.prototype={init:function(E,H){E=E||document;if(E.nodeType){this[0]=E;this.length=1;this.context=E;return this}if(typeof E==="string"){var G=D.exec(E);if(G&&(G[1]||!H)){if(G[1]){E=o.clean([G[1]],H)}else{var I=document.getElementById(G[3]);if(I&&I.id!=G[3]){return o().find(E)}var F=o(I||[]);F.context=document;F.selector=E;return F}}else{return o(H).find(E)}}else{if(o.isFunction(E)){return o(document).ready(E)}}if(E.selector&&E.context){this.selector=E.selector;this.context=E.context}return this.setArray(o.isArray(E)?E:o.makeArray(E))},selector:"",jquery:"1.3.2",size:function(){return this.length},get:function(E){return E===g?Array.prototype.slice.call(this):this[E]},pushStack:function(F,H,E){var G=o(F);G.prevObject=this;G.context=this.context;if(H==="find"){G.selector=this.selector+(this.selector?" ":"")+E}else{if(H){G.selector=this.selector+"."+H+"("+E+")"}}return G},setArray:function(E){this.length=0;Array.prototype.push.apply(this,E);return this},each:function(F,E){return o.each(this,F,E)},index:function(E){return o.inArray(E&&E.jquery?E[0]:E,this)},attr:function(F,H,G){var E=F;if(typeof F==="string"){if(H===g){return this[0]&&o[G||"attr"](this[0],F)}else{E={};E[F]=H}}return this.each(function(I){for(F in E){o.attr(G?this.style:this,F,o.prop(this,E[F],G,I,F))}})},css:function(E,F){if((E=="width"||E=="height")&&parseFloat(F)<0){F=g}return this.attr(E,F,"curCSS")},text:function(F){if(typeof F!=="object"&&F!=null){return this.empty().append((this[0]&&this[0].ownerDocument||document).createTextNode(F))}var E="";o.each(F||this,function(){o.each(this.childNodes,function(){if(this.nodeType!=8){E+=this.nodeType!=1?this.nodeValue:o.fn.text([this])}})});return E},wrapAll:function(E){if(this[0]){var F=o(E,this[0].ownerDocument).clone();if(this[0].parentNode){F.insertBefore(this[0])}F.map(function(){var G=this;while(G.firstChild){G=G.firstChild}return G}).append(this)}return this},wrapInner:function(E){return this.each(function(){o(this).contents().wrapAll(E)})},wrap:function(E){return this.each(function(){o(this).wrapAll(E)})},append:function(){return this.domManip(arguments,true,function(E){if(this.nodeType==1){this.appendChild(E)}})},prepend:function(){return this.domManip(arguments,true,function(E){if(this.nodeType==1){this.insertBefore(E,this.firstChild)}})},before:function(){return this.domManip(arguments,false,function(E){this.parentNode.insertBefore(E,this)})},after:function(){return this.domManip(arguments,false,function(E){this.parentNode.insertBefore(E,this.nextSibling)})},end:function(){return this.prevObject||o([])},push:[].push,sort:[].sort,splice:[].splice,find:function(E){if(this.length===1){var F=this.pushStack([],"find",E);F.length=0;o.find(E,this[0],F);return F}else{return this.pushStack(o.unique(o.map(this,function(G){return o.find(E,G)})),"find",E)}},clone:function(G){var E=this.map(function(){if(!o.support.noCloneEvent&&!o.isXMLDoc(this)){var I=this.outerHTML;if(!I){var J=this.ownerDocument.createElement("div");J.appendChild(this.cloneNode(true));I=J.innerHTML}return o.clean([I.replace(/ jQuery\d+="(?:\d+|null)"/g,"").replace(/^\s*/,"")])[0]}else{return this.cloneNode(true)}});if(G===true){var H=this.find("*").andSelf(),F=0;E.find("*").andSelf().each(function(){if(this.nodeName!==H[F].nodeName){return}var I=o.data(H[F],"events");for(var K in I){for(var J in I[K]){o.event.add(this,K,I[K][J],I[K][J].data)}}F++})}return E},filter:function(E){return this.pushStack(o.isFunction(E)&&o.grep(this,function(G,F){return E.call(G,F)})||o.multiFilter(E,o.grep(this,function(F){return F.nodeType===1})),"filter",E)},closest:function(E){var G=o.expr.match.POS.test(E)?o(E):null,F=0;return this.map(function(){var H=this;while(H&&H.ownerDocument){if(G?G.index(H)>-1:o(H).is(E)){o.data(H,"closest",F);return H}H=H.parentNode;F++}})},not:function(E){if(typeof E==="string"){if(f.test(E)){return this.pushStack(o.multiFilter(E,this,true),"not",E)}else{E=o.multiFilter(E,this)}}var F=E.length&&E[E.length-1]!==g&&!E.nodeType;return this.filter(function(){return F?o.inArray(this,E)<0:this!=E})},add:function(E){return this.pushStack(o.unique(o.merge(this.get(),typeof E==="string"?o(E):o.makeArray(E))))},is:function(E){return !!E&&o.multiFilter(E,this).length>0},hasClass:function(E){return !!E&&this.is("."+E)},val:function(K){if(K===g){var E=this[0];if(E){if(o.nodeName(E,"option")){return(E.attributes.value||{}).specified?E.value:E.text}if(o.nodeName(E,"select")){var I=E.selectedIndex,L=[],M=E.options,H=E.type=="select-one";if(I<0){return null}for(var F=H?I:0,J=H?I+1:M.length;F<J;F++){var G=M[F];if(G.selected){K=o(G).val();if(H){return K}L.push(K)}}return L}return(E.value||"").replace(/\r/g,"")}return g}if(typeof K==="number"){K+=""}return this.each(function(){if(this.nodeType!=1){return}if(o.isArray(K)&&/radio|checkbox/.test(this.type)){this.checked=(o.inArray(this.value,K)>=0||o.inArray(this.name,K)>=0)}else{if(o.nodeName(this,"select")){var N=o.makeArray(K);o("option",this).each(function(){this.selected=(o.inArray(this.value,N)>=0||o.inArray(this.text,N)>=0)});if(!N.length){this.selectedIndex=-1}}else{this.value=K}}})},html:function(E){return E===g?(this[0]?this[0].innerHTML.replace(/ jQuery\d+="(?:\d+|null)"/g,""):null):this.empty().append(E)},replaceWith:function(E){return this.after(E).remove()},eq:function(E){return this.slice(E,+E+1)},slice:function(){return this.pushStack(Array.prototype.slice.apply(this,arguments),"slice",Array.prototype.slice.call(arguments).join(","))},map:function(E){return this.pushStack(o.map(this,function(G,F){return E.call(G,F,G)}))},andSelf:function(){return this.add(this.prevObject)},domManip:function(J,M,L){if(this[0]){var I=(this[0].ownerDocument||this[0]).createDocumentFragment(),F=o.clean(J,(this[0].ownerDocument||this[0]),I),H=I.firstChild;if(H){for(var G=0,E=this.length;G<E;G++){L.call(K(this[G],H),this.length>1||G>0?I.cloneNode(true):I)}}if(F){o.each(F,z)}}return this;function K(N,O){return M&&o.nodeName(N,"table")&&o.nodeName(O,"tr")?(N.getElementsByTagName("tbody")[0]||N.appendChild(N.ownerDocument.createElement("tbody"))):N}}};o.fn.init.prototype=o.fn;function z(E,F){if(F.src){o.ajax({url:F.src,async:false,dataType:"script"})}else{o.globalEval(F.text||F.textContent||F.innerHTML||"")}if(F.parentNode){F.parentNode.removeChild(F)}}function e(){return +new Date}o.extend=o.fn.extend=function(){var J=arguments[0]||{},H=1,I=arguments.length,E=false,G;if(typeof J==="boolean"){E=J;J=arguments[1]||{};H=2}if(typeof J!=="object"&&!o.isFunction(J)){J={}}if(I==H){J=this;--H}for(;H<I;H++){if((G=arguments[H])!=null){for(var F in G){var K=J[F],L=G[F];if(J===L){continue}if(E&&L&&typeof L==="object"&&!L.nodeType){J[F]=o.extend(E,K||(L.length!=null?[]:{}),L)}else{if(L!==g){J[F]=L}}}}}return J};var b=/z-?index|font-?weight|opacity|zoom|line-?height/i,q=document.defaultView||{},s=Object.prototype.toString;o.extend({noConflict:function(E){l.$=p;if(E){l.jQuery=y}return o},isFunction:function(E){return s.call(E)==="[object Function]"},isArray:function(E){return s.call(E)==="[object Array]"},isXMLDoc:function(E){return E.nodeType===9&&E.documentElement.nodeName!=="HTML"||!!E.ownerDocument&&o.isXMLDoc(E.ownerDocument)},globalEval:function(G){if(G&&/\S/.test(G)){var F=document.getElementsByTagName("head")[0]||document.documentElement,E=document.createElement("script");E.type="text/javascript";if(o.support.scriptEval){E.appendChild(document.createTextNode(G))}else{E.text=G}F.insertBefore(E,F.firstChild);F.removeChild(E)}},nodeName:function(F,E){return F.nodeName&&F.nodeName.toUpperCase()==E.toUpperCase()},each:function(G,K,F){var E,H=0,I=G.length;if(F){if(I===g){for(E in G){if(K.apply(G[E],F)===false){break}}}else{for(;H<I;){if(K.apply(G[H++],F)===false){break}}}}else{if(I===g){for(E in G){if(K.call(G[E],E,G[E])===false){break}}}else{for(var J=G[0];H<I&&K.call(J,H,J)!==false;J=G[++H]){}}}return G},prop:function(H,I,G,F,E){if(o.isFunction(I)){I=I.call(H,F)}return typeof I==="number"&&G=="curCSS"&&!b.test(E)?I+"px":I},className:{add:function(E,F){o.each((F||"").split(/\s+/),function(G,H){if(E.nodeType==1&&!o.className.has(E.className,H)){E.className+=(E.className?" ":"")+H}})},remove:function(E,F){if(E.nodeType==1){E.className=F!==g?o.grep(E.className.split(/\s+/),function(G){return !o.className.has(F,G)}).join(" "):""}},has:function(F,E){return F&&o.inArray(E,(F.className||F).toString().split(/\s+/))>-1}},swap:function(H,G,I){var E={};for(var F in G){E[F]=H.style[F];H.style[F]=G[F]}I.call(H);for(var F in G){H.style[F]=E[F]}},css:function(H,F,J,E){if(F=="width"||F=="height"){var L,G={position:"absolute",visibility:"hidden",display:"block"},K=F=="width"?["Left","Right"]:["Top","Bottom"];function I(){L=F=="width"?H.offsetWidth:H.offsetHeight;if(E==="border"){return}o.each(K,function(){if(!E){L-=parseFloat(o.curCSS(H,"padding"+this,true))||0}if(E==="margin"){L+=parseFloat(o.curCSS(H,"margin"+this,true))||0}else{L-=parseFloat(o.curCSS(H,"border"+this+"Width",true))||0}})}if(H.offsetWidth!==0){I()}else{o.swap(H,G,I)}return Math.max(0,Math.round(L))}return o.curCSS(H,F,J)},curCSS:function(I,F,G){var L,E=I.style;if(F=="opacity"&&!o.support.opacity){L=o.attr(E,"opacity");return L==""?"1":L}if(F.match(/float/i)){F=w}if(!G&&E&&E[F]){L=E[F]}else{if(q.getComputedStyle){if(F.match(/float/i)){F="float"}F=F.replace(/([A-Z])/g,"-$1").toLowerCase();var M=q.getComputedStyle(I,null);if(M){L=M.getPropertyValue(F)}if(F=="opacity"&&L==""){L="1"}}else{if(I.currentStyle){var J=F.replace(/\-(\w)/g,function(N,O){return O.toUpperCase()});L=I.currentStyle[F]||I.currentStyle[J];if(!/^\d+(px)?$/i.test(L)&&/^\d/.test(L)){var H=E.left,K=I.runtimeStyle.left;I.runtimeStyle.left=I.currentStyle.left;E.left=L||0;L=E.pixelLeft+"px";E.left=H;I.runtimeStyle.left=K}}}}return L},clean:function(F,K,I){K=K||document;if(typeof K.createElement==="undefined"){K=K.ownerDocument||K[0]&&K[0].ownerDocument||document}if(!I&&F.length===1&&typeof F[0]==="string"){var H=/^<(\w+)\s*\/?>$/.exec(F[0]);if(H){return[K.createElement(H[1])]}}var G=[],E=[],L=K.createElement("div");o.each(F,function(P,S){if(typeof S==="number"){S+=""}if(!S){return}if(typeof S==="string"){S=S.replace(/(<(\w+)[^>]*?)\/>/g,function(U,V,T){return T.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i)?U:V+"></"+T+">"});var O=S.replace(/^\s+/,"").substring(0,10).toLowerCase();var Q=!O.indexOf("<opt")&&[1,"<select multiple='multiple'>","</select>"]||!O.indexOf("<leg")&&[1,"<fieldset>","</fieldset>"]||O.match(/^<(thead|tbody|tfoot|colg|cap)/)&&[1,"<table>","</table>"]||!O.indexOf("<tr")&&[2,"<table><tbody>","</tbody></table>"]||(!O.indexOf("<td")||!O.indexOf("<th"))&&[3,"<table><tbody><tr>","</tr></tbody></table>"]||!O.indexOf("<col")&&[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"]||!o.support.htmlSerialize&&[1,"div<div>","</div>"]||[0,"",""];L.innerHTML=Q[1]+S+Q[2];while(Q[0]--){L=L.lastChild}if(!o.support.tbody){var R=/<tbody/i.test(S),N=!O.indexOf("<table")&&!R?L.firstChild&&L.firstChild.childNodes:Q[1]=="<table>"&&!R?L.childNodes:[];for(var M=N.length-1;M>=0;--M){if(o.nodeName(N[M],"tbody")&&!N[M].childNodes.length){N[M].parentNode.removeChild(N[M])}}}if(!o.support.leadingWhitespace&&/^\s/.test(S)){L.insertBefore(K.createTextNode(S.match(/^\s*/)[0]),L.firstChild)}S=o.makeArray(L.childNodes)}if(S.nodeType){G.push(S)}else{G=o.merge(G,S)}});if(I){for(var J=0;G[J];J++){if(o.nodeName(G[J],"script")&&(!G[J].type||G[J].type.toLowerCase()==="text/javascript")){E.push(G[J].parentNode?G[J].parentNode.removeChild(G[J]):G[J])}else{if(G[J].nodeType===1){G.splice.apply(G,[J+1,0].concat(o.makeArray(G[J].getElementsByTagName("script"))))}I.appendChild(G[J])}}return E}return G},attr:function(J,G,K){if(!J||J.nodeType==3||J.nodeType==8){return g}var H=!o.isXMLDoc(J),L=K!==g;G=H&&o.props[G]||G;if(J.tagName){var F=/href|src|style/.test(G);if(G=="selected"&&J.parentNode){J.parentNode.selectedIndex}if(G in J&&H&&!F){if(L){if(G=="type"&&o.nodeName(J,"input")&&J.parentNode){throw"type property can't be changed"}J[G]=K}if(o.nodeName(J,"form")&&J.getAttributeNode(G)){return J.getAttributeNode(G).nodeValue}if(G=="tabIndex"){var I=J.getAttributeNode("tabIndex");return I&&I.specified?I.value:J.nodeName.match(/(button|input|object|select|textarea)/i)?0:J.nodeName.match(/^(a|area)$/i)&&J.href?0:g}return J[G]}if(!o.support.style&&H&&G=="style"){return o.attr(J.style,"cssText",K)}if(L){J.setAttribute(G,""+K)}var E=!o.support.hrefNormalized&&H&&F?J.getAttribute(G,2):J.getAttribute(G);return E===null?g:E}if(!o.support.opacity&&G=="opacity"){if(L){J.zoom=1;J.filter=(J.filter||"").replace(/alpha\([^)]*\)/,"")+(parseInt(K)+""=="NaN"?"":"alpha(opacity="+K*100+")")}return J.filter&&J.filter.indexOf("opacity=")>=0?(parseFloat(J.filter.match(/opacity=([^)]*)/)[1])/100)+"":""}G=G.replace(/-([a-z])/ig,function(M,N){return N.toUpperCase()});if(L){J[G]=K}return J[G]},trim:function(E){return(E||"").replace(/^\s+|\s+$/g,"")},makeArray:function(G){var E=[];if(G!=null){var F=G.length;if(F==null||typeof G==="string"||o.isFunction(G)||G.setInterval){E[0]=G}else{while(F){E[--F]=G[F]}}}return E},inArray:function(G,H){for(var E=0,F=H.length;E<F;E++){if(H[E]===G){return E}}return -1},merge:function(H,E){var F=0,G,I=H.length;if(!o.support.getAll){while((G=E[F++])!=null){if(G.nodeType!=8){H[I++]=G}}}else{while((G=E[F++])!=null){H[I++]=G}}return H},unique:function(K){var F=[],E={};try{for(var G=0,H=K.length;G<H;G++){var J=o.data(K[G]);if(!E[J]){E[J]=true;F.push(K[G])}}}catch(I){F=K}return F},grep:function(F,J,E){var G=[];for(var H=0,I=F.length;H<I;H++){if(!E!=!J(F[H],H)){G.push(F[H])}}return G},map:function(E,J){var F=[];for(var G=0,H=E.length;G<H;G++){var I=J(E[G],G);if(I!=null){F[F.length]=I}}return F.concat.apply([],F)}});var C=navigator.userAgent.toLowerCase();o.browser={version:(C.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/)||[0,"0"])[1],safari:/webkit/.test(C),opera:/opera/.test(C),msie:/msie/.test(C)&&!/opera/.test(C),mozilla:/mozilla/.test(C)&&!/(compatible|webkit)/.test(C)};o.each({parent:function(E){return E.parentNode},parents:function(E){return o.dir(E,"parentNode")},next:function(E){return o.nth(E,2,"nextSibling")},prev:function(E){return o.nth(E,2,"previousSibling")},nextAll:function(E){return o.dir(E,"nextSibling")},prevAll:function(E){return o.dir(E,"previousSibling")},siblings:function(E){return o.sibling(E.parentNode.firstChild,E)},children:function(E){return o.sibling(E.firstChild)},contents:function(E){return o.nodeName(E,"iframe")?E.contentDocument||E.contentWindow.document:o.makeArray(E.childNodes)}},function(E,F){o.fn[E]=function(G){var H=o.map(this,F);if(G&&typeof G=="string"){H=o.multiFilter(G,H)}return this.pushStack(o.unique(H),E,G)}});o.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(E,F){o.fn[E]=function(G){var J=[],L=o(G);for(var K=0,H=L.length;K<H;K++){var I=(K>0?this.clone(true):this).get();o.fn[F].apply(o(L[K]),I);J=J.concat(I)}return this.pushStack(J,E,G)}});o.each({removeAttr:function(E){o.attr(this,E,"");if(this.nodeType==1){this.removeAttribute(E)}},addClass:function(E){o.className.add(this,E)},removeClass:function(E){o.className.remove(this,E)},toggleClass:function(F,E){if(typeof E!=="boolean"){E=!o.className.has(this,F)}o.className[E?"add":"remove"](this,F)},remove:function(E){if(!E||o.filter(E,[this]).length){o("*",this).add([this]).each(function(){o.event.remove(this);o.removeData(this)});if(this.parentNode){this.parentNode.removeChild(this)}}},empty:function(){o(this).children().remove();while(this.firstChild){this.removeChild(this.firstChild)}}},function(E,F){o.fn[E]=function(){return this.each(F,arguments)}});function j(E,F){return E[0]&&parseInt(o.curCSS(E[0],F,true),10)||0}var h="jQuery"+e(),v=0,A={};o.extend({cache:{},data:function(F,E,G){F=F==l?A:F;var H=F[h];if(!H){H=F[h]=++v}if(E&&!o.cache[H]){o.cache[H]={}}if(G!==g){o.cache[H][E]=G}return E?o.cache[H][E]:H},removeData:function(F,E){F=F==l?A:F;var H=F[h];if(E){if(o.cache[H]){delete o.cache[H][E];E="";for(E in o.cache[H]){break}if(!E){o.removeData(F)}}}else{try{delete F[h]}catch(G){if(F.removeAttribute){F.removeAttribute(h)}}delete o.cache[H]}},queue:function(F,E,H){if(F){E=(E||"fx")+"queue";var G=o.data(F,E);if(!G||o.isArray(H)){G=o.data(F,E,o.makeArray(H))}else{if(H){G.push(H)}}}return G},dequeue:function(H,G){var E=o.queue(H,G),F=E.shift();if(!G||G==="fx"){F=E[0]}if(F!==g){F.call(H)}}});o.fn.extend({data:function(E,G){var H=E.split(".");H[1]=H[1]?"."+H[1]:"";if(G===g){var F=this.triggerHandler("getData"+H[1]+"!",[H[0]]);if(F===g&&this.length){F=o.data(this[0],E)}return F===g&&H[1]?this.data(H[0]):F}else{return this.trigger("setData"+H[1]+"!",[H[0],G]).each(function(){o.data(this,E,G)})}},removeData:function(E){return this.each(function(){o.removeData(this,E)})},queue:function(E,F){if(typeof E!=="string"){F=E;E="fx"}if(F===g){return o.queue(this[0],E)}return this.each(function(){var G=o.queue(this,E,F);if(E=="fx"&&G.length==1){G[0].call(this)}})},dequeue:function(E){return this.each(function(){o.dequeue(this,E)})}});
/*
 * Sizzle CSS Selector Engine - v0.9.3
 *  Copyright 2009, The Dojo Foundation
 *  Released under the MIT, BSD, and GPL Licenses.
 *  More information: http://sizzlejs.com/
 */
(function(){var R=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?/g,L=0,H=Object.prototype.toString;var F=function(Y,U,ab,ac){ab=ab||[];U=U||document;if(U.nodeType!==1&&U.nodeType!==9){return[]}if(!Y||typeof Y!=="string"){return ab}var Z=[],W,af,ai,T,ad,V,X=true;R.lastIndex=0;while((W=R.exec(Y))!==null){Z.push(W[1]);if(W[2]){V=RegExp.rightContext;break}}if(Z.length>1&&M.exec(Y)){if(Z.length===2&&I.relative[Z[0]]){af=J(Z[0]+Z[1],U)}else{af=I.relative[Z[0]]?[U]:F(Z.shift(),U);while(Z.length){Y=Z.shift();if(I.relative[Y]){Y+=Z.shift()}af=J(Y,af)}}}else{var ae=ac?{expr:Z.pop(),set:E(ac)}:F.find(Z.pop(),Z.length===1&&U.parentNode?U.parentNode:U,Q(U));af=F.filter(ae.expr,ae.set);if(Z.length>0){ai=E(af)}else{X=false}while(Z.length){var ah=Z.pop(),ag=ah;if(!I.relative[ah]){ah=""}else{ag=Z.pop()}if(ag==null){ag=U}I.relative[ah](ai,ag,Q(U))}}if(!ai){ai=af}if(!ai){throw"Syntax error, unrecognized expression: "+(ah||Y)}if(H.call(ai)==="[object Array]"){if(!X){ab.push.apply(ab,ai)}else{if(U.nodeType===1){for(var aa=0;ai[aa]!=null;aa++){if(ai[aa]&&(ai[aa]===true||ai[aa].nodeType===1&&K(U,ai[aa]))){ab.push(af[aa])}}}else{for(var aa=0;ai[aa]!=null;aa++){if(ai[aa]&&ai[aa].nodeType===1){ab.push(af[aa])}}}}}else{E(ai,ab)}if(V){F(V,U,ab,ac);if(G){hasDuplicate=false;ab.sort(G);if(hasDuplicate){for(var aa=1;aa<ab.length;aa++){if(ab[aa]===ab[aa-1]){ab.splice(aa--,1)}}}}}return ab};F.matches=function(T,U){return F(T,null,null,U)};F.find=function(aa,T,ab){var Z,X;if(!aa){return[]}for(var W=0,V=I.order.length;W<V;W++){var Y=I.order[W],X;if((X=I.match[Y].exec(aa))){var U=RegExp.leftContext;if(U.substr(U.length-1)!=="\\"){X[1]=(X[1]||"").replace(/\\/g,"");Z=I.find[Y](X,T,ab);if(Z!=null){aa=aa.replace(I.match[Y],"");break}}}}if(!Z){Z=T.getElementsByTagName("*")}return{set:Z,expr:aa}};F.filter=function(ad,ac,ag,W){var V=ad,ai=[],aa=ac,Y,T,Z=ac&&ac[0]&&Q(ac[0]);while(ad&&ac.length){for(var ab in I.filter){if((Y=I.match[ab].exec(ad))!=null){var U=I.filter[ab],ah,af;T=false;if(aa==ai){ai=[]}if(I.preFilter[ab]){Y=I.preFilter[ab](Y,aa,ag,ai,W,Z);if(!Y){T=ah=true}else{if(Y===true){continue}}}if(Y){for(var X=0;(af=aa[X])!=null;X++){if(af){ah=U(af,Y,X,aa);var ae=W^!!ah;if(ag&&ah!=null){if(ae){T=true}else{aa[X]=false}}else{if(ae){ai.push(af);T=true}}}}}if(ah!==g){if(!ag){aa=ai}ad=ad.replace(I.match[ab],"");if(!T){return[]}break}}}if(ad==V){if(T==null){throw"Syntax error, unrecognized expression: "+ad}else{break}}V=ad}return aa};var I=F.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF_-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF_-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF_-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF_-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*_-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF_-]|\\.)+)(?:\((['"]*)((?:\([^\)]+\)|[^\2\(\)]*)+)\2\))?/},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(T){return T.getAttribute("href")}},relative:{"+":function(aa,T,Z){var X=typeof T==="string",ab=X&&!/\W/.test(T),Y=X&&!ab;if(ab&&!Z){T=T.toUpperCase()}for(var W=0,V=aa.length,U;W<V;W++){if((U=aa[W])){while((U=U.previousSibling)&&U.nodeType!==1){}aa[W]=Y||U&&U.nodeName===T?U||false:U===T}}if(Y){F.filter(T,aa,true)}},">":function(Z,U,aa){var X=typeof U==="string";if(X&&!/\W/.test(U)){U=aa?U:U.toUpperCase();for(var V=0,T=Z.length;V<T;V++){var Y=Z[V];if(Y){var W=Y.parentNode;Z[V]=W.nodeName===U?W:false}}}else{for(var V=0,T=Z.length;V<T;V++){var Y=Z[V];if(Y){Z[V]=X?Y.parentNode:Y.parentNode===U}}if(X){F.filter(U,Z,true)}}},"":function(W,U,Y){var V=L++,T=S;if(!U.match(/\W/)){var X=U=Y?U:U.toUpperCase();T=P}T("parentNode",U,V,W,X,Y)},"~":function(W,U,Y){var V=L++,T=S;if(typeof U==="string"&&!U.match(/\W/)){var X=U=Y?U:U.toUpperCase();T=P}T("previousSibling",U,V,W,X,Y)}},find:{ID:function(U,V,W){if(typeof V.getElementById!=="undefined"&&!W){var T=V.getElementById(U[1]);return T?[T]:[]}},NAME:function(V,Y,Z){if(typeof Y.getElementsByName!=="undefined"){var U=[],X=Y.getElementsByName(V[1]);for(var W=0,T=X.length;W<T;W++){if(X[W].getAttribute("name")===V[1]){U.push(X[W])}}return U.length===0?null:U}},TAG:function(T,U){return U.getElementsByTagName(T[1])}},preFilter:{CLASS:function(W,U,V,T,Z,aa){W=" "+W[1].replace(/\\/g,"")+" ";if(aa){return W}for(var X=0,Y;(Y=U[X])!=null;X++){if(Y){if(Z^(Y.className&&(" "+Y.className+" ").indexOf(W)>=0)){if(!V){T.push(Y)}}else{if(V){U[X]=false}}}}return false},ID:function(T){return T[1].replace(/\\/g,"")},TAG:function(U,T){for(var V=0;T[V]===false;V++){}return T[V]&&Q(T[V])?U[1]:U[1].toUpperCase()},CHILD:function(T){if(T[1]=="nth"){var U=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(T[2]=="even"&&"2n"||T[2]=="odd"&&"2n+1"||!/\D/.test(T[2])&&"0n+"+T[2]||T[2]);T[2]=(U[1]+(U[2]||1))-0;T[3]=U[3]-0}T[0]=L++;return T},ATTR:function(X,U,V,T,Y,Z){var W=X[1].replace(/\\/g,"");if(!Z&&I.attrMap[W]){X[1]=I.attrMap[W]}if(X[2]==="~="){X[4]=" "+X[4]+" "}return X},PSEUDO:function(X,U,V,T,Y){if(X[1]==="not"){if(X[3].match(R).length>1||/^\w/.test(X[3])){X[3]=F(X[3],null,null,U)}else{var W=F.filter(X[3],U,V,true^Y);if(!V){T.push.apply(T,W)}return false}}else{if(I.match.POS.test(X[0])||I.match.CHILD.test(X[0])){return true}}return X},POS:function(T){T.unshift(true);return T}},filters:{enabled:function(T){return T.disabled===false&&T.type!=="hidden"},disabled:function(T){return T.disabled===true},checked:function(T){return T.checked===true},selected:function(T){T.parentNode.selectedIndex;return T.selected===true},parent:function(T){return !!T.firstChild},empty:function(T){return !T.firstChild},has:function(V,U,T){return !!F(T[3],V).length},header:function(T){return/h\d/i.test(T.nodeName)},text:function(T){return"text"===T.type},radio:function(T){return"radio"===T.type},checkbox:function(T){return"checkbox"===T.type},file:function(T){return"file"===T.type},password:function(T){return"password"===T.type},submit:function(T){return"submit"===T.type},image:function(T){return"image"===T.type},reset:function(T){return"reset"===T.type},button:function(T){return"button"===T.type||T.nodeName.toUpperCase()==="BUTTON"},input:function(T){return/input|select|textarea|button/i.test(T.nodeName)}},setFilters:{first:function(U,T){return T===0},last:function(V,U,T,W){return U===W.length-1},even:function(U,T){return T%2===0},odd:function(U,T){return T%2===1},lt:function(V,U,T){return U<T[3]-0},gt:function(V,U,T){return U>T[3]-0},nth:function(V,U,T){return T[3]-0==U},eq:function(V,U,T){return T[3]-0==U}},filter:{PSEUDO:function(Z,V,W,aa){var U=V[1],X=I.filters[U];if(X){return X(Z,W,V,aa)}else{if(U==="contains"){return(Z.textContent||Z.innerText||"").indexOf(V[3])>=0}else{if(U==="not"){var Y=V[3];for(var W=0,T=Y.length;W<T;W++){if(Y[W]===Z){return false}}return true}}}},CHILD:function(T,W){var Z=W[1],U=T;switch(Z){case"only":case"first":while(U=U.previousSibling){if(U.nodeType===1){return false}}if(Z=="first"){return true}U=T;case"last":while(U=U.nextSibling){if(U.nodeType===1){return false}}return true;case"nth":var V=W[2],ac=W[3];if(V==1&&ac==0){return true}var Y=W[0],ab=T.parentNode;if(ab&&(ab.sizcache!==Y||!T.nodeIndex)){var X=0;for(U=ab.firstChild;U;U=U.nextSibling){if(U.nodeType===1){U.nodeIndex=++X}}ab.sizcache=Y}var aa=T.nodeIndex-ac;if(V==0){return aa==0}else{return(aa%V==0&&aa/V>=0)}}},ID:function(U,T){return U.nodeType===1&&U.getAttribute("id")===T},TAG:function(U,T){return(T==="*"&&U.nodeType===1)||U.nodeName===T},CLASS:function(U,T){return(" "+(U.className||U.getAttribute("class"))+" ").indexOf(T)>-1},ATTR:function(Y,W){var V=W[1],T=I.attrHandle[V]?I.attrHandle[V](Y):Y[V]!=null?Y[V]:Y.getAttribute(V),Z=T+"",X=W[2],U=W[4];return T==null?X==="!=":X==="="?Z===U:X==="*="?Z.indexOf(U)>=0:X==="~="?(" "+Z+" ").indexOf(U)>=0:!U?Z&&T!==false:X==="!="?Z!=U:X==="^="?Z.indexOf(U)===0:X==="$="?Z.substr(Z.length-U.length)===U:X==="|="?Z===U||Z.substr(0,U.length+1)===U+"-":false},POS:function(X,U,V,Y){var T=U[2],W=I.setFilters[T];if(W){return W(X,V,U,Y)}}}};var M=I.match.POS;for(var O in I.match){I.match[O]=RegExp(I.match[O].source+/(?![^\[]*\])(?![^\(]*\))/.source)}var E=function(U,T){U=Array.prototype.slice.call(U);if(T){T.push.apply(T,U);return T}return U};try{Array.prototype.slice.call(document.documentElement.childNodes)}catch(N){E=function(X,W){var U=W||[];if(H.call(X)==="[object Array]"){Array.prototype.push.apply(U,X)}else{if(typeof X.length==="number"){for(var V=0,T=X.length;V<T;V++){U.push(X[V])}}else{for(var V=0;X[V];V++){U.push(X[V])}}}return U}}var G;if(document.documentElement.compareDocumentPosition){G=function(U,T){var V=U.compareDocumentPosition(T)&4?-1:U===T?0:1;if(V===0){hasDuplicate=true}return V}}else{if("sourceIndex" in document.documentElement){G=function(U,T){var V=U.sourceIndex-T.sourceIndex;if(V===0){hasDuplicate=true}return V}}else{if(document.createRange){G=function(W,U){var V=W.ownerDocument.createRange(),T=U.ownerDocument.createRange();V.selectNode(W);V.collapse(true);T.selectNode(U);T.collapse(true);var X=V.compareBoundaryPoints(Range.START_TO_END,T);if(X===0){hasDuplicate=true}return X}}}}(function(){var U=document.createElement("form"),V="script"+(new Date).getTime();U.innerHTML="<input name='"+V+"'/>";var T=document.documentElement;T.insertBefore(U,T.firstChild);if(!!document.getElementById(V)){I.find.ID=function(X,Y,Z){if(typeof Y.getElementById!=="undefined"&&!Z){var W=Y.getElementById(X[1]);return W?W.id===X[1]||typeof W.getAttributeNode!=="undefined"&&W.getAttributeNode("id").nodeValue===X[1]?[W]:g:[]}};I.filter.ID=function(Y,W){var X=typeof Y.getAttributeNode!=="undefined"&&Y.getAttributeNode("id");return Y.nodeType===1&&X&&X.nodeValue===W}}T.removeChild(U)})();(function(){var T=document.createElement("div");T.appendChild(document.createComment(""));if(T.getElementsByTagName("*").length>0){I.find.TAG=function(U,Y){var X=Y.getElementsByTagName(U[1]);if(U[1]==="*"){var W=[];for(var V=0;X[V];V++){if(X[V].nodeType===1){W.push(X[V])}}X=W}return X}}T.innerHTML="<a href='#'></a>";if(T.firstChild&&typeof T.firstChild.getAttribute!=="undefined"&&T.firstChild.getAttribute("href")!=="#"){I.attrHandle.href=function(U){return U.getAttribute("href",2)}}})();if(document.querySelectorAll){(function(){var T=F,U=document.createElement("div");U.innerHTML="<p class='TEST'></p>";if(U.querySelectorAll&&U.querySelectorAll(".TEST").length===0){return}F=function(Y,X,V,W){X=X||document;if(!W&&X.nodeType===9&&!Q(X)){try{return E(X.querySelectorAll(Y),V)}catch(Z){}}return T(Y,X,V,W)};F.find=T.find;F.filter=T.filter;F.selectors=T.selectors;F.matches=T.matches})()}if(document.getElementsByClassName&&document.documentElement.getElementsByClassName){(function(){var T=document.createElement("div");T.innerHTML="<div class='test e'></div><div class='test'></div>";if(T.getElementsByClassName("e").length===0){return}T.lastChild.className="e";if(T.getElementsByClassName("e").length===1){return}I.order.splice(1,0,"CLASS");I.find.CLASS=function(U,V,W){if(typeof V.getElementsByClassName!=="undefined"&&!W){return V.getElementsByClassName(U[1])}}})()}function P(U,Z,Y,ad,aa,ac){var ab=U=="previousSibling"&&!ac;for(var W=0,V=ad.length;W<V;W++){var T=ad[W];if(T){if(ab&&T.nodeType===1){T.sizcache=Y;T.sizset=W}T=T[U];var X=false;while(T){if(T.sizcache===Y){X=ad[T.sizset];break}if(T.nodeType===1&&!ac){T.sizcache=Y;T.sizset=W}if(T.nodeName===Z){X=T;break}T=T[U]}ad[W]=X}}}function S(U,Z,Y,ad,aa,ac){var ab=U=="previousSibling"&&!ac;for(var W=0,V=ad.length;W<V;W++){var T=ad[W];if(T){if(ab&&T.nodeType===1){T.sizcache=Y;T.sizset=W}T=T[U];var X=false;while(T){if(T.sizcache===Y){X=ad[T.sizset];break}if(T.nodeType===1){if(!ac){T.sizcache=Y;T.sizset=W}if(typeof Z!=="string"){if(T===Z){X=true;break}}else{if(F.filter(Z,[T]).length>0){X=T;break}}}T=T[U]}ad[W]=X}}}var K=document.compareDocumentPosition?function(U,T){return U.compareDocumentPosition(T)&16}:function(U,T){return U!==T&&(U.contains?U.contains(T):true)};var Q=function(T){return T.nodeType===9&&T.documentElement.nodeName!=="HTML"||!!T.ownerDocument&&Q(T.ownerDocument)};var J=function(T,aa){var W=[],X="",Y,V=aa.nodeType?[aa]:aa;while((Y=I.match.PSEUDO.exec(T))){X+=Y[0];T=T.replace(I.match.PSEUDO,"")}T=I.relative[T]?T+"*":T;for(var Z=0,U=V.length;Z<U;Z++){F(T,V[Z],W)}return F.filter(X,W)};o.find=F;o.filter=F.filter;o.expr=F.selectors;o.expr[":"]=o.expr.filters;F.selectors.filters.hidden=function(T){return T.offsetWidth===0||T.offsetHeight===0};F.selectors.filters.visible=function(T){return T.offsetWidth>0||T.offsetHeight>0};F.selectors.filters.animated=function(T){return o.grep(o.timers,function(U){return T===U.elem}).length};o.multiFilter=function(V,T,U){if(U){V=":not("+V+")"}return F.matches(V,T)};o.dir=function(V,U){var T=[],W=V[U];while(W&&W!=document){if(W.nodeType==1){T.push(W)}W=W[U]}return T};o.nth=function(X,T,V,W){T=T||1;var U=0;for(;X;X=X[V]){if(X.nodeType==1&&++U==T){break}}return X};o.sibling=function(V,U){var T=[];for(;V;V=V.nextSibling){if(V.nodeType==1&&V!=U){T.push(V)}}return T};return;l.Sizzle=F})();o.event={add:function(I,F,H,K){if(I.nodeType==3||I.nodeType==8){return}if(I.setInterval&&I!=l){I=l}if(!H.guid){H.guid=this.guid++}if(K!==g){var G=H;H=this.proxy(G);H.data=K}var E=o.data(I,"events")||o.data(I,"events",{}),J=o.data(I,"handle")||o.data(I,"handle",function(){return typeof o!=="undefined"&&!o.event.triggered?o.event.handle.apply(arguments.callee.elem,arguments):g});J.elem=I;o.each(F.split(/\s+/),function(M,N){var O=N.split(".");N=O.shift();H.type=O.slice().sort().join(".");var L=E[N];if(o.event.specialAll[N]){o.event.specialAll[N].setup.call(I,K,O)}if(!L){L=E[N]={};if(!o.event.special[N]||o.event.special[N].setup.call(I,K,O)===false){if(I.addEventListener){I.addEventListener(N,J,false)}else{if(I.attachEvent){I.attachEvent("on"+N,J)}}}}L[H.guid]=H;o.event.global[N]=true});I=null},guid:1,global:{},remove:function(K,H,J){if(K.nodeType==3||K.nodeType==8){return}var G=o.data(K,"events"),F,E;if(G){if(H===g||(typeof H==="string"&&H.charAt(0)==".")){for(var I in G){this.remove(K,I+(H||""))}}else{if(H.type){J=H.handler;H=H.type}o.each(H.split(/\s+/),function(M,O){var Q=O.split(".");O=Q.shift();var N=RegExp("(^|\\.)"+Q.slice().sort().join(".*\\.")+"(\\.|$)");if(G[O]){if(J){delete G[O][J.guid]}else{for(var P in G[O]){if(N.test(G[O][P].type)){delete G[O][P]}}}if(o.event.specialAll[O]){o.event.specialAll[O].teardown.call(K,Q)}for(F in G[O]){break}if(!F){if(!o.event.special[O]||o.event.special[O].teardown.call(K,Q)===false){if(K.removeEventListener){K.removeEventListener(O,o.data(K,"handle"),false)}else{if(K.detachEvent){K.detachEvent("on"+O,o.data(K,"handle"))}}}F=null;delete G[O]}}})}for(F in G){break}if(!F){var L=o.data(K,"handle");if(L){L.elem=null}o.removeData(K,"events");o.removeData(K,"handle")}}},trigger:function(I,K,H,E){var G=I.type||I;if(!E){I=typeof I==="object"?I[h]?I:o.extend(o.Event(G),I):o.Event(G);if(G.indexOf("!")>=0){I.type=G=G.slice(0,-1);I.exclusive=true}if(!H){I.stopPropagation();if(this.global[G]){o.each(o.cache,function(){if(this.events&&this.events[G]){o.event.trigger(I,K,this.handle.elem)}})}}if(!H||H.nodeType==3||H.nodeType==8){return g}I.result=g;I.target=H;K=o.makeArray(K);K.unshift(I)}I.currentTarget=H;var J=o.data(H,"handle");if(J){J.apply(H,K)}if((!H[G]||(o.nodeName(H,"a")&&G=="click"))&&H["on"+G]&&H["on"+G].apply(H,K)===false){I.result=false}if(!E&&H[G]&&!I.isDefaultPrevented()&&!(o.nodeName(H,"a")&&G=="click")){this.triggered=true;try{H[G]()}catch(L){}}this.triggered=false;if(!I.isPropagationStopped()){var F=H.parentNode||H.ownerDocument;if(F){o.event.trigger(I,K,F,true)}}},handle:function(K){var J,E;K=arguments[0]=o.event.fix(K||l.event);K.currentTarget=this;var L=K.type.split(".");K.type=L.shift();J=!L.length&&!K.exclusive;var I=RegExp("(^|\\.)"+L.slice().sort().join(".*\\.")+"(\\.|$)");E=(o.data(this,"events")||{})[K.type];for(var G in E){var H=E[G];if(J||I.test(H.type)){K.handler=H;K.data=H.data;var F=H.apply(this,arguments);if(F!==g){K.result=F;if(F===false){K.preventDefault();K.stopPropagation()}}if(K.isImmediatePropagationStopped()){break}}}},props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode metaKey newValue originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),fix:function(H){if(H[h]){return H}var F=H;H=o.Event(F);for(var G=this.props.length,J;G;){J=this.props[--G];H[J]=F[J]}if(!H.target){H.target=H.srcElement||document}if(H.target.nodeType==3){H.target=H.target.parentNode}if(!H.relatedTarget&&H.fromElement){H.relatedTarget=H.fromElement==H.target?H.toElement:H.fromElement}if(H.pageX==null&&H.clientX!=null){var I=document.documentElement,E=document.body;H.pageX=H.clientX+(I&&I.scrollLeft||E&&E.scrollLeft||0)-(I.clientLeft||0);H.pageY=H.clientY+(I&&I.scrollTop||E&&E.scrollTop||0)-(I.clientTop||0)}if(!H.which&&((H.charCode||H.charCode===0)?H.charCode:H.keyCode)){H.which=H.charCode||H.keyCode}if(!H.metaKey&&H.ctrlKey){H.metaKey=H.ctrlKey}if(!H.which&&H.button){H.which=(H.button&1?1:(H.button&2?3:(H.button&4?2:0)))}return H},proxy:function(F,E){E=E||function(){return F.apply(this,arguments)};E.guid=F.guid=F.guid||E.guid||this.guid++;return E},special:{ready:{setup:B,teardown:function(){}}},specialAll:{live:{setup:function(E,F){o.event.add(this,F[0],c)},teardown:function(G){if(G.length){var E=0,F=RegExp("(^|\\.)"+G[0]+"(\\.|$)");o.each((o.data(this,"events").live||{}),function(){if(F.test(this.type)){E++}});if(E<1){o.event.remove(this,G[0],c)}}}}}};o.Event=function(E){if(!this.preventDefault){return new o.Event(E)}if(E&&E.type){this.originalEvent=E;this.type=E.type}else{this.type=E}this.timeStamp=e();this[h]=true};function k(){return false}function u(){return true}o.Event.prototype={preventDefault:function(){this.isDefaultPrevented=u;var E=this.originalEvent;if(!E){return}if(E.preventDefault){E.preventDefault()}E.returnValue=false},stopPropagation:function(){this.isPropagationStopped=u;var E=this.originalEvent;if(!E){return}if(E.stopPropagation){E.stopPropagation()}E.cancelBubble=true},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=u;this.stopPropagation()},isDefaultPrevented:k,isPropagationStopped:k,isImmediatePropagationStopped:k};var a=function(F){var E=F.relatedTarget;while(E&&E!=this){try{E=E.parentNode}catch(G){E=this}}if(E!=this){F.type=F.data;o.event.handle.apply(this,arguments)}};o.each({mouseover:"mouseenter",mouseout:"mouseleave"},function(F,E){o.event.special[E]={setup:function(){o.event.add(this,F,a,E)},teardown:function(){o.event.remove(this,F,a)}}});o.fn.extend({bind:function(F,G,E){return F=="unload"?this.one(F,G,E):this.each(function(){o.event.add(this,F,E||G,E&&G)})},one:function(G,H,F){var E=o.event.proxy(F||H,function(I){o(this).unbind(I,E);return(F||H).apply(this,arguments)});return this.each(function(){o.event.add(this,G,E,F&&H)})},unbind:function(F,E){return this.each(function(){o.event.remove(this,F,E)})},trigger:function(E,F){return this.each(function(){o.event.trigger(E,F,this)})},triggerHandler:function(E,G){if(this[0]){var F=o.Event(E);F.preventDefault();F.stopPropagation();o.event.trigger(F,G,this[0]);return F.result}},toggle:function(G){var E=arguments,F=1;while(F<E.length){o.event.proxy(G,E[F++])}return this.click(o.event.proxy(G,function(H){this.lastToggle=(this.lastToggle||0)%F;H.preventDefault();return E[this.lastToggle++].apply(this,arguments)||false}))},hover:function(E,F){return this.mouseenter(E).mouseleave(F)},ready:function(E){B();if(o.isReady){E.call(document,o)}else{o.readyList.push(E)}return this},live:function(G,F){var E=o.event.proxy(F);E.guid+=this.selector+G;o(document).bind(i(G,this.selector),this.selector,E);return this},die:function(F,E){o(document).unbind(i(F,this.selector),E?{guid:E.guid+this.selector+F}:null);return this}});function c(H){var E=RegExp("(^|\\.)"+H.type+"(\\.|$)"),G=true,F=[];o.each(o.data(this,"events").live||[],function(I,J){if(E.test(J.type)){var K=o(H.target).closest(J.data)[0];if(K){F.push({elem:K,fn:J})}}});F.sort(function(J,I){return o.data(J.elem,"closest")-o.data(I.elem,"closest")});o.each(F,function(){if(this.fn.call(this.elem,H,this.fn.data)===false){return(G=false)}});return G}function i(F,E){return["live",F,E.replace(/\./g,"`").replace(/ /g,"|")].join(".")}o.extend({isReady:false,readyList:[],ready:function(){if(!o.isReady){o.isReady=true;if(o.readyList){o.each(o.readyList,function(){this.call(document,o)});o.readyList=null}o(document).triggerHandler("ready")}}});var x=false;function B(){if(x){return}x=true;if(document.addEventListener){document.addEventListener("DOMContentLoaded",function(){document.removeEventListener("DOMContentLoaded",arguments.callee,false);o.ready()},false)}else{if(document.attachEvent){document.attachEvent("onreadystatechange",function(){if(document.readyState==="complete"){document.detachEvent("onreadystatechange",arguments.callee);o.ready()}});if(document.documentElement.doScroll&&l==l.top){(function(){if(o.isReady){return}try{document.documentElement.doScroll("left")}catch(E){setTimeout(arguments.callee,0);return}o.ready()})()}}}o.event.add(l,"load",o.ready)}o.each(("blur,focus,load,resize,scroll,unload,click,dblclick,mousedown,mouseup,mousemove,mouseover,mouseout,mouseenter,mouseleave,change,select,submit,keydown,keypress,keyup,error").split(","),function(F,E){o.fn[E]=function(G){return G?this.bind(E,G):this.trigger(E)}});o(l).bind("unload",function(){for(var E in o.cache){if(E!=1&&o.cache[E].handle){o.event.remove(o.cache[E].handle.elem)}}});(function(){o.support={};var F=document.documentElement,G=document.createElement("script"),K=document.createElement("div"),J="script"+(new Date).getTime();K.style.display="none";K.innerHTML='   <link/><table></table><a href="/a" style="color:red;float:left;opacity:.5;">a</a><select><option>text</option></select><object><param/></object>';var H=K.getElementsByTagName("*"),E=K.getElementsByTagName("a")[0];if(!H||!H.length||!E){return}o.support={leadingWhitespace:K.firstChild.nodeType==3,tbody:!K.getElementsByTagName("tbody").length,objectAll:!!K.getElementsByTagName("object")[0].getElementsByTagName("*").length,htmlSerialize:!!K.getElementsByTagName("link").length,style:/red/.test(E.getAttribute("style")),hrefNormalized:E.getAttribute("href")==="/a",opacity:E.style.opacity==="0.5",cssFloat:!!E.style.cssFloat,scriptEval:false,noCloneEvent:true,boxModel:null};G.type="text/javascript";try{G.appendChild(document.createTextNode("window."+J+"=1;"))}catch(I){}F.insertBefore(G,F.firstChild);if(l[J]){o.support.scriptEval=true;delete l[J]}F.removeChild(G);if(K.attachEvent&&K.fireEvent){K.attachEvent("onclick",function(){o.support.noCloneEvent=false;K.detachEvent("onclick",arguments.callee)});K.cloneNode(true).fireEvent("onclick")}o(function(){var L=document.createElement("div");L.style.width=L.style.paddingLeft="1px";document.body.appendChild(L);o.boxModel=o.support.boxModel=L.offsetWidth===2;document.body.removeChild(L).style.display="none"})})();var w=o.support.cssFloat?"cssFloat":"styleFloat";o.props={"for":"htmlFor","class":"className","float":w,cssFloat:w,styleFloat:w,readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan",tabindex:"tabIndex"};o.fn.extend({_load:o.fn.load,load:function(G,J,K){if(typeof G!=="string"){return this._load(G)}var I=G.indexOf(" ");if(I>=0){var E=G.slice(I,G.length);G=G.slice(0,I)}var H="GET";if(J){if(o.isFunction(J)){K=J;J=null}else{if(typeof J==="object"){J=o.param(J);H="POST"}}}var F=this;o.ajax({url:G,type:H,dataType:"html",data:J,complete:function(M,L){if(L=="success"||L=="notmodified"){F.html(E?o("<div/>").append(M.responseText.replace(/<script(.|\s)*?\/script>/g,"")).find(E):M.responseText)}if(K){F.each(K,[M.responseText,L,M])}}});return this},serialize:function(){return o.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?o.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||/select|textarea/i.test(this.nodeName)||/text|hidden|password|search/i.test(this.type))}).map(function(E,F){var G=o(this).val();return G==null?null:o.isArray(G)?o.map(G,function(I,H){return{name:F.name,value:I}}):{name:F.name,value:G}}).get()}});o.each("ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","),function(E,F){o.fn[F]=function(G){return this.bind(F,G)}});var r=e();o.extend({get:function(E,G,H,F){if(o.isFunction(G)){H=G;G=null}return o.ajax({type:"GET",url:E,data:G,success:H,dataType:F})},getScript:function(E,F){return o.get(E,null,F,"script")},getJSON:function(E,F,G){return o.get(E,F,G,"json")},post:function(E,G,H,F){if(o.isFunction(G)){H=G;G={}}return o.ajax({type:"POST",url:E,data:G,success:H,dataType:F})},ajaxSetup:function(E){o.extend(o.ajaxSettings,E)},ajaxSettings:{url:location.href,global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,xhr:function(){return l.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest()},accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},ajax:function(M){M=o.extend(true,M,o.extend(true,{},o.ajaxSettings,M));var W,F=/=\?(&|$)/g,R,V,G=M.type.toUpperCase();if(M.data&&M.processData&&typeof M.data!=="string"){M.data=o.param(M.data)}if(M.dataType=="jsonp"){if(G=="GET"){if(!M.url.match(F)){M.url+=(M.url.match(/\?/)?"&":"?")+(M.jsonp||"callback")+"=?"}}else{if(!M.data||!M.data.match(F)){M.data=(M.data?M.data+"&":"")+(M.jsonp||"callback")+"=?"}}M.dataType="json"}if(M.dataType=="json"&&(M.data&&M.data.match(F)||M.url.match(F))){W="jsonp"+r++;if(M.data){M.data=(M.data+"").replace(F,"="+W+"$1")}M.url=M.url.replace(F,"="+W+"$1");M.dataType="script";l[W]=function(X){V=X;I();L();l[W]=g;try{delete l[W]}catch(Y){}if(H){H.removeChild(T)}}}if(M.dataType=="script"&&M.cache==null){M.cache=false}if(M.cache===false&&G=="GET"){var E=e();var U=M.url.replace(/(\?|&)_=.*?(&|$)/,"$1_="+E+"$2");M.url=U+((U==M.url)?(M.url.match(/\?/)?"&":"?")+"_="+E:"")}if(M.data&&G=="GET"){M.url+=(M.url.match(/\?/)?"&":"?")+M.data;M.data=null}if(M.global&&!o.active++){o.event.trigger("ajaxStart")}var Q=/^(\w+:)?\/\/([^\/?#]+)/.exec(M.url);if(M.dataType=="script"&&G=="GET"&&Q&&(Q[1]&&Q[1]!=location.protocol||Q[2]!=location.host)){var H=document.getElementsByTagName("head")[0];var T=document.createElement("script");T.src=M.url;if(M.scriptCharset){T.charset=M.scriptCharset}if(!W){var O=false;T.onload=T.onreadystatechange=function(){if(!O&&(!this.readyState||this.readyState=="loaded"||this.readyState=="complete")){O=true;I();L();T.onload=T.onreadystatechange=null;H.removeChild(T)}}}H.appendChild(T);return g}var K=false;var J=M.xhr();if(M.username){J.open(G,M.url,M.async,M.username,M.password)}else{J.open(G,M.url,M.async)}try{if(M.data){J.setRequestHeader("Content-Type",M.contentType)}if(M.ifModified){J.setRequestHeader("If-Modified-Since",o.lastModified[M.url]||"Thu, 01 Jan 1970 00:00:00 GMT")}J.setRequestHeader("X-Requested-With","XMLHttpRequest");J.setRequestHeader("Accept",M.dataType&&M.accepts[M.dataType]?M.accepts[M.dataType]+", */*":M.accepts._default)}catch(S){}if(M.beforeSend&&M.beforeSend(J,M)===false){if(M.global&&!--o.active){o.event.trigger("ajaxStop")}J.abort();return false}if(M.global){o.event.trigger("ajaxSend",[J,M])}var N=function(X){if(J.readyState==0){if(P){clearInterval(P);P=null;if(M.global&&!--o.active){o.event.trigger("ajaxStop")}}}else{if(!K&&J&&(J.readyState==4||X=="timeout")){K=true;if(P){clearInterval(P);P=null}R=X=="timeout"?"timeout":!o.httpSuccess(J)?"error":M.ifModified&&o.httpNotModified(J,M.url)?"notmodified":"success";if(R=="success"){try{V=o.httpData(J,M.dataType,M)}catch(Z){R="parsererror"}}if(R=="success"){var Y;try{Y=J.getResponseHeader("Last-Modified")}catch(Z){}if(M.ifModified&&Y){o.lastModified[M.url]=Y}if(!W){I()}}else{o.handleError(M,J,R)}L();if(X){J.abort()}if(M.async){J=null}}}};if(M.async){var P=setInterval(N,13);if(M.timeout>0){setTimeout(function(){if(J&&!K){N("timeout")}},M.timeout)}}try{J.send(M.data)}catch(S){o.handleError(M,J,null,S)}if(!M.async){N()}function I(){if(M.success){M.success(V,R)}if(M.global){o.event.trigger("ajaxSuccess",[J,M])}}function L(){if(M.complete){M.complete(J,R)}if(M.global){o.event.trigger("ajaxComplete",[J,M])}if(M.global&&!--o.active){o.event.trigger("ajaxStop")}}return J},handleError:function(F,H,E,G){if(F.error){F.error(H,E,G)}if(F.global){o.event.trigger("ajaxError",[H,F,G])}},active:0,httpSuccess:function(F){try{return !F.status&&location.protocol=="file:"||(F.status>=200&&F.status<300)||F.status==304||F.status==1223}catch(E){}return false},httpNotModified:function(G,E){try{var H=G.getResponseHeader("Last-Modified");return G.status==304||H==o.lastModified[E]}catch(F){}return false},httpData:function(J,H,G){var F=J.getResponseHeader("content-type"),E=H=="xml"||!H&&F&&F.indexOf("xml")>=0,I=E?J.responseXML:J.responseText;if(E&&I.documentElement.tagName=="parsererror"){throw"parsererror"}if(G&&G.dataFilter){I=G.dataFilter(I,H)}if(typeof I==="string"){if(H=="script"){o.globalEval(I)}if(H=="json"){I=l["eval"]("("+I+")")}}return I},param:function(E){var G=[];function H(I,J){G[G.length]=encodeURIComponent(I)+"="+encodeURIComponent(J)}if(o.isArray(E)||E.jquery){o.each(E,function(){H(this.name,this.value)})}else{for(var F in E){if(o.isArray(E[F])){o.each(E[F],function(){H(F,this)})}else{H(F,o.isFunction(E[F])?E[F]():E[F])}}}return G.join("&").replace(/%20/g,"+")}});var m={},n,d=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];function t(F,E){var G={};o.each(d.concat.apply([],d.slice(0,E)),function(){G[this]=F});return G}o.fn.extend({show:function(J,L){if(J){return this.animate(t("show",3),J,L)}else{for(var H=0,F=this.length;H<F;H++){var E=o.data(this[H],"olddisplay");this[H].style.display=E||"";if(o.css(this[H],"display")==="none"){var G=this[H].tagName,K;if(m[G]){K=m[G]}else{var I=o("<"+G+" />").appendTo("body");K=I.css("display");if(K==="none"){K="block"}I.remove();m[G]=K}o.data(this[H],"olddisplay",K)}}for(var H=0,F=this.length;H<F;H++){this[H].style.display=o.data(this[H],"olddisplay")||""}return this}},hide:function(H,I){if(H){return this.animate(t("hide",3),H,I)}else{for(var G=0,F=this.length;G<F;G++){var E=o.data(this[G],"olddisplay");if(!E&&E!=="none"){o.data(this[G],"olddisplay",o.css(this[G],"display"))}}for(var G=0,F=this.length;G<F;G++){this[G].style.display="none"}return this}},_toggle:o.fn.toggle,toggle:function(G,F){var E=typeof G==="boolean";return o.isFunction(G)&&o.isFunction(F)?this._toggle.apply(this,arguments):G==null||E?this.each(function(){var H=E?G:o(this).is(":hidden");o(this)[H?"show":"hide"]()}):this.animate(t("toggle",3),G,F)},fadeTo:function(E,G,F){return this.animate({opacity:G},E,F)},animate:function(I,F,H,G){var E=o.speed(F,H,G);return this[E.queue===false?"each":"queue"](function(){var K=o.extend({},E),M,L=this.nodeType==1&&o(this).is(":hidden"),J=this;for(M in I){if(I[M]=="hide"&&L||I[M]=="show"&&!L){return K.complete.call(this)}if((M=="height"||M=="width")&&this.style){K.display=o.css(this,"display");K.overflow=this.style.overflow}}if(K.overflow!=null){this.style.overflow="hidden"}K.curAnim=o.extend({},I);o.each(I,function(O,S){var R=new o.fx(J,K,O);if(/toggle|show|hide/.test(S)){R[S=="toggle"?L?"show":"hide":S](I)}else{var Q=S.toString().match(/^([+-]=)?([\d+-.]+)(.*)$/),T=R.cur(true)||0;if(Q){var N=parseFloat(Q[2]),P=Q[3]||"px";if(P!="px"){J.style[O]=(N||1)+P;T=((N||1)/R.cur(true))*T;J.style[O]=T+P}if(Q[1]){N=((Q[1]=="-="?-1:1)*N)+T}R.custom(T,N,P)}else{R.custom(T,S,"")}}});return true})},stop:function(F,E){var G=o.timers;if(F){this.queue([])}this.each(function(){for(var H=G.length-1;H>=0;H--){if(G[H].elem==this){if(E){G[H](true)}G.splice(H,1)}}});if(!E){this.dequeue()}return this}});o.each({slideDown:t("show",1),slideUp:t("hide",1),slideToggle:t("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"}},function(E,F){o.fn[E]=function(G,H){return this.animate(F,G,H)}});o.extend({speed:function(G,H,F){var E=typeof G==="object"?G:{complete:F||!F&&H||o.isFunction(G)&&G,duration:G,easing:F&&H||H&&!o.isFunction(H)&&H};E.duration=o.fx.off?0:typeof E.duration==="number"?E.duration:o.fx.speeds[E.duration]||o.fx.speeds._default;E.old=E.complete;E.complete=function(){if(E.queue!==false){o(this).dequeue()}if(o.isFunction(E.old)){E.old.call(this)}};return E},easing:{linear:function(G,H,E,F){return E+F*G},swing:function(G,H,E,F){return((-Math.cos(G*Math.PI)/2)+0.5)*F+E}},timers:[],fx:function(F,E,G){this.options=E;this.elem=F;this.prop=G;if(!E.orig){E.orig={}}}});o.fx.prototype={update:function(){if(this.options.step){this.options.step.call(this.elem,this.now,this)}(o.fx.step[this.prop]||o.fx.step._default)(this);if((this.prop=="height"||this.prop=="width")&&this.elem.style){this.elem.style.display="block"}},cur:function(F){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null)){return this.elem[this.prop]}var E=parseFloat(o.css(this.elem,this.prop,F));return E&&E>-10000?E:parseFloat(o.curCSS(this.elem,this.prop))||0},custom:function(I,H,G){this.startTime=e();this.start=I;this.end=H;this.unit=G||this.unit||"px";this.now=this.start;this.pos=this.state=0;var E=this;function F(J){return E.step(J)}F.elem=this.elem;if(F()&&o.timers.push(F)&&!n){n=setInterval(function(){var K=o.timers;for(var J=0;J<K.length;J++){if(!K[J]()){K.splice(J--,1)}}if(!K.length){clearInterval(n);n=g}},13)}},show:function(){this.options.orig[this.prop]=o.attr(this.elem.style,this.prop);this.options.show=true;this.custom(this.prop=="width"||this.prop=="height"?1:0,this.cur());o(this.elem).show()},hide:function(){this.options.orig[this.prop]=o.attr(this.elem.style,this.prop);this.options.hide=true;this.custom(this.cur(),0)},step:function(H){var G=e();if(H||G>=this.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;var E=true;for(var F in this.options.curAnim){if(this.options.curAnim[F]!==true){E=false}}if(E){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;this.elem.style.display=this.options.display;if(o.css(this.elem,"display")=="none"){this.elem.style.display="block"}}if(this.options.hide){o(this.elem).hide()}if(this.options.hide||this.options.show){for(var I in this.options.curAnim){o.attr(this.elem.style,I,this.options.orig[I])}}this.options.complete.call(this.elem)}return false}else{var J=G-this.startTime;this.state=J/this.options.duration;this.pos=o.easing[this.options.easing||(o.easing.swing?"swing":"linear")](this.state,J,0,1,this.options.duration);this.now=this.start+((this.end-this.start)*this.pos);this.update()}return true}};o.extend(o.fx,{speeds:{slow:600,fast:200,_default:400},step:{opacity:function(E){o.attr(E.elem.style,"opacity",E.now)},_default:function(E){if(E.elem.style&&E.elem.style[E.prop]!=null){E.elem.style[E.prop]=E.now+E.unit}else{E.elem[E.prop]=E.now}}}});if(document.documentElement.getBoundingClientRect){o.fn.offset=function(){if(!this[0]){return{top:0,left:0}}if(this[0]===this[0].ownerDocument.body){return o.offset.bodyOffset(this[0])}var G=this[0].getBoundingClientRect(),J=this[0].ownerDocument,F=J.body,E=J.documentElement,L=E.clientTop||F.clientTop||0,K=E.clientLeft||F.clientLeft||0,I=G.top+(self.pageYOffset||o.boxModel&&E.scrollTop||F.scrollTop)-L,H=G.left+(self.pageXOffset||o.boxModel&&E.scrollLeft||F.scrollLeft)-K;return{top:I,left:H}}}else{o.fn.offset=function(){if(!this[0]){return{top:0,left:0}}if(this[0]===this[0].ownerDocument.body){return o.offset.bodyOffset(this[0])}o.offset.initialized||o.offset.initialize();var J=this[0],G=J.offsetParent,F=J,O=J.ownerDocument,M,H=O.documentElement,K=O.body,L=O.defaultView,E=L.getComputedStyle(J,null),N=J.offsetTop,I=J.offsetLeft;while((J=J.parentNode)&&J!==K&&J!==H){M=L.getComputedStyle(J,null);N-=J.scrollTop,I-=J.scrollLeft;if(J===G){N+=J.offsetTop,I+=J.offsetLeft;if(o.offset.doesNotAddBorder&&!(o.offset.doesAddBorderForTableAndCells&&/^t(able|d|h)$/i.test(J.tagName))){N+=parseInt(M.borderTopWidth,10)||0,I+=parseInt(M.borderLeftWidth,10)||0}F=G,G=J.offsetParent}if(o.offset.subtractsBorderForOverflowNotVisible&&M.overflow!=="visible"){N+=parseInt(M.borderTopWidth,10)||0,I+=parseInt(M.borderLeftWidth,10)||0}E=M}if(E.position==="relative"||E.position==="static"){N+=K.offsetTop,I+=K.offsetLeft}if(E.position==="fixed"){N+=Math.max(H.scrollTop,K.scrollTop),I+=Math.max(H.scrollLeft,K.scrollLeft)}return{top:N,left:I}}}o.offset={initialize:function(){if(this.initialized){return}var L=document.body,F=document.createElement("div"),H,G,N,I,M,E,J=L.style.marginTop,K='<div style="position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;"><div></div></div><table style="position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;" cellpadding="0" cellspacing="0"><tr><td></td></tr></table>';M={position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",height:"1px",visibility:"hidden"};for(E in M){F.style[E]=M[E]}F.innerHTML=K;L.insertBefore(F,L.firstChild);H=F.firstChild,G=H.firstChild,I=H.nextSibling.firstChild.firstChild;this.doesNotAddBorder=(G.offsetTop!==5);this.doesAddBorderForTableAndCells=(I.offsetTop===5);H.style.overflow="hidden",H.style.position="relative";this.subtractsBorderForOverflowNotVisible=(G.offsetTop===-5);L.style.marginTop="1px";this.doesNotIncludeMarginInBodyOffset=(L.offsetTop===0);L.style.marginTop=J;L.removeChild(F);this.initialized=true},bodyOffset:function(E){o.offset.initialized||o.offset.initialize();var G=E.offsetTop,F=E.offsetLeft;if(o.offset.doesNotIncludeMarginInBodyOffset){G+=parseInt(o.curCSS(E,"marginTop",true),10)||0,F+=parseInt(o.curCSS(E,"marginLeft",true),10)||0}return{top:G,left:F}}};o.fn.extend({position:function(){var I=0,H=0,F;if(this[0]){var G=this.offsetParent(),J=this.offset(),E=/^body|html$/i.test(G[0].tagName)?{top:0,left:0}:G.offset();J.top-=j(this,"marginTop");J.left-=j(this,"marginLeft");E.top+=j(G,"borderTopWidth");E.left+=j(G,"borderLeftWidth");F={top:J.top-E.top,left:J.left-E.left}}return F},offsetParent:function(){var E=this[0].offsetParent||document.body;while(E&&(!/^body|html$/i.test(E.tagName)&&o.css(E,"position")=="static")){E=E.offsetParent}return o(E)}});o.each(["Left","Top"],function(F,E){var G="scroll"+E;o.fn[G]=function(H){if(!this[0]){return null}return H!==g?this.each(function(){this==l||this==document?l.scrollTo(!F?H:o(l).scrollLeft(),F?H:o(l).scrollTop()):this[G]=H}):this[0]==l||this[0]==document?self[F?"pageYOffset":"pageXOffset"]||o.boxModel&&document.documentElement[G]||document.body[G]:this[0][G]}});o.each(["Height","Width"],function(I,G){var E=I?"Left":"Top",H=I?"Right":"Bottom",F=G.toLowerCase();o.fn["inner"+G]=function(){return this[0]?o.css(this[0],F,false,"padding"):null};o.fn["outer"+G]=function(K){return this[0]?o.css(this[0],F,false,K?"margin":"border"):null};var J=G.toLowerCase();o.fn[J]=function(K){return this[0]==l?document.compatMode=="CSS1Compat"&&document.documentElement["client"+G]||document.body["client"+G]:this[0]==document?Math.max(document.documentElement["client"+G],document.body["scroll"+G],document.documentElement["scroll"+G],document.body["offset"+G],document.documentElement["offset"+G]):K===g?(this.length?o.css(this[0],J):null):this.css(J,typeof K==="string"?K:K+"px")}})})();


/* include: ui.mouse.js */
(function($) {
	
	//If the UI scope is not available, add it
	$.ui = $.ui || {};
	
	//Add methods that are vital for all mouse interaction stuff (plugin registering)
	$.extend($.ui, {
		plugin: {
			add: function(module, option, set) {
				var proto = $.ui[module].prototype;
				for(var i in set) {
					proto.plugins[i] = proto.plugins[i] || [];
					proto.plugins[i].push([option, set[i]]);
				}
			},
			call: function(instance, name, arguments) {
				var set = instance.plugins[name]; if(!set) return;
				for (var i = 0; i < set.length; i++) {
					if (instance.options[set[i][0]]) set[i][1].apply(instance.element, arguments);
				}
			}	
		},
		cssCache: {},
		css: function(name) {
			if ($.ui.cssCache[name]) return $.ui.cssCache[name];
			
			var tmp = $('<div class="ui-resizable-gen">').addClass(name).css(
				{position:'absolute', top:'-5000px', left:'-5000px', display:'block'}
			).appendTo('body');
			
			//Opera and Safari set width and height to 0px instead of auto
			//Safari returns rgba(0,0,0,0) when bgcolor is not set
			$.ui.cssCache[name] = !!(
				((/^[1-9]/).test(tmp.css('height')) || (/^[1-9]/).test(tmp.css('width')) || 
				!(/none/).test(tmp.css('backgroundImage')) || !(/transparent|rgba\(0, 0, 0, 0\)/).test(tmp.css('backgroundColor')))
			);
			try { $('body').get(0).removeChild(tmp.get(0));	} catch(e){}
			return $.ui.cssCache[name];
		},
		disableSelection: function(e) {
			if (!e) return;
			e.unselectable = "on";
			e.onselectstart = function() {	return false; };
			if (e.style) e.style.MozUserSelect = "none";
		},
		enableSelection: function(e) {
			if (!e) return;
			e.unselectable = "off";
			e.onselectstart = function() { return true; };
			if (e.style) e.style.MozUserSelect = "";
		}
	});
	
	/********************************************************************************************************/

	$.fn.extend({
		mouseInteraction: function(o) {
			return this.each(function() {
				new $.ui.mouseInteraction(this, o);
			});
		},
		removeMouseInteraction: function(o) {
			return this.each(function() {
				if($.data(this, "ui-mouse"))
					$.data(this, "ui-mouse").destroy();
			});
		}
	});
	
	/********************************************************************************************************/
	
	$.ui.mouseInteraction = function(element, options) {
	
		var self = this;
		this.element = element;
		$.data(this.element, "ui-mouse", this);
		this.options = $.extend({}, options);
		
		$(element).bind('mousedown.draggable', function() { return self.click.apply(self, arguments); });
		if($.browser.msie) $(element).attr('unselectable', 'on'); //Prevent text selection in IE
		
	};
	
	$.extend($.ui.mouseInteraction.prototype, {
		
		destroy: function() { $(this.element).unbind('mousedown.draggable'); },
		trigger: function() { return this.click.apply(this, arguments); },
		click: function(e) {
			
			if(
				   e.which != 1 //only left click starts dragging
				|| $.inArray(e.target.nodeName.toLowerCase(), this.options.dragPrevention) != -1 // Prevent execution on defined elements
				|| (this.options.condition && !this.options.condition.apply(this.options.executor || this, [e, this.element])) //Prevent execution on condition
			) return true;
			
			var self = this;
			var initialize = function() {
				self._MP = { left: e.pageX, top: e.pageY }; // Store the click mouse position
				$(document).bind('mouseup.draggable', function() { return self.stop.apply(self, arguments); });
				$(document).bind('mousemove.draggable', function() { return self.drag.apply(self, arguments); });
			};

			if(this.options.delay) {
				if(this.timer) clearInterval(this.timer);
				this.timer = setTimeout(initialize, this.options.delay);
			} else {
				initialize();
			}
			
			return false;
			
		},
		stop: function(e) {			
			
			var o = this.options;
			if(!this.initialized) return $(document).unbind('mouseup.draggable').unbind('mousemove.draggable');

			if(this.options.stop) this.options.stop.call(this.options.executor || this, e, this.element);
			$(document).unbind('mouseup.draggable').unbind('mousemove.draggable');
			this.initialized = false;
			return false;
			
		},
		drag: function(e) {

			var o = this.options;
			if ($.browser.msie && !e.button) return this.stop.apply(this, [e]); // IE mouseup check
			
			if(!this.initialized && (Math.abs(this._MP.left-e.pageX) >= o.distance || Math.abs(this._MP.top-e.pageY) >= o.distance)) {
				if(this.options.start) this.options.start.call(this.options.executor || this, e, this.element);
				this.initialized = true;
			} else {
				if(!this.initialized) return false;
			}

			if(o.drag) o.drag.call(this.options.executor || this, e, this.element);
			return false;
			
		}
	});

 })(jQuery);


/* include: ui.draggable.js */
(function($) {

	$.fn.extend({
		draggable: function(options) {
			var args = Array.prototype.slice.call(arguments, 1);
			
			return this.each(function() {
				if (typeof options == "string") {
					var drag = $.data(this, "ui-draggable");
					drag[options].apply(drag, args);

				} else if(!$.data(this, "ui-draggable"))
					new $.ui.draggable(this, options);
			});
		}
	});
	
	$.ui.draggable = function(element, options) {
		//Initialize needed constants
		var self = this;
		
		this.element = $(element);
		
		$.data(element, "ui-draggable", this);
		this.element.addClass("ui-draggable");
		
		//Prepare the passed options
		this.options = $.extend({}, options);
		var o = this.options;
		$.extend(o, {
			helper: o.ghosting == true ? 'clone' : (o.helper || 'original'),
			handle : o.handle ? ($(o.handle, element)[0] ? $(o.handle, element) : this.element) : this.element,
			appendTo: o.appendTo || 'parent'		
		});
		
		$(element).bind("setData.draggable", function(event, key, value){
			self.options[key] = value;
		}).bind("getData.draggable", function(event, key){
			return self.options[key];
		});
		
		//Initialize mouse events for interaction
		$(o.handle).mouseInteraction({
			executor: this,
			delay: o.delay,
			distance: o.distance || 0,
			dragPrevention: o.prevention ? o.prevention.toLowerCase().split(',') : ['input','textarea','button','select','option'],
			start: this.start,
			stop: this.stop,
			drag: this.drag,
			condition: function(e) { return !(e.target.className.indexOf("ui-resizable-handle") != -1 || this.disabled); }
		});
		
		//Position the node
		if(o.helper == 'original' && (this.element.css('position') == 'static' || this.element.css('position') == ''))
			this.element.css('position', 'relative');
		
	};
	
	$.extend($.ui.draggable.prototype, {
		plugins: {},
		ui: function(e) {
			return {
				helper: this.helper,
				position: this.position,
				absolutePosition: this.positionAbs,
				instance: this,
				options: this.options					
			};
		},
		propagate: function(n,e) {
			$.ui.plugin.call(this, n, [e, this.ui()]);
			return this.element.triggerHandler(n == "drag" ? n : "drag"+n, [e, this.ui()], this.options[n]);
		},
		destroy: function() {
			this.handle.removeMouseInteraction();
			this.element
				.removeClass("ui-draggable ui-draggable-disabled")
				.removeData("ui-draggable")
				.unbind(".draggable");
		},
		enable: function() {
			this.element.removeClass("ui-draggable-disabled");
			this.disabled = false;
		},
		disable: function() {
			this.element.addClass("ui-draggable-disabled");
			this.disabled = true;
		},
		recallOffset: function(e) {

			var elementPosition = { left: this.elementOffset.left - this.offsetParentOffset.left, top: this.elementOffset.top - this.offsetParentOffset.top };
			var r = this.helper.css('position') == 'relative';

			//Generate the original position
			this.originalPosition = {
				left: (r ? parseInt(this.helper.css('left'),10) || 0 : elementPosition.left + (this.offsetParent[0] == document.body ? 0 : this.offsetParent[0].scrollLeft)),
				top: (r ? parseInt(this.helper.css('top'),10) || 0 : elementPosition.top + (this.offsetParent[0] == document.body ? 0 : this.offsetParent[0].scrollTop))
			};
			
			//Generate a flexible offset that will later be subtracted from e.pageX/Y
			this.offset = {left: this._pageX - this.originalPosition.left, top: this._pageY - this.originalPosition.top };
			
		},
		start: function(e) {
			
			var o = this.options;
			if($.ui.ddmanager) $.ui.ddmanager.current = this;
			
			//Create and append the visible helper
			this.helper = typeof o.helper == 'function' ? $(o.helper.apply(this.element[0], [e])) : (o.helper == 'clone' ? this.element.clone().appendTo((o.appendTo == 'parent' ? this.element[0].parentNode : o.appendTo)) : this.element);
			if(this.helper[0] != this.element[0]) this.helper.css('position', 'absolute');
			if(!this.helper.parents('body').length) this.helper.appendTo((o.appendTo == 'parent' ? this.element[0].parentNode : o.appendTo));

			//Find out the next positioned parent
			this.offsetParent = (function(cp) {
				while(cp) {
					if(cp.style && (/(absolute|relative|fixed)/).test($.css(cp,'position'))) return $(cp);
					cp = cp.parentNode ? cp.parentNode : null;
				}; return $("body");		
			})(this.helper[0].parentNode);
			
			//Prepare variables for position generation
			this.elementOffset = this.element.offset();
			this.offsetParentOffset = this.offsetParent.offset();
			var elementPosition = { left: this.elementOffset.left - this.offsetParentOffset.left, top: this.elementOffset.top - this.offsetParentOffset.top };
			this._pageX = e.pageX; this._pageY = e.pageY;
			this.clickOffset = { left: e.pageX - this.elementOffset.left, top: e.pageY - this.elementOffset.top };
			var r = this.helper.css('position') == 'relative';

			//Generate the original position
			this.originalPosition = {
				left: (r ? parseInt(this.helper.css('left'),10) || 0 : elementPosition.left + (this.offsetParent[0] == document.body ? 0 : this.offsetParent[0].scrollLeft)),
				top: (r ? parseInt(this.helper.css('top'),10) || 0 : elementPosition.top + (this.offsetParent[0] == document.body ? 0 : this.offsetParent[0].scrollTop))
			};
			
			//If we have a fixed element, we must subtract the scroll offset again
			if(this.element.css('position') == 'fixed') {
				this.originalPosition.top -= this.offsetParent[0] == document.body ? $(document).scrollTop() : this.offsetParent[0].scrollTop;
				this.originalPosition.left -= this.offsetParent[0] == document.body ? $(document).scrollLeft() : this.offsetParent[0].scrollLeft;
			}
			
			//Generate a flexible offset that will later be subtracted from e.pageX/Y
			this.offset = {left: e.pageX - this.originalPosition.left, top: e.pageY - this.originalPosition.top };
			
			//Call plugins and callbacks
			this.propagate("start", e);

			this.helperProportions = { width: this.helper.outerWidth(), height: this.helper.outerHeight() };
			if ($.ui.ddmanager && !o.dropBehaviour) $.ui.ddmanager.prepareOffsets(this, e);
			
			//If we have something in cursorAt, we'll use it
			if(o.cursorAt) {
				if(o.cursorAt.top != undefined || o.cursorAt.bottom != undefined) {
					this.offset.top -= this.clickOffset.top - (o.cursorAt.top != undefined ? o.cursorAt.top : (this.helperProportions.height - o.cursorAt.bottom));
					this.clickOffset.top = (o.cursorAt.top != undefined ? o.cursorAt.top : (this.helperProportions.height - o.cursorAt.bottom));
				}
				if(o.cursorAt.left != undefined || o.cursorAt.right != undefined) {
					this.offset.left -= this.clickOffset.left - (o.cursorAt.left != undefined ? o.cursorAt.left : (this.helperProportions.width - o.cursorAt.right));
					this.clickOffset.left = (o.cursorAt.left != undefined ? o.cursorAt.left : (this.helperProportions.width - o.cursorAt.right));
				}
			}

			return false;

		},
		clear: function() {
			if($.ui.ddmanager) $.ui.ddmanager.current = null;
			this.helper = null;
		},
		stop: function(e) {

			//If we are using droppables, inform the manager about the drop
			if ($.ui.ddmanager && !this.options.dropBehaviour)
				$.ui.ddmanager.drop(this, e);
				
			//Call plugins and trigger callbacks
			this.propagate("stop", e);
			
			if(this.cancelHelperRemoval) return false;			
			if(this.options.helper != 'original') this.helper.remove();
			this.clear();

			return false;
		},
		drag: function(e) {

			//Compute the helpers position
			this.position = { top: e.pageY - this.offset.top, left: e.pageX - this.offset.left };
			this.positionAbs = { left: e.pageX - this.clickOffset.left, top: e.pageY - this.clickOffset.top };

			//Call plugins and callbacks			
			this.position = this.propagate("drag", e) || this.position;
			
			this.helper.css({ left: this.position.left+'px', top: this.position.top+'px' }); // Stick the helper to the cursor
			if($.ui.ddmanager) $.ui.ddmanager.drag(this, e);
			return false;
			
		}
	});

})(jQuery);



/* include: jquery.bgiframe.min.js */
/* Copyright (c) 2006 Brandon Aaron (http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * $LastChangedDate: 2007-07-22 07:45:56 +0800 (Sun, 22 Jul 2007) $
 * $Rev: 2447 $
 *
 * Version 2.1.1
 */
(function($){$.fn.bgIframe=$.fn.bgiframe=function(s){if($.browser.msie&&/6.0/.test(navigator.userAgent)){s=$.extend({top:'auto',left:'auto',width:'auto',height:'auto',opacity:true,src:'javascript:false;'},s||{});var prop=function(n){return n&&n.constructor==Number?n+'px':n;},html='<iframe class="bgiframe"frameborder="0"tabindex="-1"src="'+s.src+'"'+'style="display:block;position:absolute;z-index:-1;'+(s.opacity!==false?'filter:Alpha(Opacity=\'0\');':'')+'top:'+(s.top=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderTopWidth)||0)*-1)+\'px\')':prop(s.top))+';'+'left:'+(s.left=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderLeftWidth)||0)*-1)+\'px\')':prop(s.left))+';'+'width:'+(s.width=='auto'?'expression(this.parentNode.offsetWidth+\'px\')':prop(s.width))+';'+'height:'+(s.height=='auto'?'expression(this.parentNode.offsetHeight+\'px\')':prop(s.height))+';'+'"/>';return this.each(function(){if($('> iframe.bgiframe',this).length==0)this.insertBefore(document.createElement(html),this.firstChild);});}return this;};})(jQuery);


/* include: util.js */
// utility function
var Util = {
/**
 * helper function for supplant() 
 * return true if the input object is a string or a number
 *
 * @name isStringOrNumber
 * @type Boolean
 * @param Object a
 */
  isStringOrNumber: function (a) {
  return  typeof a === "string" ||
          typeof a === "number";
  },
  
  prettyPrint: function(obj, level) {
    if (jQuery.browser.mozilla) {
      return obj;
    }
    
    if ((level || 0) > 3 || (obj && obj.tagName)) {
      if (obj && obj.tagName) {
        return "<" + obj.tagName + ": " + Util.prettyPrint({id: obj.id, className: obj.className}, 3) + ">";
      } else if (obj && obj.nodeName) {
        return obj.nodeName + ": " + obj.nodeValue;
      } else {
        return obj;
      }

    } else if ((typeof obj) == "function") {
      return "function";

    } else if ((typeof obj) == "object") {
      var pairs = [];
      for (x in obj) {
        if ((typeof obj[x]) == "function") {
          // 
        } else {
          pairs.push(x + ": " + Util.prettyPrint(obj[x], (level || 0) + 1));
        }
      }
      return "{ " + pairs.join(", ") + " }";

    } else {
      return Util.prettyPrint(obj, (level || 0) + 1);
    }
  },
  
  merge_objects: function(objectA, objectB) {
    for (var key in objectA) {
      if (typeof objectB[key] == 'undefined') {
        // 
      } else {
        if (typeof(objectA[key]) == 'object') {
          objectA[key] = Util.merge_objects(objectA[key], objectB[key]);
        } else {
          objectA[key] = objectB[key];
        }
      }
    }
    for (var key in objectB) {
      if (typeof objectA[key] == 'undefined') {
        objectA[key] = objectB[key];
      }
    }
    return objectA;
  },

  /**
   * doc and code belong to
   * http://javascript.crockford.com/remedial.html
   *
   * supplant does variable substitution on the string. 
   * It scans through the string looking for expressions enclosed in { } braces.
   * If an expression is found, use it as a key on the object, 
   * and if the key has a string value or number value, 
   * it is substituted for the bracket expression and it repeats. 
   *
   * @example util.supplant(url, param)
   * @before url = "{media}logo.gif"; param = {domain: 'valvion.com', media: 'http://media.valvion.com/'};
   * @result "http://media.valvion.com/logo.gif"
   *
   * @name supplant
   * @type String
   * @param String str The template string to be replaced
   * @param Object obj The object contains data
   * @cat Utility
   */
  supplant: function (str, obj) {
    return str.replace(/{([^{}]*)}/g,
        function (a, b) {
            var value = obj[ b ];
            return Util.isStringOrNumber( value ) ? value : a;
        }
    );
  },
  
  supplant_by_substring: function(str, obj) {
    var matches = str.match(/{([^{}]*)}/g);
    for (var x = 0; x < matches.length; x++) {
      var si = str.indexOf(matches[x]);
      var ei = si + matches[x].length;
      var dup = obj[matches[x].substring(1, matches[x].length-1)];
      if (dup || dup == 0 || dup == "") {
        str = str.substring(0, si) + dup + str.substring(ei, str.length);
      }
    }
    return str;
  },
  
  supplant_configure_engine: function() {
    /* some sites, e.g. Flickr, apparently modifies String.replace */
    var s = Util.supplant("{x}", { "x": "y" });
    if (s != "y") {
      // shcp.debug("Bad Util.supplant", s);
      Util.supplant = Util.supplant_by_substring;
      // shcp.debug("Switching to Util.supplant_by_substring", Util.supplant("{x}", { "x": "y" }));
    } else {
      // shcp.debug("Valid Util.supplant", s);
    }
  },

  /**
   * mimic Rails ActiveSupport isBlank function 
   */
  isBlank: function( a ) {
    if ( typeof a == "undefined" || a === null || a == false || 
        (typeof a == "string" && jQuery.trim( a ) == "") ) return true;
    
    if ( a instanceof Array )
      for (var i = 0, il = a.length; i < il; i++ )
        if ( isNotBlank( a[i] ) ) return false;
    
    // a has passed all bank tests so a is not bank
    return false;
  },
  
  isNotBlank: function ( a ) {
    return !Util.isBlank( a );
  }
  
};


/*
 * selector utilities
 */
jQuery.extend( Util, {
 /**
  * @name selectByBackgroundColor
  * @type jQuery
  * @
  */
  selectByBackgroundColor: function ( selector, colorString ) {
    var compactColorString = colorString.replace(/ /g, '');
    // shcp.debug("selector", selector, "colorString", colorString, "compactColorString", compactColorString);
    return jQuery( selector ).filter( function ( index ) {
      var bgcolor = jQuery(this).css("background-color") || '';
      var bool1 = bgcolor.replace(/ /g, '') == compactColorString;
      var bool2 = false; // jQuery(this).css("background-color").replace(/ /g, '') == 'rgb(238,238,238)'; // FF3 ?
      // shcp.debug("b4", jQuery(this).css("background-color"), "after", jQuery(this).css("background-color").replace(/ /g, ''), " vs ", compactColorString, bool1, bool2);
      return (bool1 || bool2) ;
    });
  }
});

/**
 * Selection & Range utility functions
 * Reference:
 *   http://www.quirksmode.org/dom/range_intro.html
 */
jQuery.extend( Util, {

  getSelectedText: function () {
    return jQuery.trim( "" + ((!!document.getSelection) ? document.getSelection() :
            (!!window.getSelection) ? window.getSelection() : document.selection.createRange().text));
  },
  
	removeSelectedRange: function () {
  // for Safari, opera ??
  	var sel = window.getSelection ? window.getSelection() : document.selection;
	  if (sel && sel.removeAllRanges) {
	    sel.removeAllRanges(); // Mozilla
	  } else if (sel && sel.empty) {
	    sel.empty();           // IE, Safari
	  }
	},
	
  /**
   * return a range object from a selection for W3C browsers (Mozilla, Opera and Safari)
   * For IE, return a text range object
   * [note] use document.selection.createRange() will return
   * a TextRange object, textRange.htmlText property contains 
   * HTML source as a valid fragment.
   */
  getRange: function ( selection ) {
  	if ( selection.createRange )// IE! return a text range
  	  return selection.createRange();
  	// Firefox, Opera
  	if ( selection.getRangeAt )
  		return selection.getRangeAt( 0 );
    // Safari!
    if ( document.createRange ) {
  		var range = document.createRange();
  		range.setStart( selection.anchorNode, selection.anchorOffset );
  		range.setEnd(   selection.focusNode,  selection.focusOffset );
  		return range;
	  }
	  return null;
  },
  
  getSelection: function() {
    if ( window.getSelection )
    	return window.getSelection();
    if ( document.selection ) // IE
    	return document.selection;
    return null;
  },
  
  getSelectedRange: function () {
    return Util.getRange( Util.getSelection() );
  },
  
  getTextFromRange: function ( range ) {
    if ( range.textContent ) // W3C
      return range.TextContent;
    if ( range.text ) // IE
      return range.text;
    return null; 
  },
  
  surround_method: function(method, hooks) {
    return function() {
      hooks.before && hooks.before.apply(this, arguments);
      this.return_value = method.apply(this, arguments);
      hooks.after && hooks.after.apply(this, arguments);
      return this.return_value;
    }
  },
  
  pluralize: function(count, singular, plural) {
    if (count > 1) {
      return count + " " + (plural || singular + "s");
    } else {
      return count + " " + singular;
    }
  },
  
  /**
   * get all descenders
   */
  descenders: function( selector ) {
    var current = jQuery( selector );
    var result  = jQuery( [] );
    while ( current.length > 0 ) {
      current = current.children();
      result = result.add( current );
      shcp.debug(result.length + " - " + current.length );
    }
    return result;
  }
});

/* some sites, e.g. Flickr, apparently modifies String.replace */
Util.supplant_configure_engine();


/**
 * Extension to jQuery
 */
jQuery.fn.extend({
  /**
   * returns true if "child" is (or is a descendant of) one of the elements 
   * in 'this' jQuery selection
   */
  containsElement: function(child) {
    var that = this;
    return (jQuery.inArray(child, that) >= 0) || (jQuery.grep(jQuery(child).parents(), 
      function(ele, i) { 
        return jQuery.inArray(ele, that) >= 0; 
      }).length > 0
    );
  }
});

(function($){
  $.fn.extend({
    // because input element vs other elements have different padding
    effectiveWidth: function() {
      this.effectiveWidth = (this[0] && this[0].tagName.match(/input|textarea/i)) ? this.outerWidth : this.effectiveWidth = this.width;
      return this.effectiveWidth();
    },
    effectiveHeight: function() {
      this.effectiveHeight = (this[0] && this[0].tagName.match(/input|textarea/i)) ? this.outerHeight : this.height;
      return this.effectiveHeight();
    }
  })
})(jQuery);



/* include: configure.js */
(function(scripts) {
  window.upath = scripts[scripts.length-1].src.substring((window.u || '').length).replace(/\/script\/combine.*$/, '');
})(document.getElementsByTagName('script'));

(function() {
  // merge 2 JSON objects together, with values from objectB overwriting objectA
  // returns the modified objectA
  
  // initialises global variable window.SharedCopy using a base config, 
  // and overwrite specific configs if window.SharedCopy was defined earlier
  window.SharedCopy = Util.merge_objects({
    config: {
      url_base: (window.u || ''),
      url_basepath: (window.u || '') + (window.upath || ''),
      show_toolbar: true,
      default_button: 'k_button_write',
      cursors: {
      	k_button_write:  'crosshair',
      	k_button_line:   'crosshair',
      	k_button_box:    'crosshair',
      	k_button_circle: 'crosshair'
      },
      html: {}
    },
    debugging: true,
    on_document_loaded: function() { }
  }, (window.SharedCopy || {}));
})();



/* include: graphics.js */
// prevent execution of Graphics if included more than once
if(typeof window.Graphics == "undefined") {
/*
 * Graphics library
 * drawing shapes using image-based rendering 
 * reference http://www.p01.org/articles/DHTML_techniques/Drawing_lines_in_JavaScript/
 */

var Graphics = function() {
};

/**
 * Initialize a new 2D Vector object
 * for missing or not number arguments,
 * use previous valid argument value or set to zero
 *
 * @example new Graphics.Vector([3, 5])
 * @result Object x=3 y=5
 * @desc Create a new vector from an array
 *
 * @example new Graphics.Vector([3])
 * @result Object x=3 y=3
 * @desc Create a new vector from one element array
 *
 * @example new Graphics.Vector(6, 8)
 * @result Object x=6 y=8
 * @desc Create a new vector from two arguments
 *
 * @example new Graphics.Vector(6)
 * @result Object x=6 y=6
 * @desc Create a new vector from one argument
 *
 * @example new Graphics.Vector("five", 6)
 * @result Object x=0 y=6
 * @desc Create a new vector with an invalid argument
 *
 * @example new Graphics.Vector( new Graphics.Vector( 6, 4) )
 * @result Object x=6 y=4
 * @desc Create a new vector from another vector 
 *
 * @constructor
 * @private
 * @name Vector
 * @param Vector|Array<Number>|Number a 
 * @param Number b (optional)
 * @cat Graphics
 */

Graphics.init = function(a, arr) {
  // helper function
  function existsAndIsNumber( arr, i ) {
    return arr.length > i && typeof arr[i] === "number";
  }
  var x=0, y=0;
	// a is another Vector
	if (a instanceof Graphics.Vector ) {
		x = a.x;
		y = a.y;
	} // ([4, 6]) => {x:4, y:6}; ([3]) => {x:3, y:3}
	else if ( a instanceof Array ) {
		x = existsAndIsNumber(a, 0) ? a[0] : 0;
		y = existsAndIsNumber(a, 1) ? a[1] : x;
	} // () => {x:0, y:0}; (4) => {x:4, y:4}; (6, 5) => {x:6, y:5}
	else {
		x = existsAndIsNumber(arr, 0) ? arr[0] : 0; 
		y = existsAndIsNumber(arr, 1) ? arr[1] : x;
	}
	return {x: x, y: y};
};

// a 2D point is a 2D vector
Graphics.Point = Graphics.Vector = function ( a ) {
  var init = Graphics.init(a, arguments);
  this.x = init.x;
  this.y = init.y;
};
// Vector methods
Graphics.Vector.prototype = {
  /**
   * act the same as Vector constructor
   * see Vector constructor for usage details
   */
	update: function ( a ) {
    var init = Graphics.init(a, arguments);
    this.x = init.x;
    this.y = init.y;
  },
  
  /**
   * @example [a, b] = point.toArray()
   * @before point = new Graphics.Point( 5, 2);
   * @result a = 5; b = 2;
   * 
   * @name toArray
   * @type Array<Number>
   */
  toArray: function () {
    return [ this.x, this.y ];
  },

  /**
   * return sum of two vectors
   * 
   * @example a.plus( b )
   * @before a = new Graphics.Vector(3, 4); b = new Graphics.Vector(6, 3);
   * @result Object x=9 y=7
   * 
   * @example a.plus( [6, 3] )
   * @before a = new Graphics.Vector(3, 4);
   * @result Object x=9 y=7
   * 
   * @example a.plus( 6, 3 )
   * @before a = new Graphics.Vector(3, 4);
   * @result Object x=9 y=7
   * 
   * @example a.plus( 3 )
   * @before a = new Graphics.Vector(3, 4);
   * @result Object x=6 y=7
   *
   * @name plus
   * @type Vector
   * @param Vector|Array<Number>|Number a
   * @param Number b (optional)
   */
	plus: function ( a ) {
    var init = Graphics.init(a, arguments);
	  return new Graphics.Vector( this.x + init.x, this.y + init.y );
	},
	
  /**
   * return subtraction of two vectors
   * see Vector.plus() for usage details
   *
   * @name minus
   * @type Vector
   * @param Vector|Array<Number>|Number a 
   * @param Number b (optional)
   */
	minus: function ( a ) {
    var init = Graphics.init(a, arguments);
		return new Graphics.Vector( this.x - init.x, this.y - init.y );
	},
	
  /**
   * return true if the vector direction is up
   *
   * @name isUp
   * @type Boolean
   */
	isUp: function () {
		return this.x * this.y < 0;
	}
};
Graphics.Vector.ZERO = function () {return new Graphics.Vector(0, 0); };
Graphics.Vector.ONE  = function () {return new Graphics.Vector(1, 1); };

// Graphics utility functions
Graphics.fn = {
  /**
   * extract all points from arguments
   *
   * @example Graphics.getPoints(a, b, c)
   * @before a = new Graphics.Vector(1, 2); b = [a, a.minus(1)]; c={point: a.plus(1, 2)};
   * @result [Object x=1 y=2, Object x=1 y=2, Object x=0 y=1, Object x=2 y=4]
   *
   * @name getPoints
   * @type Array<Point>
   * @param Point|Array<Point>|Object
   */
	getPoints: function () {
	// return all points in arguments
		var arg, points=[]; 
		for(var i = 0, il = arguments.length; i < il; i++) {
			arg = arguments[i];
			if ( arg instanceof Graphics.Point )
				points.push( arg );
			else if ( arg instanceof Array || (arg && arg.callee) )
				for (var k = 0, kl = arg.length; k < kl; k++)
					points = points.concat( Graphics.getPoints(arg[k]) );
			else
				for(var property in arg)	
					if ( arg[property] instanceof Graphics.Point )
						points.push( arg[property] );
		}
		return points;
	},
	
  /**
   * get all point from arguments and return {minimum x, mimimum y} point
   *
   * @name getLeftTopPoint
   * @type Point
   * @param Point|Array<Point>|Object
   */
  getLeftTopPoint: function () {
    var x = Number.POSITIVE_INFINITY, y = x;
		jQuery.each( Graphics.getPoints(arguments), function(i, p) {
			x = Math.min( x, p.x );
			y = Math.min( y, p.y );
		});
    return new Graphics.Point( x, y );
  },
	
  /**
   * get all point from arguments and return {maximum x, maximum y} point
   *
   * @name getRightBottomPoint
   * @type Point
   * @param Point|Array<Point>|Object
   */
	getRightBottomPoint: function () {
    var x = Number.NEGATIVE_INFINITY, y = x;
		jQuery.each( Graphics.getPoints(arguments), function(i, p) {
			x = Math.max( x, p.x );
			y = Math.max( y, p.y );
		});
    return new Graphics.Point( x, y );
	},

  shapePath: { 
    "line": 	SharedCopy.config.url_basepath + "/style/images/lines/" , 
    "box": 		SharedCopy.config.url_basepath + "/style/images/hboxes/",
    "circle": SharedCopy.config.url_basepath + "/style/images/hcircles/",
    "text": 	SharedCopy.config.url_basepath + "/style/images/lines/"
  },
	
  /**
   * draw a line, box, or circle
   *
   * @name draw
   * @param Object an image HTML element
   * @param Point a start point
   * @param Point a end point
   * @param String shape's name
   */
	draw: function (elem, a, b, shapeName) {
    var match = null;
    if (!shapeName && elem && elem.id && (match = elem.id.match(/^(\D+)/))) shapeName = match[1];
		var path = Graphics.shapePath[ shapeName ];
		if ( !path ) return; // exit if shapeName is invalid
		var max     = Graphics.getMaxPoint(a, b),
				min     = Graphics.getMinPoint(a, b),
				size    = Graphics.getMaxPoint( max.minus( min ), Graphics.Vector.ONE() );
		function getLevel() {
		  // stretchy graphics fixed by qqzhenyi.blogspot.com
      // var level = 1, ceiling = Math.min(1024, Math.max( size.x, size.y, 1 ));
		  var level = 1, ceiling = Math.min(1024, (shapeName=="line" || shapeName=="text" ? Math.min( size.x, size.y ) : Math.max( size.x, size.y, 1 )));
		  while( ceiling >>= 1 ) level <<= 1;
		  return level;
		}
		var url = path + getLevel() + ( b.minus(a).isUp() ? "up.gif?V0" : "down.gif?V0" );
		jQuery(elem).attr("src", url).css( {width: size.x, height: size.y, left: min.x, top: min.y} );
	},
	
  /**
   * get posititon of an event
   *
   * @name getEventPosition
   * @type Point
   * @param Object an HTML event
   */
	getEventPosition: function( event ) {
		event = event || window.event;
		var x = event.pageX || (event.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft)) || 0;
		var y = event.pageY || (event.clientY + (document.documentElement.scrollTop  || document.body.scrollTop))  || 0;
		return new Graphics.Point(x, y);
	},
	
  /**
   * get size of brower's inner 
   *
   * @name getInnerSize
   * @type Vector
   */
	getInnerSize: function () {
	  var docElem = document.documentElement; 
	  if( docElem && docElem.clientWidth && docElem.clientHeight )
	    return new Graphics.Vector( docElem.clientWidth, docElem.clientHeight);
		var body = document.body; 
	  if ( body && body.clientWidth && body.clientHeight )
	    return new Graphics.Vector( body.clientWidth, body.clientHeight );
		if( typeof( window.innerWidth ) == 'number' )
	    return new Graphics.Vector( window.innerWidth, window.innerHeight );    
	  return Graphics.Vector.ZERO();
	}
};

jQuery.extend( Graphics, Graphics.fn );
Graphics.getMinPoint = Graphics.getLeftTopPoint;
Graphics.getMaxPoint = Graphics.getRightBottomPoint;
}


/* include: base.js */
jQuery.noConflict();

if (! window.shcp) (function() {
  window.shcp = {
    // properties
    k_mode: 'k_button_point',
    k_count_history: [],
    k_count: 0,
    increment_count: function(skip_history) {
      while (jQuery(".k_coupling" + shcp.k_count).length > 0) {
        shcp.k_count += 1;
      }
      if (! skip_history) shcp.k_count_history.push(shcp.k_count);
      return shcp.k_count;
    },
    
    plugins: {},
    undo_stack: [],
    user: {
      name    : SharedCopy.config.user_name || 'guest',
      ip      : SharedCopy.config.user_ip || '???.???.???.???',
      clock   : (new Date()).toUTCString() + ""
    },
    
    add_plugin: function(name, obj) {
      this.plugins[name] = this.plugins[name] || {};
      if (obj) jQuery.extend(this.plugins[name], obj);
      return this;
    },
    
    // scoped objects
    page: {
      register_events: function(doc) {
        jQuery('body', doc).start_sharedcopy_mouse();
      },
      
      reset: function(doc) {
        var seen = false;
        jQuery('script').each(function(index, ele) {
          if (ele.id && !seen && ele.id.match(/k_script/)) {
            seen = true;
          } else {
            jQuery(ele).remove();
          }
        });
      }
    },
    
    remove_toolbar: function() { window.location = jQuery('#k_toolbar_footer a')[0].href; },
    toolbar: {
      common_buttons: {},
      click_button: function(mode) {
        jQuery('#k_toolbar_buttons #' + mode).click().focus();
      },
      
      remove: function(index) {
        jQuery('.k_coupling' + index + ',.k_coupling' + index + ' *').unbind('click').unbind('mousedown').remove();
      },
      
      set_k_mode: function(new_k_mode, event_type) {
        if (new_k_mode && new_k_mode.target) {
          var ele = new_k_mode.target;
          if (jQuery.browser.safari) ele = ele.parentNode;
          var matched = null;
          jQuery('#k_toolbar_buttons button').removeClass('active_button');
          jQuery(ele).addClass('active_button');
          event_type = new_k_mode.type;
          new_k_mode = ele.id;
          shcp.clickable.css({cursor: (SharedCopy.config.cursors[new_k_mode] || 'auto') });
        }
        event_type = event_type || 'click';
        shcp.last_k_mode = shcp.k_mode;
        shcp.k_mode = new_k_mode;
        var plugin = shcp.plugins[shcp.k_mode];
        if (plugin && plugin.self && plugin.self[event_type]) {
          shcp.plugins[shcp.k_mode].self[event_type]();
        }
        return true;
      },
      
      render: function(doc) {
        if (! jQuery('#karea', doc)[0]) {
          if (SharedCopy.config.no_css) {
            // do nothing
          } else {
            var link_ele = document.createElement('link');
            link_ele.type = 'text/css';
            link_ele.rel = 'stylesheet';
            link_ele.href = (SharedCopy.config.css_href ? SharedCopy.config.css_href : SharedCopy.config.url_basepath + "/style/base.css?v=" + ((new Date()) * 1));
            (document.getElementsByTagName('head')[0] || document.body).appendChild(link_ele);
          }
          jQuery('body', doc).append("<div id='karea'></div>");
        }
        
        if (! jQuery("#k_toolbar_buttons", doc)[0]) {
          jQuery('#karea', doc).append(Util.supplant(SharedCopy.config.html.toolbar, { 
            url_base: SharedCopy.config.url_base,
            url_basepath: SharedCopy.config.url_basepath,
            comments_showhide: SharedCopy.config.html.comments_showhide
          }));
        }
                
        jQuery('#k_toolbar_buttons button', doc).unbind('click', shcp.toolbar.set_k_mode);        
        var buttons_container = jQuery("#k_toolbar_buttons", doc);
        buttons_container.html("");
        var buttons = SharedCopy.config.buttons || [
          shcp.toolbar.common_buttons.pointer,
          shcp.toolbar.common_buttons.write,
          shcp.toolbar.common_buttons.mark,
          shcp.toolbar.common_buttons.color_button,
          shcp.toolbar.common_buttons.arrow_button,
          shcp.toolbar.common_buttons.line,
          shcp.toolbar.common_buttons.circle,
          shcp.toolbar.common_buttons.box,
          shcp.toolbar.common_buttons.undo
        ];
        jQuery.each(buttons, function(index, button_config) {
          buttons_container.append(Util.supplant(SharedCopy.config.html.toolbar_button, button_config.html));
          shcp.add_plugin(button_config.html.id, button_config.events);
        });
        jQuery('#k_toolbar_buttons button', doc).bind('click', shcp.toolbar.set_k_mode);
        jQuery('#k_toolbar').bgiframe({opacity:false});
      },
      
      position_toolbar: function() {
        var toolbar = jQuery('#k_toolbar');
        if (jQuery.browser.msie && jQuery.browser.version < 8) {
          // absolutish
          if (toolbar[0] && !toolbar[0].className.match(/k_sunken/)) {
            var v = (jQuery(window).scrollTop() + 5) + 'px';
            toolbar.css({ position: 'absolute', top: v });
            if (! window.onscroll) window.onscroll = shcp.toolbar.position_toolbar;
            if (! window.onresize) window.onresize = shcp.toolbar.position_toolbar;
          }
        } else {
          toolbar.css(
            { position: 'fixed', top: '5px' }
          );
        }
      },
      
      on_undo: function() {
        if (shcp.k_count_history.length < 1) {
          shcp.toolbar.click_button(shcp.last_k_mode);
          return;
        }
        shcp.toolbar.exec_undo(shcp.k_count_history.pop());
      },
      
      exec_undo: function(undo_k_count) {
        var coupling_selector = "k_coupling" + undo_k_count;
        var highlight_selector = "k_highlight_text" + undo_k_count;
        if (jQuery("." + coupling_selector).length > 0) {
          // cant cache jQuery result since elements are removed in following steps..
          shcp.Hilite.unwrapNodes(jQuery("." + highlight_selector));
          jQuery("." + highlight_selector).removeClass(coupling_selector).removeClass(highlight_selector);
          jQuery("." + coupling_selector).unbind().remove();
          shcp.toolbar.click_button(shcp.last_k_mode);
        } else if (undo_k_count < 1) {
          shcp.toolbar.click_button(shcp.last_k_mode);
        } else {
          shcp.toolbar.exec_undo(shcp.k_count_history.pop());
        }
      },
      
      on_ready: function(doc) {
        this.click_button(SharedCopy.config.default_button);
        var jele = jQuery('#k_toolbar', doc);
        
        if (SharedCopy.config.show_toolbar) {
          jele.show();
        } else {
          jele.hide();
        }
        
        jele.draggable({
          stop: shcp.toolbar.position_toolbar
        });
        
        shcp.toolbar.position_toolbar();
      }
    },
    
    stickynote: {
      render_form: function(point, options) {
        jQuery('.k_sticky:last .stickynote_ok').click();
        if (! options.skip_k_count) shcp.increment_count(options.skip_k_count_history);
        options = jQuery.extend((window.SharedCopy && SharedCopy.config && SharedCopy.config.comment_options), options);
        var html = options.html || SharedCopy.config.html.sticky_note;
        if (!options.title_text) {
          options.title_text = Util.supplant("<a title=\"{user_name}@{user_ip} {user_clock}\" " + 
            "href=\"{url}\">{user_name} {verb}...</a>", {
              verb: options.verb || 'says',
              url: options.url || (SharedCopy.config.url_base + "/~" + (options.user_name || shcp.user.name)),
              sticky_note_close: SharedCopy.config.html.sticky_note_close,
              url_basepath: SharedCopy.config.url_basepath,
              user_name: options.user_name || shcp.user.name,
              user_ip: options.user_ip || shcp.user.ip,
              user_clock: options.user_clock || shcp.user.clock
            });
        }

        var divId = 'div' + shcp.k_count;
        var options = {
          message_id: options.message_id,
          url_basepath: SharedCopy.config.url_basepath,
          sticky_note_close: Util.supplant(SharedCopy.config.html.sticky_note_close, { url_basepath: SharedCopy.config.url_basepath }),
          id: divId,
          title_text: options.title_text,
          subtitle_text: options.subtitle_text || "",
          top: point.y,
          left: point.x,
          width: (point.width || 250),
          height: (point.height || 115),
          k_count: shcp.k_count,
          current_zindex: 1000000,
          on_cancel: options.on_cancel || "shcp.toolbar.remove(" + shcp.k_count + ")",
          on_ok: options.on_ok || "shcp.stickynote.on_ok(this)",
          user_name: options.user_name || shcp.user.name,
          user_ip: options.user_ip || shcp.user.ip,
          user_clock: options.user_clock || shcp.user.clock
        }
        var element = jQuery(Util.supplant(html, options)).appendTo('#karea');
        jQuery('.k_panel_bottom img', element).css({ cursor: 'normal' });

        shcp.stickynote.make_resizable_draggable(jQuery(element), options);
        jQuery(element).bgiframe({opacity:false});
        return divId;
      },
      
      make_resizable_draggable: function(elements, options) {
        // extracted as standalone method so that we can apply resize/draggable
        // to sticky notes already drawn on a page
        // e.g. shcp.stickynote.make_resizable_draggable(jQuery('.k_sticky').parent());
        elements.each(function(index, element) {
          jQuery(element).css('position', 'absolute').draggable({
            start: shcp.stickynote.dragger.on_start,
            drag: shcp.stickynote.dragger.on_drag,
            handle: jQuery('.k_panel_top', element)
          });
          jQuery('textarea', element).keyup( shcp.stickynote.on_text_keyup ).focus();
        })
        return elements;
      },
      
      on_text_keyup: function(evt) {
        var ele = jQuery(evt.target);
        var scroll = ele.scrollTop();
        if (scroll > 0) {
          var mindiff = parseInt(ele.css('font-size'));
          ele.height(ele.height() + (scroll > mindiff ? scroll : mindiff + scroll));
        }
      },

      render: function(point, options) {
        if (options.position.width<300) options.position.width=300;
        if (options.position.height<110) options.position.height=110;
        var note = jQuery('#' + shcp.stickynote.render_form(point, options));
        jQuery('textarea', note).val(options.content);
        jQuery('.stickynote_ok', note).click();
        note.addClass("stickynote");
        if (options.comment_id) note.addClass("stickynote_" + options.comment_id);
        jQuery('.k_panel_main p', note).html(options.content); // onclick escapes body content. we need the unescaped version
      },

      on_ok: function(ele) {
        function input2html(value) {
          var div = document.createElement('div');
          /* IE6 innerHTML strips out \n, so we need to invent our own delimiter */
          var delimiter = "" + (Math.random() * 100000);
          while (value.indexOf(delimiter) != -1) {
            delimiter = "" + (Math.random() * 100000);
          }
          /* using the tedious create node and .innerHTML to ensure proper escape of input */
          var text = document.createTextNode(value.replace(/(\r\n|\n)/g, delimiter));
          div.appendChild(text);
          re = new RegExp(delimiter, "g");
          html = div.innerHTML;
          return html.replace(re, "<br />");
        }

        var parent = jQuery(ele).parent();
        var text = parent.children('textarea');
        var value = text.val();
        if (!value || value.match(/^\s*$/)) return shcp.remove_stickynote(ele);

        var p = document.createElement("p");
        var p_html = input2html(value);
        p.innerHTML = p_html;
        if (text[0].parentNode) {
          text[0].parentNode.replaceChild(p, text[0]);
          parent.children('input').remove();
        } // ignore if text[0] is orphaned
        return p_html;
      },
      
      dragger: {
        on_start: function(e, ui) {
          // anchors image (if any)
          jQuery('img.' + ui.instance.element[0].id.replace('div', 'k_coupling') + ':first').each(function(index, imgObject) {
            if (! imgObject.anchorPoint) {
              var img = jQuery(imgObject);
              var imgTopLeft = img.offset();
              var noteTopLeft = jQuery(ui.instance.element).offset();
              // if we're sharing any side (top/left), anchor from further side
              if (imgTopLeft.left == noteTopLeft.left) imgTopLeft.left += img.width();
              if (imgTopLeft.top == noteTopLeft.top) imgTopLeft.top += img.height();
              imgObject.anchorPoint = new Graphics.Point(imgTopLeft.left, imgTopLeft.top);
            }
          });
        },
        on_drag: function(e, ui) {
          // update image (if any) based in new sticky note location
          jQuery('img.' + ui.instance.element[0].id.replace('div', 'k_coupling') + ':first').each(function(index, imgObject) {
            if (imgObject.anchorPoint) {
              Graphics.draw(imgObject, imgObject.anchorPoint, new Graphics.Point( ui.position.left, ui.position.top ));
            }
          });
        }
      }
    },
    
    highlight_selected: function() {
      shcp.debug("try highlight");
      var d = document.createElement("div");
      d.appendChild(document.createTextNode(Util.getSelectedText()));
      shcp.Hilite.selectedText = d.innerHTML;
      shcp.Hilite.log( "selectedText = '" + shcp.Hilite.selectedText + "'" );
      // complete highlighting
      var return_value = shcp.Hilite.completeHighlighting();
      Util.removeSelectedRange();
      return return_value;
    },
    
    render_drawing: function(domid, k_mode, k_count) {
      var domObject = document.getElementById(domid);
      if (! domObject) {
        var html = Util.supplant(
          "<div id='wrap_{domid}' class='k_coupling{k_count}' style=''>" +
          "<img id='{domid}' style='position: absolute; height: 1px; width: 1px; z-index: 99998; ' class='k_coupling{k_count} k_passthrough k_translucent k_translucent{k_mode}' height='1' width='1' />" + 
          "</div>", { 
          domid: domid, k_mode: k_mode, k_count: k_count
        });
        jQuery(html).appendTo('#karea');
        domObject = document.getElementById(domid);
      }
      return domObject;
    },
    
    // functions
    on_ready: function(doc, callback) {
      // not working for loaded page: jQuery(doc).ready(callback);
      if (SharedCopy.on_ready) {
        SharedCopy.on_ready(function() { callback(doc); });
      } else {
        callback(doc);
      }
    }
  };
  
  // logging
  shcp.konsole = window.console;
  shcp.debug = function() { };
  if (window.SharedCopy && SharedCopy.debugging) {
    if (jQuery.browser.safari || !window.console) {
      shcp.debug = function(str) { window.status = str; };
    } else {
      shcp.debug = function() { if (window.console && console.log) console.log.apply(console, arguments); };
    }
  }
})();



/* include: mouse.js */
// Base framework
(function($, shcp) {
  // states
  var _state, _mouseup, _mousedown, _mousemove, _mouseover, _mouseout, _click;
  _state = {
    current: null,
    evt: {}
  };
  function stopEvent(evt) {
    if (evt && evt.preventDefault) {
        evt.preventDefault();
        evt.stopPropagation();
    } else if (typeof(event) != 'undefined') {
        event.cancelBubble = false;
        event.returnValue = false;
    }
  }
  function _unbind_all(elements) {
    if (elements && elements.unbind) {
  		elements.unbind('mouseup', _mouseup);
  		elements.unbind('mousemove', _mousemove);
  		elements.unbind('mouseover', _mouseover);
  		elements.unbind('mouseout', _mouseout);
  		elements.unbind('mousedown', _mousedown);
  		elements.unbind('click', _click);
    }
  }
  // execute related function (depending on shcp.k_mode) if exists
  function _exec(evt, current_mode) {
    if (! (shcp && shcp.plugins && shcp.k_mode)) return;
    var o = shcp.plugins[shcp.k_mode];
    if (! o) return;
    o = o[current_mode || _state.current];
    if (o) return o(_state, evt);
    return false;
  }
  
  function _unacceptable(evt) {
    if (evt.which != 1) return true;
    var jtarget = $(evt.target);
    if (jtarget.parents('#karea')[0] && !jtarget.hasClass('k_passthrough')) return true;
    return false;
  }
  
  _mouseup = function(evt) {
    // assert
    if (_unacceptable(evt)) return true;
    
    // setup
    _state.current = 'mouseup';
    _state.evt.mouseup = evt;
    // exec
    var retval = _exec(evt);
    // cleanup
		shcp.clickable.unbind(evt.type, arguments.callee);
		shcp.clickable.unbind('mousemove', _mousemove);
		shcp.clickable.bind('mousedown', _mousedown);
		shcp.clickable.bind('click', _click);

		if (! retval) stopEvent(evt);
    return retval;
  }
  _mousedown = function(evt) {
    // assert
    if (_unacceptable(evt)) return true;
    
    // setup
    _state.current = 'mousedown';
    _state.evt.mousedown = evt;
    shcp.increment_count();
    // exec
    var retval = _exec(evt);
    // cleanup
		shcp.clickable.unbind(evt.type, arguments.callee);
		shcp.clickable.bind('mouseup', _mouseup);
		shcp.clickable.bind('mousemove', _mousemove);

		if (! retval) stopEvent(evt);
    return retval;
  }
  _mousemove = function(evt) {
    // assert
    if (_unacceptable(evt)) return true;

    // setup
    _state.evt.mousemove = evt;
    // exec
    var retval = _exec(evt, (_state.current == 'mousedown' ? 'drag' : 'mousemove'));
    // cleanup

		if (! retval) stopEvent(evt);
    return retval;
  }
  _mouseover = function(evt) {
    // assert
    if (_unacceptable(evt)) return true;

    // setup
    _state.evt.mouseover = evt;
    // exec
    var retval = _exec(evt, 'mouseover');
    // cleanup

		if (! retval) stopEvent(evt);
    return retval;
  }
  _mouseout = function(evt) {
    // assert
    if (_unacceptable(evt)) return true;

    // setup
    _state.evt.mouseout = evt;
    // exec
    var retval = _exec(evt, 'mouseout');
    // cleanup

		if (! retval) stopEvent(evt);
    return retval;
  }
  _click = function(evt) {
    // assert
    if (_unacceptable(evt)) return true;

    // setup
    _state.current = 'click';
    _state.evt.click = evt;
    // exec
    var retval = _exec(evt);
    // cleanup
		shcp.clickable.unbind(evt.type, arguments.callee);
		_state.evt = {};

    if (! retval) stopEvent(evt);
    return retval;
  }
  
  // init
	$.fn.start_sharedcopy_mouse = function(options) {
	  _unbind_all(shcp.clickable);
	  shcp.clickable = this;
	  _unbind_all(shcp.clickable);
		shcp.clickable.bind('mousedown', _mousedown);
		shcp.clickable.bind('mouseover', _mouseover);
		shcp.clickable.bind('mouseout', _mouseout);
	}
})(jQuery, shcp);

// Behaviors
(function(shcp) {
  // setup
  function make_drawing_handler(k_mode) {
    return function(state, evt) {
      var startPosition = Graphics.getEventPosition( state.evt.mousedown );
      var endPosition = Graphics.getEventPosition( state.evt.mousemove );
      var domid = k_mode + shcp.k_count;
      var domObject = shcp.render_drawing(domid, k_mode, shcp.k_count);
      Graphics.draw(domObject, startPosition, endPosition, k_mode );
      return false;
    }
  }
  
  shcp.toolbar.common_buttons.pointer = {
    html: {
      id: 'k_button_point',
      label: "Point", 
      title: "Restore normal mouse behavior",
      style: '',
      css_class: ''
    },
    events: {
      mousedown: function() { return true; },
      drag: function() { return true; },
      mouseup: function() { return true; },
      click: function() { return true; }
    }
  };

  shcp.toolbar.common_buttons.line = {
    html: {
      id: 'k_button_line',
      label: "Line", 
      title: "Click and Drag to draw lines on this page",
      style: '',
      css_class: ''
    },
    events: {
      drag: make_drawing_handler('line')
    }
  };

  shcp.toolbar.common_buttons.box = {
    html: {
      id: 'k_button_box',
      label: "Box", 
      title: "Click and Drag to draw boxes on this page",
      style: '',
      css_class: ''
    },
    events: {
      drag: make_drawing_handler('box')
    }
  };

  shcp.toolbar.common_buttons.circle = {
    html: {
      id: 'k_button_circle',
      label: "Circle", 
      title: "Click and Drag to draw circles on this page",
      style: '',
      css_class: ''
    },
    events: {
      drag: make_drawing_handler('circle')
    }
  };

  shcp.toolbar.common_buttons.write = {
    html: {
      id: 'k_button_write',
      label: "Write", 
      title: "Click or Drag to place Sticky Notes on this page",
      style: '',
      css_class: ''
    },
    events: {
      drag: make_drawing_handler('line'),
      mouseup: function(state, evt) {
        shcp.stickynote.render_form(Graphics.getEventPosition(evt), { skip_k_count: true });
        return false;
      }
    }
  };

  shcp.toolbar.common_buttons.mark = {
    html: {
      id: 'k_button_mark',
      label: "Mark", 
      title: "Select some text to highlight",
      style: '',
      css_class: ''
    },
    events: {
      mousedown: function() { return true; },
      drag: function() { return true; },
      mouseup: function(state, evt) {
        if (state.evt.mousemove) {
          shcp.highlight_selected();
          return false; 
        } else {
          shcp.debug("no highlight");
          return true; 
        }
      }
    }
  };

  shcp.toolbar.common_buttons.undo = {
    html: {
      id: 'k_button_undo',
      label: "Undo", 
      title: "Remove that last sticky note, drawing, highlight, etc",
      style: '',
      css_class: ''
    },
    events: {
      self: {
        click: shcp.toolbar.on_undo
      }
    }
  };
  
  shcp.toolbar.colorpicker = {
    load: function(){
      if(!jQuery('#k_color_script').length){
       jQuery('head').append('<link rel="stylesheet" href="' + SharedCopy.config.url_basepath + '/script/vendor/colorjack/plugin.css" type="text/css">');
       var s = document.createElement('script');
       s.id = 'k_color_script';
       s.src= SharedCopy.config.url_basepath + '/script/vendor/colorjack/plugin.js';
       document.body.appendChild(s);
      }
    },
    render: function(point){
      this.killUnset();
      var color = jQuery('.k_color:last .k_hex').html() || 'FF0000';
      var colorHTML = Util.supplant(SharedCopy.config.html.colorpicker_stub, {
        k_count: shcp.k_count,
        y: point.y,
        x: point.x,
        color: color
      });
      jQuery('#karea').append(colorHTML);
      jQuery('#k_color'+shcp.k_count+' .k_pick').click(function(){
        shcp.toolbar.colorpicker.showPicker(this.parentNode);
      });
      jQuery('#k_color'+shcp.k_count+' .k_pick').click();
    },
    showPicker: function(elm){
      var y = jQuery(elm).css('top');
      var x = parseInt(jQuery(elm).css('left')) + jQuery(elm).width() + 10 + 'px';
      this.killUnset();
      this.killPicker(true);
      var pickerHTML = '<div id="plugin" style="top:' + y + '; left:' + x + '; z-index: 1000001; padding: 7px 10px 11px; background: #FBF489; border: 1px solid #F3E307;"><div id="plugHEX" style="top: 3px; left: 10px; position: absolute;">FF0000</div><div id="colorbox" style="border: 1px solid gray; width: 30px; height: 11px; background-color: #FF0000; top:4px; left: 65px; position: absolute;"></div><div id="plugCLOSE"><div id="plugOK" style="top: 2px; right: 60px; position: absolute; text-decoration: underline;">Ok</div><div id="plugCANCEL" style="top: 2px; right: 12px; position: absolute; text-decoration: underline;">Cancel</div></div><br><div id="SV" style="filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'' + SharedCopy.config.url_basepath + '/script/vendor/colorjack/SatVal.png\', sizingMethod=\'scale\'); margin-right: 10px;" title="Saturation + Value"><div id="SVslide" style="TOP: -4px; LEFT: -4px;">&nbsp;</div></div><form id="H" title="Hue"><div id="Hslide" style="TOP: -7px; LEFT: -8px;">&nbsp;</div><div id="Hmodel"></div><input id="plugParent" type="hidden" value="" /></form></div>';
      jQuery('#karea').append(pickerHTML);
      jQuery('#plugin').hide().show(true);
      this.loadSV();
      jQuery('#plugHEX').mousedown(function(){stop=0; setTimeout('stop=1',100);});
      jQuery('#SV').mousedown(function(event){shcp.toolbar.colorpicker.HSVslide('SVslide','plugin',event);});
      jQuery('#H').mousedown(function(event){shcp.toolbar.colorpicker.HSVslide('Hslide','plugin',event);});
      jQuery('#plugOK').mousedown(function(){
        var parentId = jQuery('#plugParent').attr('value');
        var color = jQuery('#plugin #plugHEX').html();
        jQuery('#'+parentId+' .k_hex').html(color);
        jQuery('#'+parentId+' .k_pick').css('background','#'+color);
        jQuery('#'+parentId).removeClass('k_unchanged');
        shcp.toolbar.colorpicker.killPicker(false);
        return false;
      });
      jQuery('#plugCANCEL').mousedown(function(){
        shcp.toolbar.colorpicker.killUnset();
        shcp.toolbar.colorpicker.killPicker(false);
        return false;
      });
      jQuery('#plugParent').attr('value',elm.id);
      jQuery('#plugin').removeClass().addClass('k_make_remove k_coupling'+elm.id.substring(7));
      var color = jQuery('#'+elm.id+' .k_hex').html();
      this.updateH(color);
      jQuery('#plugin #plugHEX').html(color);
      jQuery('#plugin #colorbox').css('background','#'+color);
    },
    killPicker: function(immediately){
      if (immediately) jQuery('#plugin').remove();
      else jQuery('#plugin').hide(true,function(){jQuery(this).remove()});
    },
    killUnset: function(){
      var parentId = jQuery('#plugParent').attr('value');
      var match = null;
      if (jQuery('#'+parentId).is('.k_unchanged') && (match = parentId.match(/\D(\d+)$/)))
        shcp.toolbar.remove(match[1]);
    },

    //needed for the (function) thingy
    loadSV: function(){},
    updateH: function(){},
    HSVslide: function(){}
  };

  shcp.toolbar.common_buttons.color_button = {
    html: {
      id: 'k_button_color',
      label: 'Color', 
      title: 'Click or Drag to place Color Pickers on this page',
      style: '',
      css_class: ''
    },
    events: {
      drag: function(state, evt) {
        var k_mode = 'line';
        var startPosition = Graphics.getEventPosition( state.evt.mousedown );
        var endPosition = Graphics.getEventPosition( state.evt.mousemove );
        var domid = k_mode + shcp.k_count;
        var domObject = shcp.render_drawing(domid, k_mode, shcp.k_count);
        Graphics.draw(domObject, startPosition, endPosition, k_mode );
        return false;
      },
      mouseup: function(state, evt) {
        var position = Graphics.getEventPosition(evt);
        shcp.toolbar.colorpicker.render(position);
        return false;
      },
      self: {
        click: function() {
          shcp.toolbar.colorpicker.load();
        }
      }
    }
  };

  Graphics.shapePath.arrow = Graphics.shapePath.line;
  Graphics.draw = Util.surround_method(Graphics.draw, {
    after: function(domObject, startPosition, endPosition, k_mode ) {
      var match = null;
  	  if (!k_mode && domObject && domObject.id && (match = domObject.id.match(/^(\D+)/))) k_mode = match[1];

      if (k_mode == 'arrow') {
        var domid = domObject.id;
        var tangent = (endPosition.y - startPosition.y)/(endPosition.x - startPosition.x);
        var angle = Math.atan(tangent);
        var leftSide = endPosition.x < startPosition.x;
        jQuery([angle+0.5,angle-0.5]).each( function(){
          endPosition.x = leftSide ? startPosition.x - Math.cos(this)*30 : startPosition.x + Math.cos(this)*30 ;
          endPosition.y = leftSide ? startPosition.y - Math.sin(this)*30 : startPosition.y + Math.sin(this)*30 ;
          domid += '_a';
          domObject = shcp.render_drawing(domid, k_mode, shcp.k_count);
          Graphics.draw(domObject, startPosition, endPosition, 'line' );
        });
      }
    }
  });
  
  shcp.toolbar.common_buttons.arrow_button = {
    html: {
      id: 'k_button_arrow',
      label: 'Arow', 
      title: 'Click and Drag to draw arrows on this page',
      style: '',
      css_class: ''
    },
    events: {
      drag: make_drawing_handler('arrow')      
    }
  };
  
})(shcp);



/* include: highlight.js */
(function(shcp) {
  /* [note] integrate rangeHilite by adding three new functions
    surroundContents() to Safari
    Hilite.wrapIntersectedElement()
    Hilite.createNewWrapper()
  */

  /**
    * surroundContents(), intersectsNode() for Safari
    */
  var range = document.createRange && document.createRange();
  if ( jQuery.browser.safari ) {
    try {// Safari!!
      range.__proto__.surroundContents = function(parent) {
        /* 
         * http://codingforums.com/showthread.php?t=112358 
         */
      	var frag = this.extractContents();
      	if (frag != null)
      		parent.appendChild(frag);
      	this.insertNode(parent);
      	this.selectNode(parent);
      }

      if (! range.intersectsNode) {
        range.__proto__.intersectsNode = function(targetNode, currentNode) {
          if (! currentNode) currentNode = this.startContainer;
          if (currentNode == targetNode) return true;
          if (currentNode == this.endContainer) return false;
        
          for (var i = 0; currentNode.hasChildNodes() && currentNode.childNodes[i] && i < 100; i++) {
            var retval = this.intersectsNode(targetNode, currentNode.childNodes[i]);
            if (retval == true || retval == false) return retval;
          }
        
          var nextNode = currentNode.nextSibling;
          while (!nextNode && currentNode.parentNode && currentNode.parentNode != this.commonAncestorContainer) {
            nextNode = currentNode.parentNode.nextSibling;
            currentNode = currentNode.parentNode;
          }
          if (nextNode) return this.intersectsNode(targetNode, nextNode);
          return false;
        }
      }
    } catch (e) {}
  } else if ( jQuery.browser.mozilla && !range.intersectsNode && range.compareBoundaryPoints) {
    /*
     * Patches Firefox3 missing Range#intersectsNode implementation
     */
    range.__proto__.intersectsNode = function(node) {
      var nodeRange = node.ownerDocument.createRange();
      try {
        nodeRange.selectNode(node);
      } catch (e) {
        nodeRange.selectNodeContents(node);
      }
      return this.compareBoundaryPoints(Range.END_TO_START || 3, nodeRange) == -1 &&
      this.compareBoundaryPoints(Range.START_TO_END || 1, nodeRange) == 1;
    }
  }

  /**
   * Hilite function object
   * will use if need to wrap an object to Hilite object (jQuery idea)
   */
  shcp.Hilite = function () {}; 
  (function(Hilite) {
    jQuery.extend( Hilite, {
      /**
       * select all simple (single chunk) highlight element is the current document
       * and convert it to mutiple chunk highlight element
       * @purpose use only one kind of object to handle highlight elements
       *
       * @name convertSimpleHiliteElements
       * @type an jQuery object of all selected elements
       */
      convertSimpleHiliteElements: function () {
        // select all simple (single chunk) highlight elements
        var simpleHiliteElements = jQuery(".k_highlight").filter( function ( index ){
          return jQuery(this).attr("id").indexOf("chunk") == -1;
        });
    
        // convert them to new highlight elements by
        // (1) copy id to class
        simpleHiliteElements.each( function ( index ) {
          var elem = jQuery( this );
          elem.addClass( elem.attr("id") );
        });
    
        // (2) change add _chunk0 to current id
        simpleHiliteElements.attr("id", function ( index ) { 
          return jQuery(this).attr("id") + "_chunk0"; 
        });
    
        Hilite.log( simpleHiliteElements.length + " simple elements converted.")
        return simpleHiliteElements;
      },
  
      log: function( str ) {
        shcp.debug("[Hilite] " + str);
      },
  
      /** 
       * create values for
       *  - selectedColor
       *  - markedColor
       *  - backupColor
       * change all elements whose background-colors 
       * are equal to selectedColor to backupColor
       */
      initColors: function () {
        if ( Hilite.selectedColor ) return;
  
        // [warning] do not change color strings (add space, zero .. )
        if ( jQuery.browser.msie ) {
          Hilite.selectedColor  = "rgb(251, 244, 137)";
          Hilite.markedColor    = "rgb(251, 244, 136)";
          Hilite.backupColor    = "rgb(251, 244, 138)"; 
        } else {
          Hilite.selectedColor  = "rgb(251, 244, 137)";
          Hilite.markedColor    = "rgb(251, 244, 136)";
          Hilite.backupColor    = "rgb(251, 244, 138)"; 
        }
  
        // change all elements whose background-colors are equal to selectedColor to backupColor
        Hilite.getSelectedElements().css("background-color", Hilite.backupColor );
      },
  
      getSelectedElements: function ( ) {
        Hilite.selector = Hilite.selector || "*";
        return Util.selectByBackgroundColor( Hilite.selector, Hilite.selectedColor );
      },
  
      template: {
        title     : "{name}@{ip} {clock}",
        anchor    : "<a style='position: relative; top: -2em;' name='shcp{count}'></a>",
        classNames: "k_highlight_text{count} k_highlight k_commentter k_coupling{count}",
        identifier: "k_highlight_text{count}_chunk{index}"
      },
  
      makeMarkedChunks: function( count ) {
        var selectedElements = Hilite.getSelectedElements();
        
        if ( selectedElements.length == 0 ) {
          Hilite.log("hilite chunks not found.");
          return false;
        }
        Hilite.log( "Total hilite chunks = " + selectedElements.length );
    
        // create data to supplant into templates
        var param = { count: count };
        jQuery.extend( param, shcp.user );
    
        // insert an anchor before the first element
        var anchor = Util.supplant( Hilite.template.anchor, param );
        jQuery( selectedElements[0] ).before( anchor );
        Hilite.log( Util.supplant("'{anchor}' inserted.", { anchor : anchor }) );
      
        // add title and class to all selected elements
        var title       = Util.supplant( Hilite.template.title,       param );
        var classNames  = Util.supplant( Hilite.template.classNames,  param );
        selectedElements.attr("title", title).addClass( classNames );
    
        // add a unique id to each selected elements
        selectedElements.each( function ( index ) {
          jQuery.extend( param, { index: index } );
          this.id = Util.supplant( Hilite.template.identifier, param );
        });
    
       // change selected chunks' background-colors to markedColor
        selectedElements.css("background-color", Hilite.markedColor );

        Hilite.log("marked chunks created");
        return true;
      },
  
      // getToolbarAnchorText: function () {
      // // return anchor text to display on toolbar, cut if longer than MAX_LENGTH
      //   // var MAX_LENGTH = 50;
      //   //     var text = Hilite.selectedText;
      //   //     if ( text.length <= MAX_LENGTH + 4 ) return text;
      //   //     else return text.substring(0, MAX_LENGTH ) + "... ";
      //   return Hilite.selectedText;
      // },
      // 
      completeHighlighting: function () {
        if ( ! Hilite.selectedTextIsValid() ) {
          Hilite.log("seleted text is invalid (could be empty)");
          return false;
        }

      	if (! Hilite.makeWrappers() ) return;

        Hilite.makeMarkedChunks( shcp.k_count );
        // add highlight and anchor identifiers to session (for undo function)
        shcp.undo_stack.push( 'k_coupling' + shcp.k_count );

        // add anchor link to the toolbar
        // shcp.add_current_comment( Hilite.getToolbarAnchorText(), shcp.user.name, true, shcp.k_count);
        Hilite.log("done");
        return true;
      },
  
      // isEnable: function () {
      //   return shcp.k_current_mode == kMode.Highlight;
      // },
      // 
      selectedTextIsValid: function () {
        if (typeof Hilite.selectedText == "undefined") return false;
        return Util.isNotBlank( Hilite.selectedText );
      },
  
      // limitHighlighableElements: function () {
      //   // not sure the doc is put new elements (new sticky note .. ) or not, so do this every time start highliting
      //   jQuery("#k_toolbar").add("img").add(".k_sticky0").add("k_highlight")
      //     .bind( "mousedown", function ( event ) {
      //       if ( Hilite.isEnable() ) {
      //         Hilite.log( "can't highlight this element" );
      //         // cancel event bubbling so hilite mousedown handler will not get the event
      //         event.stopPropagation(); 
      //       }
      //   });
      // },

      isValidHtml: function ( html ) {
        return (html.indexOf("k_highlight") == -1);
      },

      isValidRange: function ( range ) {
      // todo: need to expand range to cover add begin and end node before verify
        if ( range.htmlText ) // IE
          return Hilite.isValidHtml( range.htmlText );
        // W3C
        var rangeDescenders = Util.descenders( range.cloneContents() );
        return ( rangeDescenders.filter(".k_highlight").length == 0 );
      },

      createNewWrapper: function () {
        var element = document.createElement('span');
        element.className = "hilite_chunk_wrapper";
        element.style.backgroundColor = Hilite.selectedColor;
        return element;
      },
  
      wrapTextNode: function (range, ele ) {
        var subRange = document.createRange ? document.createRange() : document.selection.createRange();
    
        shcp.debug("wrapIntersectedElement: " + ele.nodeName + " > surroundContents(" + ele.data.replace(/\n/, ' ') + ")");
    
        // select correct sub-range
        if (ele == range.startContainer || ele == range.endContainer) {
          subRange.setStart(ele, (ele == range.startContainer) ? range.startOffset : 0);
          subRange.setEnd(ele, (ele == range.endContainer) ? range.endOffset : ele.length);
        } 
        else {
          if (!!ele.parentNode.className.match(/hilite_chunk_wrapper/)) {
            return; // avoid double-wrapping
          } else {
            subRange.selectNode(ele);
          }
        }
        // then wrap sub-range
        subRange.surroundContents( Hilite.createNewWrapper() );
        subRange.detach();
      },
  
      unwrapNodes: function(jarray) {
        try {
          // remove the spans
          jarray.each(function(index, ele) {
            var innerRange = document.createRange ? document.createRange() : document.selection.createRange();
            var outerRange = document.createRange ? document.createRange() : document.selection.createRange();
            outerRange.selectNode(ele);
            innerRange.selectNodeContents(ele);
            innerContent = innerRange.extractContents();
            outerContent = outerRange.extractContents();
            outerRange.insertNode(innerContent);    
          });
        } catch (e) {
          // uncolor the spans
          jarray.removeClass("k_highlight")
            .attr( {title: "", id:""} )
            .css("background-color", "");
        }
      },
  
      isValidTextNode: function ( range, ele ) {
        // check if ele is empty or not
        var isNotEmpty = ele.data && ele.data.replace(/ /g, '') != '';
        
        // check if ele is in the range or not
        var isInRange = range.intersectsNode && range.intersectsNode(ele);
        if ( ! isInRange ) {
          shcp.debug("wrapIntersectedElement: ! isInRange");
          shcp.debug(ele.data);
        } else if (! isNotEmpty ) {
          shcp.debug("wrapIntersectedElement: ! isNotEmpty");
          shcp.debug(ele.data);      
        }
        return isNotEmpty && isInRange;
      },
  
      logInforWhileRangeTraveling: function (ele, i) {
        shcp.debug("wrapIntersectedElement: " + ele.nodeName + " > " + (i+1) + 
                    "/" + ele.childNodes.length + ": " + 
                    ele.childNodes[i].nodeName + 
        '');
      },

      wrapIntersectedElement: function (ele, range) {
        // if has children                  
        if (ele.childNodes && ele.childNodes.length > 0) {
          shcp.debug("wrapIntersectedElement: has " + ele.childNodes.length + " children ", ele, ele.childNodes);
          // then do range traveling
          for (var i = (ele.childNodes.length-1); i >= 0 && ele.childNodes[i]; i--) {
            Hilite.logInforWhileRangeTraveling( ele, i );
            Hilite.wrapIntersectedElement( ele.childNodes[i], range );
          }
        } else if ( Hilite.isValidTextNode( range, ele ) ) {
          shcp.debug("wrapIntersectedElement: has no children ", ele);
          Hilite.wrapTextNode( range, ele );
        }
      },

      makeWrappers: function () {
        var range = Util.getSelectedRange();
    
        if ( ! Hilite.isValidRange( range ) ) {
          Hilite.log("can't not overlap existing highlights.");
          return false;
        }
    
        if ( range.execCommand ) { 
          // IE, use execCommand will create <font> wrappers
          Hilite.selector = "font";
          range.execCommand( "BackColor", "false", Hilite.selectedColor );
        }   
        else {// W3C! range is a Range object
          Hilite.wrapIntersectedElement(range.commonAncestorContainer, range);
          Hilite.selector = ".hilite_chunk_wrapper";
        }
        return true;
      }
    });
    Hilite.convertSimpleHiliteElements();
    Hilite.initColors();
  })(shcp.Hilite);
})(shcp);



/* include: compatible.js */
shcp.remove_stickynote = function(ele) {
  jQuery(ele).parents('div.k_shadow').each(function(index, element) {
    var match = null;
    if (element.id && (match = element.id.match(/\D(\d+)$/))) {
      shcp.toolbar.remove(match[1]);
      // TODO: existing note?
    }
  });
}

shcp.click_areas = {
  mousedown: function() {
    // 
  }
}

function minmax_panel(img, ele, force_hide) {
  function toggleElemChildren( element, selector, force_hide ) {
    var retvalue = null;
    jQuery(selector, element).each( function ( index ) {
      retvalue = this.style.display = ( this.style.display == 'none' || force_hide) ? 'block' : 'none';
      // shcp.iframe_shim.resizeShim(this.parentNode);
      // shcp.iframe_shim.resizeShim(this.parentNode.parentNode);
    });
    return retvalue;
  }

  function toggleImage( img ) {
    if (!img || !img.src) return;

    var i = (img.src.indexOf('_min') == -1) ? 0 : 1;
    var srcArr = ["_max", "_min"];
    var titleArr = ["Max", "Min"];

    img.src   = img.src.replace( srcArr[i], srcArr[1-i] );
    img.title = img.title.replace( titleArr[i], titleArr[1-i] );
  }

  toggleImage( img );
  toggleElemChildren( ele, ".k_panel_bottom", force_hide );
  var retvalue = toggleElemChildren( ele, ".k_panel_main"  , force_hide );
  
  jQuery(ele).height('');
  jQuery("#" + ele.id + "> div").height('');
  if (jQuery("#" + ele.id + " .ui-resizable-handle")[0]) {
    jQuery("#" + ele.id).resizable((retvalue == 'block') ? 'enable' : 'disable');
  }
}



/* include: templates.js */
SharedCopy.config.html.colorpicker_stub = '<div class=\"k_color k_unchanged k_coupling{k_count}\" id=\"k_color{k_count}\" \n     style=\"padding: 5px ;background: #FFF89F; border: 1px solid #F3E307; top:{y}px; left:{x}px; position:absolute\">\n  <div class=\"k_hex_instructions\" style=\"font-weight: bold; color: #B5351B; float: left; padding-right: 0.5em; \">\n    Color \n  </div>\n  <div class=\"k_pick\" \n       style=\"border: 1px solid grey; float: left; height:14px; width:14px;background-color: #{color};\">\n  </div>\n  <br style=\"clear: left; \"/>\n  #<div class=\"k_hex\" \n       style=\"display: inline; \">{color}</div>\n</div>';
SharedCopy.config.html.comment_li = '<li class=\"{li_class}\" id=\"{li_id}\">\n  <a href=\"{user_url}\" class=\"user\">{user_name}\n    <span class=\"ago k_make_blank\" title=\"{datetime}\">{datetime}</span>\n  </a>\n  <span class=\"content\">\n    <span class=\"photo\">\n      <img alt=\"{user_name}\" class=\"user_photo\" \n           title=\"{user_name}\" src=\"{user_picture_url}\">\n    </span>\n    <span class=\"text\">\n    </span>\n  </span>\n</li>\n';
SharedCopy.config.html.comment_li_body = '<{tag_name} class=\"{content_css}\">\n  <a href=\"{body_url}\" class=\"{link_css}\">\n    {body}\n    <sup>link &raquo;</sup>\n  </a>\n</{tag_name}>\n';
SharedCopy.config.html.comments_rss = '<a id=\"k_comments_rss\" class=\"rss\"\n   title=\"Be notified of comments on this copy via RSS\"\n   href=\"{rss_url}\"><img \n   width=\"14\" height=\"14\" border=\"0\" style=\"vertical-align: middle;\" \n   src=\"{url_base}/images/icons/rss.png\"/>\n</a>';
SharedCopy.config.html.comments_showhide = '<div id=\'k_comments_showhide\' class=\"section_tohide\">\n	<div class=\"commentwrap\"><!-- BEGIN class commentwrap-->\n	  <span id=\"k_comments_label_row\">\n		<a id=\'k_comments_label\' href=\"#\" onclick=\"return false;\">no comments</a>\n    </span>\n	</div><!-- END class commentwrap-->\n</div>\n<form>\n  <ol id=\"k_toolbar_list\">\n  </ol>\n</form>\n';
SharedCopy.config.html.sticky_note = '<div style=\"top: {top}px; left: {left}px; z-index: {current_zindex}; width: {width}px; position: absolute; \"\nclass=\"k_shadow k_hover k_draggable k_coupling{k_count}\" id=\"div{k_count}\">\n<div class=\"k_sticky\" >\n  <a name=\"shcp{k_count}\"></a>\n  <p id=\"drag_div{k_count}\" class=\"k_panel_top\" style=\"cursor: move; \" >\n    {title_text}\n    <span style=\"float: right;\">\n      <img src=\"{url_basepath}/style/images/resize_min.gif?V2\"  \n      onclick=\"minmax_panel(this, document.getElementById(\'div{k_count}\'), false); shcp.click_areas.mousedown(shcp.on_k_mousedown); \" \n      style=\"cursor: auto; \" \n      class=\"minimize_button\"\n      title=\"Minimize this comment\" />\n      {sticky_note_close}\n    </span>\n    <br style=\"clear: both; \" />\n    {subtitle_text}\n  </p>\n  <div id=\"textdiv{k_count}\" class=\"k_panel_main\" style=\"\">\n    <textarea class=\"k_main_object\" tabindex=\"1\" id=\"text{k_count}\"></textarea>\n    <br />\n    <input class=\"stickynote_ok\" type=\"button\" onclick=\"{on_ok}\" tabindex=\"1\" value=\"Ok\" id=\"obutton_text{k_count}\" />\n    <input class=\"stickynote_cancel\" type=\"button\" onclick=\"{on_cancel}\" \n    tabindex=\"1\" value=\"Cancel\" title=\"shortcut key: ESC\" id=\"cbutton_text{k_count}\" />\n  </div>\n  <div class=\"k_panel_bottom\" style=\"\"></div>\n</div>\n</div>\n';
SharedCopy.config.html.sticky_note_close = '<img \n  src=\"{url_basepath}/style/images/resize_close.gif?V2\"\n  onclick=\"return shcp.remove_stickynote(this);\"\n  class=\"k_make_remove close_button\"\n  style=\"cursor: auto; \" \n  title=\"Delete this comment\" />\n';
SharedCopy.config.html.toolbar = '<div id=\'k_toolbar\' class=\'k_shadow\' style=\'display: none; \'>\n  <p class=\'k_panel_top\'>\n    <a href=\'{url_base}\' title=\'Powered by SharedCopy\' alt=\'Web annotations by SharedCopy\'>Web annotations</a>\n    <img src=\'{url_basepath}/style/images/resize_min_dark.gif?V1\' title=\'Minimize this window, and all comments\' \n         onclick=\"minmax_panel(this, document.getElementById(\'k_toolbar\'), false); shcp.click_areas.mousedown(shcp.on_k_mousedown); \" />\n    <img src=\'{url_basepath}/style/images/resize_close_dark.gif?V1\' title=\'Remove this toolbar\' \n         class=\"k_make_remove\"\n         onclick=\"if (confirm(\'Remove this toolbar?\')) { shcp.remove_toolbar(); }\" />\n  </p> \n  <div id=\'k_toolbar_inner\' class=\'k_panel_main\' >\n    <div id=\'k_toolbar_buttons\' class=\'k_make_blank k_clearfix\' style=\'inline\' ></div>\n  </div>\n</div>\n';
SharedCopy.config.html.toolbar_button = '<button type=\'button\' id=\'{id}\' class=\'{css_class}\' title=\'{title}\' style=\'{style}\'>\n  <span>{label}</span>\n</button>';
SharedCopy.config.html.toolbar_footer = '<div class=\"hint\" id=\"k_toolbar_footer\">\n  <a title=\"link to the original copy\" href=\"{original_url}\">original page</a>\n  |\n  <a target=\"_blank\" href=\"{help_url}\" title=\"report problems\">help</a>\n</div>';



/* include: exec.js */
if (window.SharedCopy.before_load) window.SharedCopy.before_load();
shcp.on_ready(document, function(doc) {
  // cleanse base
  shcp.page.reset(doc);
  
  // load FORM
  shcp.toolbar.render(doc);
  
  // apply FUNCTION
  shcp.page.register_events(doc);
  
  // perform CUSTOM
  if (SharedCopy.on_document_loaded) SharedCopy.on_document_loaded();

  // cleanup & action!
  shcp.toolbar.on_ready(doc);

  // remove "Loading..." message from bookmarklet
  jQuery('#k_deleteme').remove();

  if (window.SharedCopy.after_load) window.SharedCopy.after_load(doc);
});




