web/wp-includes/js/imgareaselect/jquery.imgareaselect.dev.js
changeset 194 32102edaa81b
parent 136 bde1974c263b
equal deleted inserted replaced
193:2f6f6f7551ca 194:32102edaa81b
     1 /*
     1 /*
     2  * imgAreaSelect jQuery plugin
     2  * imgAreaSelect jQuery plugin
     3  * version 0.9.1
     3  * version 0.9.9
     4  *
     4  *
     5  * Copyright (c) 2008-2009 Michal Wojciechowski (odyniec.net)
     5  * Copyright (c) 2008-2011 Michal Wojciechowski (odyniec.net)
     6  *
     6  *
     7  * Dual licensed under the MIT (MIT-LICENSE.txt)
     7  * Dual licensed under the MIT (MIT-LICENSE.txt)
     8  * and GPL (GPL-LICENSE.txt) licenses.
     8  * and GPL (GPL-LICENSE.txt) licenses.
     9  *
     9  *
    10  * http://odyniec.net/projects/imgareaselect/
    10  * http://odyniec.net/projects/imgareaselect/
    11  *
    11  *
    12  */
    12  */
    13 
    13 
    14 (function($) {
    14 (function($) {
    15 
    15 
       
    16 /*
       
    17  * Math functions will be used extensively, so it's convenient to make a few
       
    18  * shortcuts
       
    19  */
    16 var abs = Math.abs,
    20 var abs = Math.abs,
    17     max = Math.max,
    21     max = Math.max,
    18     min = Math.min,
    22     min = Math.min,
    19     round = Math.round;
    23     round = Math.round;
    20 
    24 
       
    25 /**
       
    26  * Create a new HTML div element
       
    27  *
       
    28  * @return A jQuery object representing the new element
       
    29  */
    21 function div() {
    30 function div() {
    22     return $('<div/>');
    31     return $('<div/>');
    23 }
    32 }
    24 
    33 
       
    34 /**
       
    35  * imgAreaSelect initialization
       
    36  *
       
    37  * @param img
       
    38  *            A HTML image element to attach the plugin to
       
    39  * @param options
       
    40  *            An options object
       
    41  */
    25 $.imgAreaSelect = function (img, options) {
    42 $.imgAreaSelect = function (img, options) {
    26     var
    43     var
    27 
    44         /* jQuery object representing the image */
    28         $img = $(img),
    45         $img = $(img),
    29 
    46 
       
    47         /* Has the image finished loading? */
    30         imgLoaded,
    48         imgLoaded,
    31 
    49 
       
    50         /* Plugin elements */
       
    51 
       
    52         /* Container box */
    32         $box = div(),
    53         $box = div(),
       
    54         /* Selection area */
    33         $area = div(),
    55         $area = div(),
       
    56         /* Border (four divs) */
    34         $border = div().add(div()).add(div()).add(div()),
    57         $border = div().add(div()).add(div()).add(div()),
       
    58         /* Outer area (four divs) */
    35         $outer = div().add(div()).add(div()).add(div()),
    59         $outer = div().add(div()).add(div()).add(div()),
       
    60         /* Handles (empty by default, initialized in setOptions()) */
    36         $handles = $([]),
    61         $handles = $([]),
    37 
    62 
       
    63         /*
       
    64          * Additional element to work around a cursor problem in Opera
       
    65          * (explained later)
       
    66          */
    38         $areaOpera,
    67         $areaOpera,
    39 
    68 
       
    69         /* Image position (relative to viewport) */
    40         left, top,
    70         left, top,
    41 
    71 
    42         imgOfs,
    72         /* Image offset (as returned by .offset()) */
    43 
    73         imgOfs = { left: 0, top: 0 },
       
    74 
       
    75         /* Image dimensions (as returned by .width() and .height()) */
    44         imgWidth, imgHeight,
    76         imgWidth, imgHeight,
    45 
    77 
       
    78         /*
       
    79          * jQuery object representing the parent element that the plugin
       
    80          * elements are appended to
       
    81          */
    46         $parent,
    82         $parent,
    47 
    83 
    48         parOfs,
    84         /* Parent element offset (as returned by .offset()) */
    49 
    85         parOfs = { left: 0, top: 0 },
       
    86 
       
    87         /* Base z-index for plugin elements */
    50         zIndex = 0,
    88         zIndex = 0,
    51 
    89 
       
    90         /* Plugin elements position */
    52         position = 'absolute',
    91         position = 'absolute',
    53 
    92 
       
    93         /* X/Y coordinates of the starting point for move/resize operations */
    54         startX, startY,
    94         startX, startY,
    55 
    95 
       
    96         /* Horizontal and vertical scaling factors */
    56         scaleX, scaleY,
    97         scaleX, scaleY,
    57 
    98 
    58         resizeMargin = 10,
    99         /* Current resize mode ("nw", "se", etc.) */
    59 
       
    60         resize,
   100         resize,
    61 
   101 
       
   102         /* Selection area constraints */
       
   103         minWidth, minHeight, maxWidth, maxHeight,
       
   104 
       
   105         /* Aspect ratio to maintain (floating point number) */
    62         aspectRatio,
   106         aspectRatio,
    63 
   107 
       
   108         /* Are the plugin elements currently displayed? */
    64         shown,
   109         shown,
    65 
   110 
       
   111         /* Current selection (relative to parent element) */
    66         x1, y1, x2, y2,
   112         x1, y1, x2, y2,
    67 
   113 
       
   114         /* Current selection (relative to scaled image) */
    68         selection = { x1: 0, y1: 0, x2: 0, y2: 0, width: 0, height: 0 },
   115         selection = { x1: 0, y1: 0, x2: 0, y2: 0, width: 0, height: 0 },
    69 
   116 
       
   117         /* Document element */
       
   118         docElem = document.documentElement,
       
   119 
       
   120         /* Various helper variables used throughout the code */
    70         $p, d, i, o, w, h, adjusted;
   121         $p, d, i, o, w, h, adjusted;
    71 
   122 
       
   123     /*
       
   124      * Translate selection coordinates (relative to scaled image) to viewport
       
   125      * coordinates (relative to parent element)
       
   126      */
       
   127 
       
   128     /**
       
   129      * Translate selection X to viewport X
       
   130      *
       
   131      * @param x
       
   132      *            Selection X
       
   133      * @return Viewport X
       
   134      */
    72     function viewX(x) {
   135     function viewX(x) {
    73         return x + imgOfs.left - parOfs.left;
   136         return x + imgOfs.left - parOfs.left;
    74     }
   137     }
    75 
   138 
       
   139     /**
       
   140      * Translate selection Y to viewport Y
       
   141      *
       
   142      * @param y
       
   143      *            Selection Y
       
   144      * @return Viewport Y
       
   145      */
    76     function viewY(y) {
   146     function viewY(y) {
    77         return y + imgOfs.top - parOfs.top;
   147         return y + imgOfs.top - parOfs.top;
    78     }
   148     }
    79 
   149 
       
   150     /*
       
   151      * Translate viewport coordinates to selection coordinates
       
   152      */
       
   153 
       
   154     /**
       
   155      * Translate viewport X to selection X
       
   156      *
       
   157      * @param x
       
   158      *            Viewport X
       
   159      * @return Selection X
       
   160      */
    80     function selX(x) {
   161     function selX(x) {
    81         return x - imgOfs.left + parOfs.left;
   162         return x - imgOfs.left + parOfs.left;
    82     }
   163     }
    83 
   164 
       
   165     /**
       
   166      * Translate viewport Y to selection Y
       
   167      *
       
   168      * @param y
       
   169      *            Viewport Y
       
   170      * @return Selection Y
       
   171      */
    84     function selY(y) {
   172     function selY(y) {
    85         return y - imgOfs.top + parOfs.top;
   173         return y - imgOfs.top + parOfs.top;
    86     }
   174     }
    87 
   175 
       
   176     /*
       
   177      * Translate event coordinates (relative to document) to viewport
       
   178      * coordinates
       
   179      */
       
   180 
       
   181     /**
       
   182      * Get event X and translate it to viewport X
       
   183      *
       
   184      * @param event
       
   185      *            The event object
       
   186      * @return Viewport X
       
   187      */
    88     function evX(event) {
   188     function evX(event) {
    89         return event.pageX - parOfs.left;
   189         return event.pageX - parOfs.left;
    90     }
   190     }
    91 
   191 
       
   192     /**
       
   193      * Get event Y and translate it to viewport Y
       
   194      *
       
   195      * @param event
       
   196      *            The event object
       
   197      * @return Viewport Y
       
   198      */
    92     function evY(event) {
   199     function evY(event) {
    93         return event.pageY - parOfs.top;
   200         return event.pageY - parOfs.top;
    94     }
   201     }
    95 
   202 
       
   203     /**
       
   204      * Get the current selection
       
   205      *
       
   206      * @param noScale
       
   207      *            If set to <code>true</code>, scaling is not applied to the
       
   208      *            returned selection
       
   209      * @return Selection object
       
   210      */
    96     function getSelection(noScale) {
   211     function getSelection(noScale) {
    97         var sx = noScale || scaleX, sy = noScale || scaleY;
   212         var sx = noScale || scaleX, sy = noScale || scaleY;
    98 
   213 
    99         return { x1: round(selection.x1 * sx),
   214         return { x1: round(selection.x1 * sx),
   100             y1: round(selection.y1 * sy),
   215             y1: round(selection.y1 * sy),
   102             y2: round(selection.y2 * sy),
   217             y2: round(selection.y2 * sy),
   103             width: round(selection.x2 * sx) - round(selection.x1 * sx),
   218             width: round(selection.x2 * sx) - round(selection.x1 * sx),
   104             height: round(selection.y2 * sy) - round(selection.y1 * sy) };
   219             height: round(selection.y2 * sy) - round(selection.y1 * sy) };
   105     }
   220     }
   106 
   221 
       
   222     /**
       
   223      * Set the current selection
       
   224      *
       
   225      * @param x1
       
   226      *            X coordinate of the upper left corner of the selection area
       
   227      * @param y1
       
   228      *            Y coordinate of the upper left corner of the selection area
       
   229      * @param x2
       
   230      *            X coordinate of the lower right corner of the selection area
       
   231      * @param y2
       
   232      *            Y coordinate of the lower right corner of the selection area
       
   233      * @param noScale
       
   234      *            If set to <code>true</code>, scaling is not applied to the
       
   235      *            new selection
       
   236      */
   107     function setSelection(x1, y1, x2, y2, noScale) {
   237     function setSelection(x1, y1, x2, y2, noScale) {
   108         var sx = noScale || scaleX, sy = noScale || scaleY;
   238         var sx = noScale || scaleX, sy = noScale || scaleY;
   109 
   239 
   110         selection = {
   240         selection = {
   111             x1: round(x1 / sx),
   241             x1: round(x1 / sx || 0),
   112             y1: round(y1 / sy),
   242             y1: round(y1 / sy || 0),
   113             x2: round(x2 / sx),
   243             x2: round(x2 / sx || 0),
   114             y2: round(y2 / sy)
   244             y2: round(y2 / sy || 0)
   115         };
   245         };
   116 
   246 
   117         selection.width = (x2 = viewX(selection.x2)) - (x1 = viewX(selection.x1));
   247         selection.width = selection.x2 - selection.x1;
   118         selection.height = (y2 = viewX(selection.y2)) - (y1 = viewX(selection.y1));
   248         selection.height = selection.y2 - selection.y1;
   119     }
   249     }
   120 
   250 
       
   251     /**
       
   252      * Recalculate image and parent offsets
       
   253      */
   121     function adjust() {
   254     function adjust() {
       
   255         /*
       
   256          * Do not adjust if image width is not a positive number. This might
       
   257          * happen when imgAreaSelect is put on a parent element which is then
       
   258          * hidden.
       
   259          */
   122         if (!$img.width())
   260         if (!$img.width())
   123             return;
   261             return;
   124 
   262 
       
   263         /*
       
   264          * Get image offset. The .offset() method returns float values, so they
       
   265          * need to be rounded.
       
   266          */
   125         imgOfs = { left: round($img.offset().left), top: round($img.offset().top) };
   267         imgOfs = { left: round($img.offset().left), top: round($img.offset().top) };
   126 
   268 
   127         imgWidth = $img.width();
   269         /* Get image dimensions */
   128         imgHeight = $img.height();
   270         imgWidth = $img.innerWidth();
   129 
   271         imgHeight = $img.innerHeight();
   130         if ($().jquery == '1.3.2' && $.browser.safari && position == 'fixed') {
   272 
   131             imgOfs.top += max(document.documentElement.scrollTop, $('body').scrollTop());
   273         imgOfs.top += ($img.outerHeight() - imgHeight) >> 1;
   132 
   274         imgOfs.left += ($img.outerWidth() - imgWidth) >> 1;
   133             imgOfs.left += max(document.documentElement.scrollLeft, $('body').scrollLeft());
   275 
   134         }
   276         /* Set minimum and maximum selection area dimensions */
   135 
   277         minWidth = round(options.minWidth / scaleX) || 0;
   136         parOfs = $.inArray($parent.css('position'), ['absolute', 'relative']) + 1 ?
   278         minHeight = round(options.minHeight / scaleY) || 0;
       
   279         maxWidth = round(min(options.maxWidth / scaleX || 1<<24, imgWidth));
       
   280         maxHeight = round(min(options.maxHeight / scaleY || 1<<24, imgHeight));
       
   281 
       
   282         /*
       
   283          * Workaround for jQuery 1.3.2 incorrect offset calculation, originally
       
   284          * observed in Safari 3. Firefox 2 is also affected.
       
   285          */
       
   286         if ($().jquery == '1.3.2' && position == 'fixed' &&
       
   287             !docElem['getBoundingClientRect'])
       
   288         {
       
   289             imgOfs.top += max(document.body.scrollTop, docElem.scrollTop);
       
   290             imgOfs.left += max(document.body.scrollLeft, docElem.scrollLeft);
       
   291         }
       
   292 
       
   293         /* Determine parent element offset */
       
   294         parOfs = /absolute|relative/.test($parent.css('position')) ?
   137             { left: round($parent.offset().left) - $parent.scrollLeft(),
   295             { left: round($parent.offset().left) - $parent.scrollLeft(),
   138                 top: round($parent.offset().top) - $parent.scrollTop() } :
   296                 top: round($parent.offset().top) - $parent.scrollTop() } :
   139             position == 'fixed' ?
   297             position == 'fixed' ?
   140                 { left: $(document).scrollLeft(), top: $(document).scrollTop() } :
   298                 { left: $(document).scrollLeft(), top: $(document).scrollTop() } :
   141                 { left: 0, top: 0 };
   299                 { left: 0, top: 0 };
   142 
   300 
   143         left = viewX(0);
   301         left = viewX(0);
   144         top = viewY(0);
   302         top = viewY(0);
   145     }
   303 
   146 
   304         /*
       
   305          * Check if selection area is within image boundaries, adjust if
       
   306          * necessary
       
   307          */
       
   308         if (selection.x2 > imgWidth || selection.y2 > imgHeight)
       
   309             doResize();
       
   310     }
       
   311 
       
   312     /**
       
   313      * Update plugin elements
       
   314      *
       
   315      * @param resetKeyPress
       
   316      *            If set to <code>false</code>, this instance's keypress
       
   317      *            event handler is not activated
       
   318      */
   147     function update(resetKeyPress) {
   319     function update(resetKeyPress) {
       
   320         /* If plugin elements are hidden, do nothing */
   148         if (!shown) return;
   321         if (!shown) return;
   149 
   322 
       
   323         /*
       
   324          * Set the position and size of the container box and the selection area
       
   325          * inside it
       
   326          */
   150         $box.css({ left: viewX(selection.x1), top: viewY(selection.y1) })
   327         $box.css({ left: viewX(selection.x1), top: viewY(selection.y1) })
   151             .add($area).width(w = selection.width).height(h = selection.height);
   328             .add($area).width(w = selection.width).height(h = selection.height);
   152 
   329 
       
   330         /*
       
   331          * Reset the position of selection area, borders, and handles (IE6/IE7
       
   332          * position them incorrectly if we don't do this)
       
   333          */
   153         $area.add($border).add($handles).css({ left: 0, top: 0 });
   334         $area.add($border).add($handles).css({ left: 0, top: 0 });
   154 
   335 
       
   336         /* Set border dimensions */
   155         $border
   337         $border
   156             .width(max(w - $border.outerWidth() + $border.innerWidth(), 0))
   338             .width(max(w - $border.outerWidth() + $border.innerWidth(), 0))
   157             .height(max(h - $border.outerHeight() + $border.innerHeight(), 0));
   339             .height(max(h - $border.outerHeight() + $border.innerHeight(), 0));
   158 
   340 
       
   341         /* Arrange the outer area elements */
   159         $($outer[0]).css({ left: left, top: top,
   342         $($outer[0]).css({ left: left, top: top,
   160             width: selection.x1, height: imgHeight });
   343             width: selection.x1, height: imgHeight });
   161         $($outer[1]).css({ left: left + selection.x1, top: top,
   344         $($outer[1]).css({ left: left + selection.x1, top: top,
   162             width: w, height: selection.y1 });
   345             width: w, height: selection.y1 });
   163         $($outer[2]).css({ left: left + selection.x2, top: top,
   346         $($outer[2]).css({ left: left + selection.x2, top: top,
   166             width: w, height: imgHeight - selection.y2 });
   349             width: w, height: imgHeight - selection.y2 });
   167 
   350 
   168         w -= $handles.outerWidth();
   351         w -= $handles.outerWidth();
   169         h -= $handles.outerHeight();
   352         h -= $handles.outerHeight();
   170 
   353 
       
   354         /* Arrange handles */
   171         switch ($handles.length) {
   355         switch ($handles.length) {
   172         case 8:
   356         case 8:
   173             $($handles[4]).css({ left: w / 2 });
   357             $($handles[4]).css({ left: w >> 1 });
   174             $($handles[5]).css({ left: w, top: h / 2 });
   358             $($handles[5]).css({ left: w, top: h >> 1 });
   175             $($handles[6]).css({ left: w / 2, top: h });
   359             $($handles[6]).css({ left: w >> 1, top: h });
   176             $($handles[7]).css({ top: h / 2 });
   360             $($handles[7]).css({ top: h >> 1 });
   177         case 4:
   361         case 4:
   178             $handles.slice(1,3).css({ left: w });
   362             $handles.slice(1,3).css({ left: w });
   179             $handles.slice(2,4).css({ top: h });
   363             $handles.slice(2,4).css({ top: h });
   180         }
   364         }
   181 
   365 
   182         if (resetKeyPress !== false) {
   366         if (resetKeyPress !== false) {
       
   367             /*
       
   368              * Need to reset the document keypress event handler -- unbind the
       
   369              * current handler
       
   370              */
   183             if ($.imgAreaSelect.keyPress != docKeyPress)
   371             if ($.imgAreaSelect.keyPress != docKeyPress)
   184                 $(document).unbind($.imgAreaSelect.keyPress,
   372                 $(document).unbind($.imgAreaSelect.keyPress,
   185                     $.imgAreaSelect.onKeyPress);
   373                     $.imgAreaSelect.onKeyPress);
   186 
   374 
   187             if (options.keys)
   375             if (options.keys)
       
   376                 /*
       
   377                  * Set the document keypress event handler to this instance's
       
   378                  * docKeyPress() function
       
   379                  */
   188                 $(document)[$.imgAreaSelect.keyPress](
   380                 $(document)[$.imgAreaSelect.keyPress](
   189                     $.imgAreaSelect.onKeyPress = docKeyPress);
   381                     $.imgAreaSelect.onKeyPress = docKeyPress);
   190         }
   382         }
   191 
   383 
       
   384         /*
       
   385          * Internet Explorer displays 1px-wide dashed borders incorrectly by
       
   386          * filling the spaces between dashes with white. Toggling the margin
       
   387          * property between 0 and "auto" fixes this in IE6 and IE7 (IE8 is still
       
   388          * broken). This workaround is not perfect, as it requires setTimeout()
       
   389          * and thus causes the border to flicker a bit, but I haven't found a
       
   390          * better solution.
       
   391          *
       
   392          * Note: This only happens with CSS borders, set with the borderWidth,
       
   393          * borderOpacity, borderColor1, and borderColor2 options (which are now
       
   394          * deprecated). Borders created with GIF background images are fine.
       
   395          */
   192         if ($.browser.msie && $border.outerWidth() - $border.innerWidth() == 2) {
   396         if ($.browser.msie && $border.outerWidth() - $border.innerWidth() == 2) {
   193             $border.css('margin', 0);
   397             $border.css('margin', 0);
   194             setTimeout(function () { $border.css('margin', 'auto'); }, 0);
   398             setTimeout(function () { $border.css('margin', 'auto'); }, 0);
   195         }
   399         }
   196     }
   400     }
   197 
   401 
       
   402     /**
       
   403      * Do the complete update sequence: recalculate offsets, update the
       
   404      * elements, and set the correct values of x1, y1, x2, and y2.
       
   405      *
       
   406      * @param resetKeyPress
       
   407      *            If set to <code>false</code>, this instance's keypress
       
   408      *            event handler is not activated
       
   409      */
   198     function doUpdate(resetKeyPress) {
   410     function doUpdate(resetKeyPress) {
   199         adjust();
   411         adjust();
   200         update(resetKeyPress);
   412         update(resetKeyPress);
   201         x1 = viewX(selection.x1); y1 = viewY(selection.y1);
   413         x1 = viewX(selection.x1); y1 = viewY(selection.y1);
   202         x2 = viewX(selection.x2); y2 = viewY(selection.y2);
   414         x2 = viewX(selection.x2); y2 = viewY(selection.y2);
   203     }
   415     }
   204 
   416 
       
   417     /**
       
   418      * Hide or fade out an element (or multiple elements)
       
   419      *
       
   420      * @param $elem
       
   421      *            A jQuery object containing the element(s) to hide/fade out
       
   422      * @param fn
       
   423      *            Callback function to be called when fadeOut() completes
       
   424      */
   205     function hide($elem, fn) {
   425     function hide($elem, fn) {
   206         options.fadeSpeed ? $elem.fadeOut(options.fadeSpeed, fn) : $elem.hide();
   426         options.fadeSpeed ? $elem.fadeOut(options.fadeSpeed, fn) : $elem.hide();
   207 
   427     }
   208     }
   428 
   209 
   429     /**
       
   430      * Selection area mousemove event handler
       
   431      *
       
   432      * @param event
       
   433      *            The event object
       
   434      */
   210     function areaMouseMove(event) {
   435     function areaMouseMove(event) {
   211         var x = selX(evX(event)) - selection.x1,
   436         var x = selX(evX(event)) - selection.x1,
   212             y = selY(evY(event)) - selection.y1;
   437             y = selY(evY(event)) - selection.y1;
   213 
   438 
   214         if (!adjusted) {
   439         if (!adjusted) {
   216             adjusted = true;
   441             adjusted = true;
   217 
   442 
   218             $box.one('mouseout', function () { adjusted = false; });
   443             $box.one('mouseout', function () { adjusted = false; });
   219         }
   444         }
   220 
   445 
       
   446         /* Clear the resize mode */
   221         resize = '';
   447         resize = '';
   222 
   448 
   223         if (options.resizable) {
   449         if (options.resizable) {
   224             if (y <= resizeMargin)
   450             /*
       
   451              * Check if the mouse pointer is over the resize margin area and set
       
   452              * the resize mode accordingly
       
   453              */
       
   454             if (y <= options.resizeMargin)
   225                 resize = 'n';
   455                 resize = 'n';
   226             else if (y >= selection.height - resizeMargin)
   456             else if (y >= selection.height - options.resizeMargin)
   227                 resize = 's';
   457                 resize = 's';
   228             if (x <= resizeMargin)
   458             if (x <= options.resizeMargin)
   229                 resize += 'w';
   459                 resize += 'w';
   230             else if (x >= selection.width - resizeMargin)
   460             else if (x >= selection.width - options.resizeMargin)
   231                 resize += 'e';
   461                 resize += 'e';
   232         }
   462         }
   233 
   463 
   234         $box.css('cursor', resize ? resize + '-resize' :
   464         $box.css('cursor', resize ? resize + '-resize' :
   235             options.movable ? 'move' : '');
   465             options.movable ? 'move' : '');
   236         if ($areaOpera)
   466         if ($areaOpera)
   237             $areaOpera.toggle();
   467             $areaOpera.toggle();
   238     }
   468     }
   239 
   469 
       
   470     /**
       
   471      * Document mouseup event handler
       
   472      *
       
   473      * @param event
       
   474      *            The event object
       
   475      */
   240     function docMouseUp(event) {
   476     function docMouseUp(event) {
       
   477         /* Set back the default cursor */
   241         $('body').css('cursor', '');
   478         $('body').css('cursor', '');
   242 
   479         /*
       
   480          * If autoHide is enabled, or if the selection has zero width/height,
       
   481          * hide the selection and the outer area
       
   482          */
   243         if (options.autoHide || selection.width * selection.height == 0)
   483         if (options.autoHide || selection.width * selection.height == 0)
   244             hide($box.add($outer), function () { $(this).hide(); });
   484             hide($box.add($outer), function () { $(this).hide(); });
   245 
   485 
   246         options.onSelectEnd(img, getSelection());
       
   247 
       
   248         $(document).unbind('mousemove', selectingMouseMove);
   486         $(document).unbind('mousemove', selectingMouseMove);
   249         $box.mousemove(areaMouseMove);
   487         $box.mousemove(areaMouseMove);
   250     }
   488 
   251 
   489         options.onSelectEnd(img, getSelection());
       
   490     }
       
   491 
       
   492     /**
       
   493      * Selection area mousedown event handler
       
   494      *
       
   495      * @param event
       
   496      *            The event object
       
   497      * @return false
       
   498      */
   252     function areaMouseDown(event) {
   499     function areaMouseDown(event) {
   253         if (event.which != 1) return false;
   500         if (event.which != 1) return false;
   254 
   501 
   255         adjust();
   502         adjust();
   256 
   503 
   257         if (resize) {
   504         if (resize) {
       
   505             /* Resize mode is in effect */
   258             $('body').css('cursor', resize + '-resize');
   506             $('body').css('cursor', resize + '-resize');
   259 
   507 
   260             x1 = viewX(selection[/w/.test(resize) ? 'x2' : 'x1']);
   508             x1 = viewX(selection[/w/.test(resize) ? 'x2' : 'x1']);
   261             y1 = viewY(selection[/n/.test(resize) ? 'y2' : 'y1']);
   509             y1 = viewY(selection[/n/.test(resize) ? 'y2' : 'y1']);
   262 
   510 
   282             $img.mousedown(event);
   530             $img.mousedown(event);
   283 
   531 
   284         return false;
   532         return false;
   285     }
   533     }
   286 
   534 
   287     function aspectRatioXY() {
   535     /**
   288         x2 = max(left, min(left + imgWidth,
   536      * Adjust the x2/y2 coordinates to maintain aspect ratio (if defined)
   289             x1 + abs(y2 - y1) * aspectRatio * (x2 > x1 || -1)));
   537      *
   290 
   538      * @param xFirst
   291         y2 = round(max(top, min(top + imgHeight,
   539      *            If set to <code>true</code>, calculate x2 first. Otherwise,
   292             y1 + abs(x2 - x1) / aspectRatio * (y2 > y1 || -1))));
   540      *            calculate y2 first.
   293         x2 = round(x2);
   541      */
   294     }
   542     function fixAspectRatio(xFirst) {
   295 
   543         if (aspectRatio)
   296     function aspectRatioYX() {
   544             if (xFirst) {
   297         y2 = max(top, min(top + imgHeight,
   545                 x2 = max(left, min(left + imgWidth,
   298             y1 + abs(x2 - x1) / aspectRatio * (y2 > y1 || -1)));
   546                     x1 + abs(y2 - y1) * aspectRatio * (x2 > x1 || -1)));
   299         x2 = round(max(left, min(left + imgWidth,
   547                 y2 = round(max(top, min(top + imgHeight,
   300             x1 + abs(y2 - y1) * aspectRatio * (x2 > x1 || -1))));
   548                     y1 + abs(x2 - x1) / aspectRatio * (y2 > y1 || -1))));
   301         y2 = round(y2);
   549                 x2 = round(x2);
   302     }
   550             }
   303 
   551             else {
       
   552                 y2 = max(top, min(top + imgHeight,
       
   553                     y1 + abs(x2 - x1) / aspectRatio * (y2 > y1 || -1)));
       
   554                 x2 = round(max(left, min(left + imgWidth,
       
   555                     x1 + abs(y2 - y1) * aspectRatio * (x2 > x1 || -1))));
       
   556                 y2 = round(y2);
       
   557             }
       
   558     }
       
   559 
       
   560     /**
       
   561      * Resize the selection area respecting the minimum/maximum dimensions and
       
   562      * aspect ratio
       
   563      */
   304     function doResize() {
   564     function doResize() {
   305         if (abs(x2 - x1) < options.minWidth) {
   565         /*
   306             x2 = x1 - options.minWidth * (x2 < x1 || -1);
   566          * Make sure the top left corner of the selection area stays within
       
   567          * image boundaries (it might not if the image source was dynamically
       
   568          * changed).
       
   569          */
       
   570         x1 = min(x1, left + imgWidth);
       
   571         y1 = min(y1, top + imgHeight);
       
   572 
       
   573         if (abs(x2 - x1) < minWidth) {
       
   574             /* Selection width is smaller than minWidth */
       
   575             x2 = x1 - minWidth * (x2 < x1 || -1);
   307 
   576 
   308             if (x2 < left)
   577             if (x2 < left)
   309                 x1 = left + options.minWidth;
   578                 x1 = left + minWidth;
   310             else if (x2 > left + imgWidth)
   579             else if (x2 > left + imgWidth)
   311                 x1 = left + imgWidth - options.minWidth;
   580                 x1 = left + imgWidth - minWidth;
   312         }
   581         }
   313 
   582 
   314         if (abs(y2 - y1) < options.minHeight) {
   583         if (abs(y2 - y1) < minHeight) {
   315             y2 = y1 - options.minHeight * (y2 < y1 || -1);
   584             /* Selection height is smaller than minHeight */
       
   585             y2 = y1 - minHeight * (y2 < y1 || -1);
   316 
   586 
   317             if (y2 < top)
   587             if (y2 < top)
   318                 y1 = top + options.minHeight;
   588                 y1 = top + minHeight;
   319             else if (y2 > top + imgHeight)
   589             else if (y2 > top + imgHeight)
   320                 y1 = top + imgHeight - options.minHeight;
   590                 y1 = top + imgHeight - minHeight;
   321         }
   591         }
   322 
   592 
   323         x2 = max(left, min(x2, left + imgWidth));
   593         x2 = max(left, min(x2, left + imgWidth));
   324         y2 = max(top, min(y2, top + imgHeight));
   594         y2 = max(top, min(y2, top + imgHeight));
   325 
   595 
   326         if (aspectRatio)
   596         fixAspectRatio(abs(x2 - x1) < abs(y2 - y1) * aspectRatio);
   327             if (abs(x2 - x1) / aspectRatio > abs(y2 - y1))
   597 
   328                 aspectRatioYX();
   598         if (abs(x2 - x1) > maxWidth) {
   329             else
   599             /* Selection width is greater than maxWidth */
   330                 aspectRatioXY();
   600             x2 = x1 - maxWidth * (x2 < x1 || -1);
   331 
   601             fixAspectRatio();
   332         if (abs(x2 - x1) > options.maxWidth) {
   602         }
   333             x2 = x1 - options.maxWidth * (x2 < x1 || -1);
   603 
   334             if (aspectRatio) aspectRatioYX();
   604         if (abs(y2 - y1) > maxHeight) {
   335         }
   605             /* Selection height is greater than maxHeight */
   336 
   606             y2 = y1 - maxHeight * (y2 < y1 || -1);
   337         if (abs(y2 - y1) > options.maxHeight) {
   607             fixAspectRatio(true);
   338             y2 = y1 - options.maxHeight * (y2 < y1 || -1);
       
   339             if (aspectRatio) aspectRatioXY();
       
   340         }
   608         }
   341 
   609 
   342         selection = { x1: selX(min(x1, x2)), x2: selX(max(x1, x2)),
   610         selection = { x1: selX(min(x1, x2)), x2: selX(max(x1, x2)),
   343             y1: selY(min(y1, y2)), y2: selY(max(y1, y2)),
   611             y1: selY(min(y1, y2)), y2: selY(max(y1, y2)),
   344             width: abs(x2 - x1), height: abs(y2 - y1) };
   612             width: abs(x2 - x1), height: abs(y2 - y1) };
   346         update();
   614         update();
   347 
   615 
   348         options.onSelectChange(img, getSelection());
   616         options.onSelectChange(img, getSelection());
   349     }
   617     }
   350 
   618 
       
   619     /**
       
   620      * Mousemove event handler triggered when the user is selecting an area
       
   621      *
       
   622      * @param event
       
   623      *            The event object
       
   624      * @return false
       
   625      */
   351     function selectingMouseMove(event) {
   626     function selectingMouseMove(event) {
   352         x2 = resize == '' || /w|e/.test(resize) || aspectRatio ? evX(event) : viewX(selection.x2);
   627         x2 = /w|e|^$/.test(resize) || aspectRatio ? evX(event) : viewX(selection.x2);
   353         y2 = resize == '' || /n|s/.test(resize) || aspectRatio ? evY(event) : viewY(selection.y2);
   628         y2 = /n|s|^$/.test(resize) || aspectRatio ? evY(event) : viewY(selection.y2);
   354 
   629 
   355         doResize();
   630         doResize();
   356 
   631 
   357         return false;
   632         return false;
   358 
   633     }
   359     }
   634 
   360 
   635     /**
       
   636      * Move the selection area
       
   637      *
       
   638      * @param newX1
       
   639      *            New viewport X1
       
   640      * @param newY1
       
   641      *            New viewport Y1
       
   642      */
   361     function doMove(newX1, newY1) {
   643     function doMove(newX1, newY1) {
   362         x2 = (x1 = newX1) + selection.width;
   644         x2 = (x1 = newX1) + selection.width;
   363         y2 = (y1 = newY1) + selection.height;
   645         y2 = (y1 = newY1) + selection.height;
   364 
   646 
   365         selection = $.extend(selection, { x1: selX(x1), y1: selY(y1),
   647         $.extend(selection, { x1: selX(x1), y1: selY(y1), x2: selX(x2),
   366             x2: selX(x2), y2: selY(y2) });
   648             y2: selY(y2) });
   367 
   649 
   368         update();
   650         update();
   369 
   651 
   370         options.onSelectChange(img, getSelection());
   652         options.onSelectChange(img, getSelection());
   371     }
   653     }
   372 
   654 
       
   655     /**
       
   656      * Mousemove event handler triggered when the selection area is being moved
       
   657      *
       
   658      * @param event
       
   659      *            The event object
       
   660      * @return false
       
   661      */
   373     function movingMouseMove(event) {
   662     function movingMouseMove(event) {
   374         x1 = max(left, min(startX + evX(event), left + imgWidth - selection.width));
   663         x1 = max(left, min(startX + evX(event), left + imgWidth - selection.width));
   375         y1 = max(top, min(startY + evY(event), top + imgHeight - selection.height));
   664         y1 = max(top, min(startY + evY(event), top + imgHeight - selection.height));
   376 
   665 
   377         doMove(x1, y1);
   666         doMove(x1, y1);
   378 
   667 
   379         event.preventDefault();
   668         event.preventDefault();
   380 
       
   381         return false;
   669         return false;
   382     }
   670     }
   383 
   671 
       
   672     /**
       
   673      * Start selection
       
   674      */
   384     function startSelection() {
   675     function startSelection() {
       
   676         $(document).unbind('mousemove', startSelection);
   385         adjust();
   677         adjust();
   386 
   678 
   387         x2 = x1;
   679         x2 = x1;
   388         y2 = y1;
   680         y2 = y1;
   389 
       
   390         doResize();
   681         doResize();
   391 
   682 
   392         resize = '';
   683         resize = '';
   393 
   684 
   394         if ($outer.is(':not(:visible)'))
   685         if (!$outer.is(':visible'))
       
   686             /* Show the plugin elements */
   395             $box.add($outer).hide().fadeIn(options.fadeSpeed||0);
   687             $box.add($outer).hide().fadeIn(options.fadeSpeed||0);
   396 
   688 
   397         shown = true;
   689         shown = true;
   398 
   690 
   399         $(document).unbind('mouseup', cancelSelection)
   691         $(document).unbind('mouseup', cancelSelection)
   401         $box.unbind('mousemove', areaMouseMove);
   693         $box.unbind('mousemove', areaMouseMove);
   402 
   694 
   403         options.onSelectStart(img, getSelection());
   695         options.onSelectStart(img, getSelection());
   404     }
   696     }
   405 
   697 
       
   698     /**
       
   699      * Cancel selection
       
   700      */
   406     function cancelSelection() {
   701     function cancelSelection() {
   407         $(document).unbind('mousemove', startSelection);
   702         $(document).unbind('mousemove', startSelection)
       
   703             .unbind('mouseup', cancelSelection);
   408         hide($box.add($outer));
   704         hide($box.add($outer));
   409 
   705 
   410         selection = { x1: selX(x1), y1: selY(y1), x2: selX(x1), y2: selY(y1),
   706         setSelection(selX(x1), selY(y1), selX(x1), selY(y1));
   411                 width: 0, height: 0 };
   707 
   412 
   708         /* If this is an API call, callback functions should not be triggered */
   413         options.onSelectChange(img, getSelection());
   709         if (!(this instanceof $.imgAreaSelect)) {
   414         options.onSelectEnd(img, getSelection());
   710             options.onSelectChange(img, getSelection());
   415     }
   711             options.onSelectEnd(img, getSelection());
   416 
   712         }
       
   713     }
       
   714 
       
   715     /**
       
   716      * Image mousedown event handler
       
   717      *
       
   718      * @param event
       
   719      *            The event object
       
   720      * @return false
       
   721      */
   417     function imgMouseDown(event) {
   722     function imgMouseDown(event) {
       
   723         /* Ignore the event if animation is in progress */
   418         if (event.which != 1 || $outer.is(':animated')) return false;
   724         if (event.which != 1 || $outer.is(':animated')) return false;
   419 
   725 
   420         adjust();
   726         adjust();
   421         startX = x1 = evX(event);
   727         startX = x1 = evX(event);
   422         startY = y1 = evY(event);
   728         startY = y1 = evY(event);
   423 
   729 
   424         $(document).one('mousemove', startSelection)
   730         /* Selection will start when the mouse is moved */
   425             .one('mouseup', cancelSelection);
   731         $(document).mousemove(startSelection).mouseup(cancelSelection);
   426 
   732 
   427         return false;
   733         return false;
   428     }
   734     }
   429 
   735 
   430     function parentScroll() {
   736     /**
       
   737      * Window resize event handler
       
   738      */
       
   739     function windowResize() {
   431         doUpdate(false);
   740         doUpdate(false);
   432     }
   741     }
   433 
   742 
       
   743     /**
       
   744      * Image load event handler. This is the final part of the initialization
       
   745      * process.
       
   746      */
   434     function imgLoad() {
   747     function imgLoad() {
   435         imgLoaded = true;
   748         imgLoaded = true;
   436 
   749 
       
   750         /* Set options */
   437         setOptions(options = $.extend({
   751         setOptions(options = $.extend({
   438             classPrefix: 'imgareaselect',
   752             classPrefix: 'imgareaselect',
   439             movable: true,
   753             movable: true,
       
   754             parent: 'body',
   440             resizable: true,
   755             resizable: true,
   441             parent: 'body',
   756             resizeMargin: 10,
   442             onInit: function () {},
   757             onInit: function () {},
   443             onSelectStart: function () {},
   758             onSelectStart: function () {},
   444             onSelectChange: function () {},
   759             onSelectChange: function () {},
   445             onSelectEnd: function () {}
   760             onSelectEnd: function () {}
   446         }, options));
   761         }, options));
   452             adjust();
   767             adjust();
   453             update();
   768             update();
   454             $box.add($outer).hide().fadeIn(options.fadeSpeed||0);
   769             $box.add($outer).hide().fadeIn(options.fadeSpeed||0);
   455         }
   770         }
   456 
   771 
       
   772         /*
       
   773          * Call the onInit callback. The setTimeout() call is used to ensure
       
   774          * that the plugin has been fully initialized and the object instance is
       
   775          * available (so that it can be obtained in the callback).
       
   776          */
   457         setTimeout(function () { options.onInit(img, getSelection()); }, 0);
   777         setTimeout(function () { options.onInit(img, getSelection()); }, 0);
   458     }
   778     }
   459 
   779 
       
   780     /**
       
   781      * Document keypress event handler
       
   782      *
       
   783      * @param event
       
   784      *            The event object
       
   785      * @return false
       
   786      */
   460     var docKeyPress = function(event) {
   787     var docKeyPress = function(event) {
   461         var k = options.keys, d, t, key = event.keyCode || event.which;
   788         var k = options.keys, d, t, key = event.keyCode;
   462 
   789 
   463         d = !isNaN(k.alt) && (event.altKey || event.originalEvent.altKey) ? k.alt :
   790         d = !isNaN(k.alt) && (event.altKey || event.originalEvent.altKey) ? k.alt :
   464             !isNaN(k.ctrl) && event.ctrlKey ? k.ctrl :
   791             !isNaN(k.ctrl) && event.ctrlKey ? k.ctrl :
   465             !isNaN(k.shift) && event.shiftKey ? k.shift :
   792             !isNaN(k.shift) && event.shiftKey ? k.shift :
   466             !isNaN(k.arrows) ? k.arrows : 10;
   793             !isNaN(k.arrows) ? k.arrows : 10;
   467 
   794 
   468         if (k.arrows == 'resize' || (k.shift == 'resize' && event.shiftKey) ||
   795         if (k.arrows == 'resize' || (k.shift == 'resize' && event.shiftKey) ||
   469             (k.ctrl == 'resize' && event.ctrlKey) ||
   796             (k.ctrl == 'resize' && event.ctrlKey) ||
   470             (k.alt == 'resize' && (event.altKey || event.originalEvent.altKey)))
   797             (k.alt == 'resize' && (event.altKey || event.originalEvent.altKey)))
   471         {
   798         {
       
   799             /* Resize selection */
       
   800 
   472             switch (key) {
   801             switch (key) {
   473             case 37:
   802             case 37:
       
   803                 /* Left */
   474                 d = -d;
   804                 d = -d;
   475             case 39:
   805             case 39:
       
   806                 /* Right */
   476                 t = max(x1, x2);
   807                 t = max(x1, x2);
   477                 x1 = min(x1, x2);
   808                 x1 = min(x1, x2);
   478                 x2 = max(t + d, x1);
   809                 x2 = max(t + d, x1);
   479                 if (aspectRatio) aspectRatioYX();
   810                 fixAspectRatio();
   480                 break;
   811                 break;
   481             case 38:
   812             case 38:
       
   813                 /* Up */
   482                 d = -d;
   814                 d = -d;
   483             case 40:
   815             case 40:
       
   816                 /* Down */
   484                 t = max(y1, y2);
   817                 t = max(y1, y2);
   485                 y1 = min(y1, y2);
   818                 y1 = min(y1, y2);
   486                 y2 = max(t + d, y1);
   819                 y2 = max(t + d, y1);
   487                 if (aspectRatio) aspectRatioXY();
   820                 fixAspectRatio(true);
   488                 break;
   821                 break;
   489             default:
   822             default:
   490                 return;
   823                 return;
   491             }
   824             }
   492 
   825 
   493             doResize();
   826             doResize();
   494         }
   827         }
   495         else {
   828         else {
       
   829             /* Move selection */
       
   830 
   496             x1 = min(x1, x2);
   831             x1 = min(x1, x2);
   497             y1 = min(y1, y2);
   832             y1 = min(y1, y2);
   498 
   833 
   499             switch (key) {
   834             switch (key) {
   500             case 37:
   835             case 37:
       
   836                 /* Left */
   501                 doMove(max(x1 - d, left), y1);
   837                 doMove(max(x1 - d, left), y1);
   502                 break;
   838                 break;
   503             case 38:
   839             case 38:
       
   840                 /* Up */
   504                 doMove(x1, max(y1 - d, top));
   841                 doMove(x1, max(y1 - d, top));
   505                 break;
   842                 break;
   506             case 39:
   843             case 39:
       
   844                 /* Right */
   507                 doMove(x1 + min(d, imgWidth - selX(x2)), y1);
   845                 doMove(x1 + min(d, imgWidth - selX(x2)), y1);
   508                 break;
   846                 break;
   509             case 40:
   847             case 40:
       
   848                 /* Down */
   510                 doMove(x1, y1 + min(d, imgHeight - selY(y2)));
   849                 doMove(x1, y1 + min(d, imgHeight - selY(y2)));
   511                 break;
   850                 break;
   512             default:
   851             default:
   513                 return;
   852                 return;
   514             }
   853             }
   515         }
   854         }
   516 
   855 
   517         return false;
   856         return false;
   518     };
   857     };
   519 
   858 
       
   859     /**
       
   860      * Apply style options to plugin element (or multiple elements)
       
   861      *
       
   862      * @param $elem
       
   863      *            A jQuery object representing the element(s) to style
       
   864      * @param props
       
   865      *            An object that maps option names to corresponding CSS
       
   866      *            properties
       
   867      */
   520     function styleOptions($elem, props) {
   868     function styleOptions($elem, props) {
   521         for (option in props)
   869         for (var option in props)
   522             if (options[option] !== undefined)
   870             if (options[option] !== undefined)
   523                 $elem.css(props[option], options[option]);
   871                 $elem.css(props[option], options[option]);
   524     }
   872     }
   525 
   873 
       
   874     /**
       
   875      * Set plugin options
       
   876      *
       
   877      * @param newOptions
       
   878      *            The new options object
       
   879      */
   526     function setOptions(newOptions) {
   880     function setOptions(newOptions) {
   527         if (newOptions.parent)
   881         if (newOptions.parent)
   528             ($parent = $(newOptions.parent)).append($box.add($outer));
   882             ($parent = $(newOptions.parent)).append($box.add($outer));
   529 
   883 
   530         options = $.extend(options, newOptions);
   884         /* Merge the new options with the existing ones */
       
   885         $.extend(options, newOptions);
   531 
   886 
   532         adjust();
   887         adjust();
   533 
   888 
   534         if (newOptions.handles != null) {
   889         if (newOptions.handles != null) {
       
   890             /* Recreate selection area handles */
   535             $handles.remove();
   891             $handles.remove();
   536             $handles = $([]);
   892             $handles = $([]);
   537 
   893 
   538             i = newOptions.handles ? newOptions.handles == 'corners' ? 4 : 8 : 0;
   894             i = newOptions.handles ? newOptions.handles == 'corners' ? 4 : 8 : 0;
   539 
   895 
   540             while (i--)
   896             while (i--)
   541                 $handles = $handles.add(div());
   897                 $handles = $handles.add(div());
   542 
   898 
       
   899             /* Add a class to handles and set the CSS properties */
   543             $handles.addClass(options.classPrefix + '-handle').css({
   900             $handles.addClass(options.classPrefix + '-handle').css({
   544                 position: 'absolute',
   901                 position: 'absolute',
       
   902                 /*
       
   903                  * The font-size property needs to be set to zero, otherwise
       
   904                  * Internet Explorer makes the handles too large
       
   905                  */
   545                 fontSize: 0,
   906                 fontSize: 0,
   546                 zIndex: zIndex + 1 || 1
   907                 zIndex: zIndex + 1 || 1
   547             });
   908             });
   548 
   909 
   549             if (!parseInt($handles.css('width')))
   910             /*
       
   911              * If handle width/height has not been set with CSS rules, set the
       
   912              * default 5px
       
   913              */
       
   914             if (!parseInt($handles.css('width')) >= 0)
   550                 $handles.width(5).height(5);
   915                 $handles.width(5).height(5);
   551 
   916 
       
   917             /*
       
   918              * If the borderWidth option is in use, add a solid border to
       
   919              * handles
       
   920              */
   552             if (o = options.borderWidth)
   921             if (o = options.borderWidth)
   553                 $handles.css({ borderWidth: o, borderStyle: 'solid' });
   922                 $handles.css({ borderWidth: o, borderStyle: 'solid' });
   554 
   923 
       
   924             /* Apply other style options */
   555             styleOptions($handles, { borderColor1: 'border-color',
   925             styleOptions($handles, { borderColor1: 'border-color',
   556                 borderColor2: 'background-color',
   926                 borderColor2: 'background-color',
   557                 borderOpacity: 'opacity' });
   927                 borderOpacity: 'opacity' });
   558         }
   928         }
   559 
   929 
       
   930         /* Calculate scale factors */
   560         scaleX = options.imageWidth / imgWidth || 1;
   931         scaleX = options.imageWidth / imgWidth || 1;
   561         scaleY = options.imageHeight / imgHeight || 1;
   932         scaleY = options.imageHeight / imgHeight || 1;
   562 
   933 
       
   934         /* Set selection */
   563         if (newOptions.x1 != null) {
   935         if (newOptions.x1 != null) {
   564             setSelection(newOptions.x1, newOptions.y1, newOptions.x2,
   936             setSelection(newOptions.x1, newOptions.y1, newOptions.x2,
   565                     newOptions.y2);
   937                 newOptions.y2);
   566             newOptions.show = !newOptions.hide;
   938             newOptions.show = !newOptions.hide;
   567         }
   939         }
   568 
   940 
   569         if (newOptions.keys)
   941         if (newOptions.keys)
       
   942             /* Enable keyboard support */
   570             options.keys = $.extend({ shift: 1, ctrl: 'resize' },
   943             options.keys = $.extend({ shift: 1, ctrl: 'resize' },
   571                 newOptions.keys);
   944                 newOptions.keys);
   572 
   945 
       
   946         /* Add classes to plugin elements */
   573         $outer.addClass(options.classPrefix + '-outer');
   947         $outer.addClass(options.classPrefix + '-outer');
   574         $area.addClass(options.classPrefix + '-selection');
   948         $area.addClass(options.classPrefix + '-selection');
   575         for (i = 0; i++ < 4;)
   949         for (i = 0; i++ < 4;)
   576             $($border[i-1]).addClass(options.classPrefix + '-border' + i);
   950             $($border[i-1]).addClass(options.classPrefix + '-border' + i);
   577 
   951 
       
   952         /* Apply style options */
   578         styleOptions($area, { selectionColor: 'background-color',
   953         styleOptions($area, { selectionColor: 'background-color',
   579             selectionOpacity: 'opacity' });
   954             selectionOpacity: 'opacity' });
   580         styleOptions($border, { borderOpacity: 'opacity',
   955         styleOptions($border, { borderOpacity: 'opacity',
   581             borderWidth: 'border-width' });
   956             borderWidth: 'border-width' });
   582         styleOptions($outer, { outerColor: 'background-color',
   957         styleOptions($outer, { outerColor: 'background-color',
   584         if (o = options.borderColor1)
   959         if (o = options.borderColor1)
   585             $($border[0]).css({ borderStyle: 'solid', borderColor: o });
   960             $($border[0]).css({ borderStyle: 'solid', borderColor: o });
   586         if (o = options.borderColor2)
   961         if (o = options.borderColor2)
   587             $($border[1]).css({ borderStyle: 'dashed', borderColor: o });
   962             $($border[1]).css({ borderStyle: 'dashed', borderColor: o });
   588 
   963 
   589         $box.append($area.add($border).add($handles).add($areaOpera));
   964         /* Append all the selection area elements to the container box */
       
   965         $box.append($area.add($border).add($areaOpera).add($handles));
   590 
   966 
   591         if ($.browser.msie) {
   967         if ($.browser.msie) {
   592             if (o = $outer.css('filter').match(/opacity=([0-9]+)/))
   968             if (o = $outer.css('filter').match(/opacity=(\d+)/))
   593                 $outer.css('opacity', o[1]/100);
   969                 $outer.css('opacity', o[1]/100);
   594             if (o = $border.css('filter').match(/opacity=([0-9]+)/))
   970             if (o = $border.css('filter').match(/opacity=(\d+)/))
   595                 $border.css('opacity', o[1]/100);
   971                 $border.css('opacity', o[1]/100);
   596         }
   972         }
   597 
   973 
   598         if (newOptions.hide)
   974         if (newOptions.hide)
   599             hide($box.add($outer));
   975             hide($box.add($outer));
   601             shown = true;
   977             shown = true;
   602             $box.add($outer).fadeIn(options.fadeSpeed||0);
   978             $box.add($outer).fadeIn(options.fadeSpeed||0);
   603             doUpdate();
   979             doUpdate();
   604         }
   980         }
   605 
   981 
       
   982         /* Calculate the aspect ratio factor */
   606         aspectRatio = (d = (options.aspectRatio || '').split(/:/))[0] / d[1];
   983         aspectRatio = (d = (options.aspectRatio || '').split(/:/))[0] / d[1];
   607 
   984 
       
   985         $img.add($outer).unbind('mousedown', imgMouseDown);
       
   986 
   608         if (options.disable || options.enable === false) {
   987         if (options.disable || options.enable === false) {
       
   988             /* Disable the plugin */
   609             $box.unbind('mousemove', areaMouseMove).unbind('mousedown', areaMouseDown);
   989             $box.unbind('mousemove', areaMouseMove).unbind('mousedown', areaMouseDown);
   610             $img.add($outer).unbind('mousedown', imgMouseDown);
   990             $(window).unbind('resize', windowResize);
   611             $(window).unbind('resize', parentScroll);
   991         }
   612             $img.add($img.parents()).unbind('scroll', parentScroll);
   992         else {
   613         }
   993             if (options.enable || options.disable === false) {
   614         else if (options.enable || options.disable === false) {
   994                 /* Enable the plugin */
   615             if (options.resizable || options.movable)
   995                 if (options.resizable || options.movable)
   616                 $box.mousemove(areaMouseMove).mousedown(areaMouseDown);
   996                     $box.mousemove(areaMouseMove).mousedown(areaMouseDown);
       
   997 
       
   998                 $(window).resize(windowResize);
       
   999             }
   617 
  1000 
   618             if (!options.persistent)
  1001             if (!options.persistent)
   619                 $img.add($outer).mousedown(imgMouseDown);
  1002                 $img.add($outer).mousedown(imgMouseDown);
   620             $(window).resize(parentScroll);
       
   621             $img.add($img.parents()).scroll(parentScroll);
       
   622         }
  1003         }
   623 
  1004 
   624         options.enable = options.disable = undefined;
  1005         options.enable = options.disable = undefined;
   625     }
  1006     }
   626 
  1007 
       
  1008     /**
       
  1009      * Remove plugin completely
       
  1010      */
       
  1011     this.remove = function () {
       
  1012         /*
       
  1013          * Call setOptions with { disable: true } to unbind the event handlers
       
  1014          */
       
  1015         setOptions({ disable: true });
       
  1016         $box.add($outer).remove();
       
  1017     };
       
  1018 
       
  1019     /*
       
  1020      * Public API
       
  1021      */
       
  1022 
       
  1023     /**
       
  1024      * Get current options
       
  1025      *
       
  1026      * @return An object containing the set of options currently in use
       
  1027      */
   627     this.getOptions = function () { return options; };
  1028     this.getOptions = function () { return options; };
   628 
  1029 
       
  1030     /**
       
  1031      * Set plugin options
       
  1032      *
       
  1033      * @param newOptions
       
  1034      *            The new options object
       
  1035      */
   629     this.setOptions = setOptions;
  1036     this.setOptions = setOptions;
   630 
  1037 
       
  1038     /**
       
  1039      * Get the current selection
       
  1040      *
       
  1041      * @param noScale
       
  1042      *            If set to <code>true</code>, scaling is not applied to the
       
  1043      *            returned selection
       
  1044      * @return Selection object
       
  1045      */
   631     this.getSelection = getSelection;
  1046     this.getSelection = getSelection;
   632 
  1047 
       
  1048     /**
       
  1049      * Set the current selection
       
  1050      *
       
  1051      * @param x1
       
  1052      *            X coordinate of the upper left corner of the selection area
       
  1053      * @param y1
       
  1054      *            Y coordinate of the upper left corner of the selection area
       
  1055      * @param x2
       
  1056      *            X coordinate of the lower right corner of the selection area
       
  1057      * @param y2
       
  1058      *            Y coordinate of the lower right corner of the selection area
       
  1059      * @param noScale
       
  1060      *            If set to <code>true</code>, scaling is not applied to the
       
  1061      *            new selection
       
  1062      */
   633     this.setSelection = setSelection;
  1063     this.setSelection = setSelection;
   634 
  1064 
       
  1065     /**
       
  1066      * Cancel selection
       
  1067      */
       
  1068     this.cancelSelection = cancelSelection;
       
  1069 
       
  1070     /**
       
  1071      * Update plugin elements
       
  1072      *
       
  1073      * @param resetKeyPress
       
  1074      *            If set to <code>false</code>, this instance's keypress
       
  1075      *            event handler is not activated
       
  1076      */
   635     this.update = doUpdate;
  1077     this.update = doUpdate;
   636 
  1078 
       
  1079     /*
       
  1080      * Traverse the image's parent elements (up to <body>) and find the
       
  1081      * highest z-index
       
  1082      */
   637     $p = $img;
  1083     $p = $img;
   638 
  1084 
   639     while ($p.length && !$p.is('body')) {
  1085     while ($p.length) {
   640         if (!isNaN($p.css('z-index')) && $p.css('z-index') > zIndex)
  1086         zIndex = max(zIndex,
   641             zIndex = $p.css('z-index');
  1087             !isNaN($p.css('z-index')) ? $p.css('z-index') : zIndex);
       
  1088         /* Also check if any of the ancestor elements has fixed position */
   642         if ($p.css('position') == 'fixed')
  1089         if ($p.css('position') == 'fixed')
   643             position = 'fixed';
  1090             position = 'fixed';
   644 
  1091 
   645         $p = $p.parent();
  1092         $p = $p.parent(':not(body)');
   646     }
  1093     }
   647 
  1094 
   648     if (!isNaN(options.zIndex))
  1095     /*
   649         zIndex = options.zIndex;
  1096      * If z-index is given as an option, it overrides the one found by the
       
  1097      * above loop
       
  1098      */
       
  1099     zIndex = options.zIndex || zIndex;
   650 
  1100 
   651     if ($.browser.msie)
  1101     if ($.browser.msie)
   652         $img.attr('unselectable', 'on');
  1102         $img.attr('unselectable', 'on');
   653 
  1103 
       
  1104     /*
       
  1105      * In MSIE and WebKit, we need to use the keydown event instead of keypress
       
  1106      */
   654     $.imgAreaSelect.keyPress = $.browser.msie ||
  1107     $.imgAreaSelect.keyPress = $.browser.msie ||
   655         $.browser.safari ? 'keydown' : 'keypress';
  1108         $.browser.safari ? 'keydown' : 'keypress';
   656 
  1109 
       
  1110     /*
       
  1111      * There is a bug affecting the CSS cursor property in Opera (observed in
       
  1112      * versions up to 10.00) that prevents the cursor from being updated unless
       
  1113      * the mouse leaves and enters the element again. To trigger the mouseover
       
  1114      * event, we're adding an additional div to $box and we're going to toggle
       
  1115      * it when mouse moves inside the selection area.
       
  1116      */
   657     if ($.browser.opera)
  1117     if ($.browser.opera)
   658         $areaOpera = div().css({ width: '100%', height: '100%',
  1118         $areaOpera = div().css({ width: '100%', height: '100%',
   659             position: 'absolute', zIndex: zIndex + 2 || 2 });
  1119             position: 'absolute', zIndex: zIndex + 2 || 2 });
   660 
  1120 
       
  1121     /*
       
  1122      * We initially set visibility to "hidden" as a workaround for a weird
       
  1123      * behaviour observed in Google Chrome 1.0.154.53 (on Windows XP). Normally
       
  1124      * we would just set display to "none", but, for some reason, if we do so
       
  1125      * then Chrome refuses to later display the element with .show() or
       
  1126      * .fadeIn().
       
  1127      */
   661     $box.add($outer).css({ visibility: 'hidden', position: position,
  1128     $box.add($outer).css({ visibility: 'hidden', position: position,
   662         overflow: 'hidden', zIndex: zIndex || '0' });
  1129         overflow: 'hidden', zIndex: zIndex || '0' });
   663     $box.css({ zIndex: zIndex + 2 || 2 });
  1130     $box.css({ zIndex: zIndex + 2 || 2 });
   664     $area.add($border).css({ position: 'absolute' });
  1131     $area.add($border).css({ position: 'absolute', fontSize: 0 });
   665 
  1132 
       
  1133     /*
       
  1134      * If the image has been fully loaded, or if it is not really an image (eg.
       
  1135      * a div), call imgLoad() immediately; otherwise, bind it to be called once
       
  1136      * on image load event.
       
  1137      */
   666     img.complete || img.readyState == 'complete' || !$img.is('img') ?
  1138     img.complete || img.readyState == 'complete' || !$img.is('img') ?
   667         imgLoad() : $img.one('load', imgLoad);
  1139         imgLoad() : $img.one('load', imgLoad);
   668 
  1140 
       
  1141     /*
       
  1142      * MSIE 9.0 doesn't always fire the image load event -- resetting the src
       
  1143      * attribute seems to trigger it. The check is for version 7 and above to
       
  1144      * accommodate for MSIE 9 running in compatibility mode.
       
  1145      */
       
  1146    if (!imgLoaded && $.browser.msie && $.browser.version >= 7)
       
  1147         img.src = img.src;
   669 };
  1148 };
   670 
  1149 
       
  1150 /**
       
  1151  * Invoke imgAreaSelect on a jQuery object containing the image(s)
       
  1152  *
       
  1153  * @param options
       
  1154  *            Options object
       
  1155  * @return The jQuery object or a reference to imgAreaSelect instance (if the
       
  1156  *         <code>instance</code> option was specified)
       
  1157  */
   671 $.fn.imgAreaSelect = function (options) {
  1158 $.fn.imgAreaSelect = function (options) {
   672     options = options || {};
  1159     options = options || {};
   673 
  1160 
   674     this.each(function () {
  1161     this.each(function () {
   675         if ($(this).data('imgAreaSelect'))
  1162         /* Is there already an imgAreaSelect instance bound to this element? */
   676             $(this).data('imgAreaSelect').setOptions(options);
  1163         if ($(this).data('imgAreaSelect')) {
   677         else {
  1164             /* Yes there is -- is it supposed to be removed? */
       
  1165             if (options.remove) {
       
  1166                 /* Remove the plugin */
       
  1167                 $(this).data('imgAreaSelect').remove();
       
  1168                 $(this).removeData('imgAreaSelect');
       
  1169             }
       
  1170             else
       
  1171                 /* Reset options */
       
  1172                 $(this).data('imgAreaSelect').setOptions(options);
       
  1173         }
       
  1174         else if (!options.remove) {
       
  1175             /* No exising instance -- create a new one */
       
  1176 
       
  1177             /*
       
  1178              * If neither the "enable" nor the "disable" option is present, add
       
  1179              * "enable" as the default
       
  1180              */
   678             if (options.enable === undefined && options.disable === undefined)
  1181             if (options.enable === undefined && options.disable === undefined)
   679                 options.enable = true;
  1182                 options.enable = true;
   680 
  1183 
   681             $(this).data('imgAreaSelect', new $.imgAreaSelect(this, options));
  1184             $(this).data('imgAreaSelect', new $.imgAreaSelect(this, options));
   682         }
  1185         }
   683     });
  1186     });
   684 
  1187 
   685     if (options.instance)
  1188     if (options.instance)
       
  1189         /*
       
  1190          * Return the imgAreaSelect instance bound to the first element in the
       
  1191          * set
       
  1192          */
   686         return $(this).data('imgAreaSelect');
  1193         return $(this).data('imgAreaSelect');
   687 
  1194 
   688     return this;
  1195     return this;
   689 };
  1196 };
   690 
  1197