var gMapSelect = function() {

  var SQUARE_SIZE_PIXELS = 10;
	//  var DEFAULT_PRICE_TARGET = 15;
  var DEFAULT_PRICE_TARGET = 5;
	var SELECT_AREA_ID = "selectArea";

  var MAP_CONTAINER_ID = "mapContainer";
	var MAP_VIEWPORT_ID = "mapViewport";
	var _elMapViewport = null;
	var _elSelectArea = null;
  var _elSelectAreaStyle = null;

  var STATE_DRAGGING = "dragging";
  var STATE_SELECTING = "selecting";
  var STATE_SELECTED = "selected";
  var STATE_RESIZING = "resizing";
  var STATE_HIDDEN = "hidden";
  var _state = STATE_HIDDEN;

  var _selectionStart = null;  // x,y where a selection drag started
  var _currentSelectAreaInfo = null;    // holds object which descirbes the current selection

  var DEFAULT_MOUSEOVER_CURSOR_VALUE = "move";
  var _currentMouseoverCursor = DEFAULT_MOUSEOVER_CURSOR_VALUE;   
   
	// cache BeboNation objects for fast access
  var _oMap = null; 
  var _oViewport = null;

  var _selectorDragStartLeft = null;
  var _selectorDragStartTop = null;
	var _selectorDragLastLeft = null;
	var	_selectorDragLastTop = null;


  // resize activation zones on the edges of the select area
//   var _leftResizeZoneBegin = null;
//   var _leftResizeZoneEnd = null;
//   var _rightResizeZoneBegin = null;
//   var _rightResizeZoneEnd = null;
//   var _topResizeZoneBegin = null;
//   var _topResizeZoneEnd = null;
//   var _bottomResizeZoneBegin = null;
//   var _bottomResizeZoneEnd = null;
//   var RESIZE_ZONE_SIZE_PIXELS = 10;

	// variables used during resizing of the select area
	var _resizeMouseStartLeft = null;
	var _resizeMouseStartTop = null;
	var _resizeStartLeft = null;
	var _resizeStartTop = null;
	var _resizeStartHeight = null;
	var _resizeStartWidth = null;

	var _resizeMoveLeft = null;
	var _resizeMoveTop = null;
	var _resizingWidth = null;
	var _resizingHeight = null;

  var _imgLocation = null;
  var _imgUrl = null;
  var _imgOriginalWidth = null;
  var _imgOriginalHeight = null;

  var _elPrice = null;
  var _elPriceometer = null;

	var _handlesArr = null;


  
  function init() {
		_elMapViewport =  _proxy_jslib_handle(document, 'getElementById', '', 1, 0)( MAP_VIEWPORT_ID );
    _oMap = gMap;
    _oViewport = gViewport;

		_handlesArr = [$("nwHandle"), $("nHandle"), $("neHandle"), $("wHandle"), $("eHandle"), $("swHandle"), $("sHandle"), $("seHandle")];

    _elPrice = $("price");
    _elPriceometer = $("priceometer");

    // add an event to the priceResize box that takes action if the user hits the return key
    var elPriceResize = $("priceResize");
    YUE.addListener( elPriceResize, "keydown", function(e) {
      if( e.keyCode == 13 ){
        gMapSelect.resizeToPriceUI();
        _hidePriceEdit();
      }
    });
  };


  function _setState( state ) {
    _state = state;
  };

	
	function isResizing() {
		return _state == STATE_RESIZING;
	}

  function _isDragging() {
    return _state == STATE_DRAGGING;
  };

  function isSelected() {
    return _state == STATE_SELECTED;
  }

  function isSelecting() {
    return _state == STATE_SELECTING;
  };



	function _createSelectAreaElement( imgUrl ) {

    imgUrl = imgUrl || false;  // optional image background URL

//     var el = document.createElement( "DIV" );
//     if( imgUrl ){
//       var elImg = document.createElement( "IMG" );
//       elImg.src = imgUrl;
//       elImg.style.width = "100%";
//       elImg.style.height = "100%";
//       el.appendChild( elImg );
//     }

    if(imgUrl){
			var elImg = $("selectAreaImage");
      YUE.addListener( elImg, "drag", function() {return false;} );   // ie temp fix to prevent images from dragging
       _proxy_jslib_assign('', elImg, 'src', '=', ( imgUrl));
      elImg.style.display="inline";
    }


		_elSelectArea = $("selectArea");
    _elSelectAreaStyle = _elSelectArea.style;

    YUE.addListener( _elSelectArea, "mousedown", _mapSelectMousedown );
		//    YUE.addListener( _elSelectArea, "mousemove", _mapSelectMousemove );
    YUE.addListener( _elSelectArea, "mouseup", _mapSelectMouseup );

    YUE.addListener( $("nwHandle"), "mousedown", _startResizing, "nw" );
    YUE.addListener( $("nHandle"), "mousedown", _startResizing, "n" );
    YUE.addListener( $("neHandle"), "mousedown", _startResizing, "ne" );
    YUE.addListener( $("wHandle"), "mousedown", _startResizing, "w" );
    YUE.addListener( $("eHandle"), "mousedown", _startResizing, "e" );
    YUE.addListener( $("swHandle"), "mousedown", _startResizing, "sw" );
    YUE.addListener( $("sHandle"), "mousedown", _startResizing, "s" );
    YUE.addListener( $("seHandle"), "mousedown", _startResizing, "se" );


		YUE.addListener("priceDisplay","mouseover", function() { $("priceDisplay").className="hoverInlineEdit";});
		YUE.addListener("priceDisplay","mouseout", function() { $("priceDisplay").className="";});
		YUE.addListener("priceDisplay","click", _showPriceEdit );
		YUE.addListener("priceGoBtn", "click", _hidePriceEdit );
    
		// prevent the text in the select area from being selected and highlighed by mouse dragging
    if( gIsIE ){
      YUE.addListener( _elSelectArea, "selectstart", function() { return false; } );  // i think this might only be necessary for IE
    }
    // i'm not sure why these were commented out.  I only commented back in what I needed to prevent selection in IE
    //_elSelectArea.unselectable = "on";
    //    _elSelectAreaStyle.MozUserSelect = "none";

    return _elSelectArea;
	};


  function clear() {

    if( _elSelectArea ){
      _setState( STATE_HIDDEN );
			_hideSelectArea();
      _destroy();
    }

    _oMap.endMapSelectDisplay();


  };

	function _showPriceEdit() {
		$("priceDisplay").style.display='none';
		$("priceEdit").style.display='block';

		var elPriceResize = $("priceResize");
		 _proxy_jslib_assign('', elPriceResize, 'value', '=', ( ""));
		elPriceResize.focus();
	}
	
	function _hidePriceEdit() {
		$("priceEdit").style.display='none';
		$("priceDisplay").style.display='block';
	}
	



  
  function _destroy() {
    
    // might as well erase these fields used to track the image the user uploaded
    _imgLocation = null;
    _imgUrl = null;
    _imgOriginalWidth = null;
    _imgOriginalHeight = null;

		// $$$$$ I'm not sure if I need to free the event handlers from the resize handles
  }


//   function _updateCurrentSelectionInfo(){
//     var info = getSelectAreaInfo();

//     // cache coordinates used to show the resize cursor icons
//     _leftResizeZoneBegin = 0;
//     _leftResizeZoneEnd = RESIZE_ZONE_SIZE_PIXELS;
//     _rightResizeZoneBegin = info.width - RESIZE_ZONE_SIZE_PIXELS;
//     _rightResizeZoneEnd = info.width;
//     _topResizeZoneBegin = 0; 
//     _topResizeZoneEnd = RESIZE_ZONE_SIZE_PIXELS;
//     _bottomResizeZoneBegin = info.height - RESIZE_ZONE_SIZE_PIXELS;
//     _bottomResizeZoneEnd = info.height;

//     _currentSelectAreaInfo = info;

//       //      gOriginalUploadImageDialog.updateFormValues( info );
//   };

//   function _getMouseoverCursorValue( e ){
//     // returns the css cursor value for the mouse's current position over the select area layer

//     var layerX = _oMap.getLayerX( e );
//     var layerY = _oMap.getLayerY( e );

//     if( layerY >= _topResizeZoneBegin && layerY <= _topResizeZoneEnd ){
//       var resizeDirection = "n";
//     } else if ( layerY >= _bottomResizeZoneBegin && layerY <= _bottomResizeZoneEnd ){
//       var resizeDirection = "s";
//     } else {
// 			var resizeDirection = "";
// 		}

//     if( layerX >= _leftResizeZoneBegin && layerX <= _leftResizeZoneEnd ){
//       resizeDirection += "w";
//     } else if( layerX >= _rightResizeZoneBegin && layerX <= _rightResizeZoneEnd ){
//       resizeDirection += "e";
//     }
    
//     if( resizeDirection == "" ) {
//       return DEFAULT_MOUSEOVER_CURSOR_VALUE; 
//     } else {
//       return resizeDirection + "-resize";
//     }

//   };


  function getImageUrl() {
    return _imgUrl;
  }

  function getSelectAreaInfo() {
    var info = _oMap.getOverlayAreaInfo( _elSelectArea );
    
    // add the URL to the info object
    if( _imgUrl ){
      info.imgLocation = _imgLocation;
      info.imgUrl = _imgUrl;
      info.imgOriginalWidth = _imgOriginalWidth;
      info.imgOriginalHeight = _imgOriginalHeight;
    }
    
		return  info;
  };

  function isSelectAreaElement( el ) {
    // returns true if the element passed in is the map select area
    return ( el.id == SELECT_AREA_ID );
  };


  function _drawSelectArea( beginMapSquare, endMapSquare ) {

    // figure out top left coord
    var left = beginMapSquare[0];
    if( endMapSquare[0] < left ){
      left = endMapSquare[0];
    }
    left *= SQUARE_SIZE_PIXELS;

    var top = beginMapSquare[1];
    if( endMapSquare[1] <  _proxy_jslib_handle(null, 'top', top, 0, 0) ){
       top= _proxy_jslib_assign_rval('', 'top', '=', ( endMapSquare[1]), top);
    }
     top= _proxy_jslib_assign_rval('', 'top', '*=', ( SQUARE_SIZE_PIXELS), top);

    // figure out width and height
    var width = Math.abs( beginMapSquare[0] - endMapSquare[0] ) * SQUARE_SIZE_PIXELS;
    if( width == 0 ) {
      width = SQUARE_SIZE_PIXELS;
    }

    var height = Math.abs( beginMapSquare[1] - endMapSquare[1] ) * SQUARE_SIZE_PIXELS;
    if( height == 0 ){
      height = SQUARE_SIZE_PIXELS; 
    }

     _proxy_jslib_assign('', _elSelectAreaStyle, 'top', '=', (  _proxy_jslib_handle(null, 'top', top, 0, 0) + "px"));
    _elSelectAreaStyle.left = left + "px";
    _elSelectAreaStyle.height = height + "px";
    //    _elSelectAreaStyle.width = width + "px";
    _setSelectAreaWidth(width);
		
		_showSelectArea();
  };

  function _setCursorValue( cursorValue ) {
    if( _currentMouseoverCursor != cursorValue ) {
      _currentMouseoverCursor = cursorValue;
       _proxy_jslib_assign('', _elSelectAreaStyle, 'cursor', '=', ( cursorValue));
    }
  };

  function getCursorValue() {
    return _currentMouseoverCursor;
  };

	function _showSelectArea() {
    _elSelectAreaStyle.visibility = "visible";
		YUD.setStyle(_handlesArr, "visibility", "visible");
	};

	function _hideSelectArea() {
    _elSelectAreaStyle.visibility = "hidden";
		YUD.setStyle(_handlesArr, "visibility", "hidden");
	};


  // ***************************************************
  //  EVENT ACTIONS FOR MOVING AND RESIZING SELECT AREA
  // ***************************************************
  
  function _mapSelectMousedown( e ) { 
// 		var cursorValue = getCursorValue();
//     if( cursorValue == DEFAULT_MOUSEOVER_CURSOR_VALUE ) {
//       // select area is being dragged
//       _startDragging( e );
//     } else {
//       _startResizing( e );
//     }


		if( !isResizing() ){
			_startDragging( e );
		}

		YUE.stopEvent( e );
  };
 
//  function _mapSelectMousemove( e ){
//     if( isSelected() ){
//       var cursorValue = _getMouseoverCursorValue( e );
//       _setCursorValue( cursorValue );
//     }
//   };

  function _mapSelectMouseup( e ) {
    if( _isDragging() ){
			_endDragging( e );
      YUE.stopEvent( e );
    }
  };

  // ********************************************
  //  EVENT ACTIONS FOR DRAGGING THE SELECT AREA
  // ********************************************

  function _startDragging( e ) {
    _setState( STATE_DRAGGING );
    
    var xy = YUE.getXY( e );
    _selectorDragStartLeft = xy[0];
    _selectorDragStartTop = xy[1];

		// reset variables to cache current position while dragging
		_selectorDragLastLeft = null;
		_selectorDragLastTop = null;

    _selectionDragStartLeft = parseInt( _elSelectAreaStyle.left );
    _selectionDragStartTop = parseInt(  _proxy_jslib_handle(_elSelectAreaStyle, 'top', '', 0, 0) );

		YUE.addListener( _elMapViewport, "mousemove", _whileDragging );

  };

  function _whileDragging( e ) {

    var squareSize = SQUARE_SIZE_PIXELS;

    var deltaX = e.clientX - _selectorDragStartLeft;
    var newLeft = _selectionDragStartLeft + (Math.floor( deltaX / squareSize ) * squareSize);
		if( _selectorDragLastLeft != newLeft ){
			_elSelectAreaStyle.left = newLeft + "px";
			_selectorDragLastLeft = newLeft;
		}

    var deltaY = e.clientY - _selectorDragStartTop;
    var newTop = _selectionDragStartTop + (Math.floor( deltaY / squareSize ) * squareSize);
		if( _selectorDragLastTop != newTop ) {
			 _proxy_jslib_assign('', _elSelectAreaStyle, 'top', '=', ( newTop + "px"));
			_selectorDragLastTop = newTop;
		}

  };


  function _endDragging( e ) {

    // use a while loop to make sure that multiple listeners get removed
    while( YUE.removeListener( _elMapViewport, "mousemove", _whileDragging ) );

    _setState( STATE_SELECTED );

    // update the x and y values in the upload form
		//    _updateCurrentSelectionInfo();
  };


  // ************************************************
  //  END EVENT ACTIONS FOR DRAGGING THE SELECT AREA
  // ************************************************




  // ********************************************
  //  EVENT ACTIONS FOR RESIZING THE SELECT AREA
  // ********************************************


  function _startResizing( e, resizeDirection ) {

    // select area is being resized
    _setState( STATE_RESIZING );
		
		if( !resizeDirection ){
			var cursorValue = getCursorValue();
			var resizeDirection = cursorValue.substring( 0, cursorValue.indexOf("-") );
		}

		_setCursorValue( resizeDirection + "-resize");

    
    _resizeMoveLeft = false;   // if resize direction will cause the left coordinate to change
    _resizingWidth = false;
    _resizeMoveTop = false;   // if resize direction will cause the top coordinate to change
    _resizingHeight = false;
    
    switch( resizeDirection )
    {
    case "n":
      _resizeMoveTop = true;
      _resizingHeight = true;
      break;
    case "s":
      _resizingHeight = true;
      break;
    case "w":
      _resizeMoveLeft = true;
      _resizingWidth = true;
      break;
    case "e":
      _resizingWidth = true;
      break;
    case "nw":
      _resizeMoveTop = true;
      _resizeMoveLeft = true;
      _resizingHeight = true;
      _resizingWidth = true;
      break;
    case "ne":
      _resizeMoveTop = true;
      _resizingHeight = true;
      _resizingWidth = true;
      break;
    case "sw":
      _resizeMoveLeft = true;
      _resizingHeight = true;
      _resizingWidth = true;
      break;
    case "se":
      _resizingHeight = true;
      _resizingWidth = true;
      break;
    }
    
    // record the mouse position as a reference point for the resize dimensions
    var xy = YUE.getXY( e );
    _resizeMouseStartLeft = xy[0];
    _resizeMouseStartTop = xy[1];
    
    // cache the original select area info so that we can resize quickly in the mousemove event
    var startInfo = getSelectAreaInfo();
    _resizeStartLeft = startInfo.left;
    _resizeStartTop =  _proxy_jslib_handle(startInfo, 'top', '', 0, 0);
    _resizeStartWidth = startInfo.width;
    _resizeStartHeight = startInfo.height;

    
    // attach the whileDragging event to the viewport's mousemove event
    YUE.addListener( _elMapViewport, "mousemove", whileResizing );

    // set the cursor of the viewport so it remains steady as the mouse leaves the select area durring resizing
    
    _oViewport.startMapSelectResize();
  };

  function whileResizing( e ) {

    var xy = [e.clientX, e.clientY];

    if( _resizingWidth ){
      var deltaX = xy[0] - _resizeMouseStartLeft;

      // change the width of the area in increments of square width
      var deltaXTicks = (Math.floor( deltaX / SQUARE_SIZE_PIXELS ) * SQUARE_SIZE_PIXELS);

      if( _resizeMoveLeft ){
        var newWidth = _resizeStartWidth - deltaXTicks;
        if( newWidth > 0 ){
          // move the left of the box in increments of square width
          _elSelectAreaStyle.left = (_resizeStartLeft + deltaXTicks) + "px";
          //          _elSelectAreaStyle.width = newWidth + "px";
          _setSelectAreaWidth(newWidth);
        }
      } else {
        var newWidth = _resizeStartWidth + deltaXTicks;
        if( newWidth > 0 ){
          //          _elSelectAreaStyle.width = newWidth + "px";
          _setSelectAreaWidth(newWidth);
        }
      }

    }

    if( _resizingHeight ){
      var deltaY = xy[1] - _resizeMouseStartTop;
      
      // change the height of the box in increments of the square height
      var deltaYTicks = (Math.floor( deltaY / SQUARE_SIZE_PIXELS ) * SQUARE_SIZE_PIXELS);
      
      if( _resizeMoveTop ){
        var newHeight = _resizeStartHeight - deltaYTicks;

        if( newHeight > 0 ){
          // move the top  of the box in increments of square height
           _proxy_jslib_assign('', _elSelectAreaStyle, 'top', '=', ( (_resizeStartTop + deltaYTicks) + "px"));
          _elSelectAreaStyle.height = newHeight + "px";
        } 

      } else {
        var newHeight = _resizeStartHeight + deltaYTicks;
        if( newHeight > 0 ){
          _elSelectAreaStyle.height = newHeight + "px";
        }
      }
    }

    _updatePriceDisplay( _elSelectArea.clientWidth, _elSelectArea.clientHeight);
  };

  function endResizing( e ) {
    
    // use a while loop to make sure that multiple listeners get removed
    while( YUE.removeListener( _elMapViewport, "mousemove", whileResizing ) );

    _setState( STATE_SELECTED );
		_setCursorValue("default");

		//    _updateCurrentSelectionInfo();

    // null out all values just to be clean
    _resizeMouseStartLeft = null;
    _resizeMouseStartTop = null;
    _resizeStartLeft = null;
    _resizeStartTop = null;
    _resizeStartHeight = null;
    _resizeStartWidth = null;
    _resizeMoveLeft = null;
    _resizeMoveTop = null;
    _resizingWidth = null;
    _resizingHeight = null;

  };


  function _setSelectAreaWidth( width ) {
    _elSelectAreaStyle.width = width + "px";

    if( width > 130 ){
      _elPriceometer.style.width = width + "px";
    } else {
      _elPriceometer.style.width = "130px";
    }


  };





  // ************************************************
  //  END EVENT ACTIONS FOR RESIZING THE SELECT AREA
  // ************************************************



  // ************************************
  //  EVENT ACTIONS WHILE SELECTING AREA
  // ************************************

  function startSelectArea( e ) {
    // assumes zoom level of the map is zero
    
		YAHOO.log( "start selecting map area" );

    _selectionStart = _oMap.getGridXY( e );

    _setState( STATE_SELECTING );
        
    // draw a square over the area
    if( !_elSelectArea ) {
      var elSelectArea = _createSelectAreaElement();
      _oMap.addOverlayElement( elSelectArea );
    }
  };

  function whileSelectArea( e ) {
    var curPos = _oMap.getGridXY( e );

    _drawSelectArea( curPos, _selectionStart );
  };


  function endSelectArea( e ) {

		YAHOO.log( "done selecting map area" );

    _setState( STATE_SELECTED );

    // figure out which square the selection ended on
    var begin = _selectionStart;
    var end = _oMap.getGridXY( e );
    
    // draw something over the selected area
    _drawSelectArea( begin, end );

    // update the selected area data and open the upload dialog
		//    _updateCurrentSelectionInfo();

    //gOriginalUploadImageDialog.show();

  };

  // ****************************************
  //  END EVENT ACTIONS WHILE SELECTING AREA
  // ****************************************


  // **********************
  //    NEW IMAGE UPLOAD
  // **********************

  function selectAreaForImage( elImg, imgLocation ) {
    
    if( _elSelectArea ){
      // purge the old select area info
      _destroy()
 }

		_setState( STATE_SELECTED );

    _imgLocation = imgLocation;
    _imgUrl =  _proxy_jslib_handle(elImg, 'src', '', 0, 0);
    var curWidth = _imgOriginalWidth = elImg.width;
    var curHeight = _imgOriginalHeight = elImg.height;

		// if image dimensions are not multiples of 10, round to the nearest 10
		var squareSize = SQUARE_SIZE_PIXELS;
		if( _imgOriginalWidth % squareSize != 0){
			elImg.width = curWidth = Math.round(_imgOriginalWidth / squareSize) * squareSize;
		}
		if( _imgOriginalHeight % squareSize != 0 ){
			elImg.height = curHeight = Math.round(_imgOriginalHeight / squareSize) * squareSize;
		}

    // $$$$$ resize the image if it is too large to fit in the viewport

    // compute where to position the image so that it is in the center of the visible map
    var mapCenter = _oMap.getVisibleMapCenter();

    var imgPosX = Math.round((mapCenter[0] - curWidth/2) / squareSize);
    var imgPosY = Math.round((mapCenter[1] - curHeight/2) / squareSize);
    
    var begin = [imgPosX,imgPosY];
    var end = [imgPosX + curWidth / SQUARE_SIZE_PIXELS,
               imgPosY + curHeight / SQUARE_SIZE_PIXELS];

    var elSelectArea = _createSelectAreaElement(_imgUrl);
    _drawSelectArea( begin, end );
    _oMap.addOverlayElement( elSelectArea );

    var price = _computePrice( curWidth, curHeight );
    if( price > DEFAULT_PRICE_TARGET ){
      resizeByPrice( DEFAULT_PRICE_TARGET, elSelectArea );
    }

    _updatePriceDisplay();
		centerSelectAreaInMapViewport();

    _oMap.beginMapSelectDisplay();

  };

    
  function centerSelectAreaInMapViewport() {

		if( isSelected() ){

			// $$$$$ this logic might belong in the map class instead.  whatever
			
			var info = getSelectAreaInfo();
			var mapCenter = _oMap.getVisibleMapCenter();
			
			var newLeft = Math.round((mapCenter[0] - info.width/2) / SQUARE_SIZE_PIXELS) * SQUARE_SIZE_PIXELS;
			var newTop = Math.round((mapCenter[1] - info.height/2) / SQUARE_SIZE_PIXELS) * SQUARE_SIZE_PIXELS;
			
			 _proxy_jslib_assign('', _elSelectAreaStyle, 'top', '=', ( newTop + "px"));
			_elSelectAreaStyle.left = newLeft + "px";
		}

  };


  function _updatePriceDisplay() {
    
    var info = getSelectAreaInfo();
    var price = getPriceDisplay( info.width, info.height );
     _proxy_jslib_assign('', _elPrice, 'innerHTML', '=', ( price));
  };



	function resizeToPriceUI() {

		// resizes the image selection to approximately the price entered by the user in the UI
		var elPrice = $("priceResize");
    var priceStr =  _proxy_jslib_handle(elPrice, 'value', '', 0, 0);
		var priceNum = parseFloat( priceStr );

    if( priceStr == "" ){
			restoreOriginalSize();
    } else if( !isNaN(priceNum) ){
			resizeByPrice( priceNum );
		} else {
			alert("Please enter a number in the box only");
			 _proxy_jslib_assign('', elPrice, 'value', '=', ( ""));
		}

	}
	
	function restoreOriginalSize() {

		 _proxy_jslib_assign('', $("priceResize"), 'value', '=', ( ""));

		_elSelectAreaStyle.height = _imgOriginalHeight + "px";
    //		_elSelectAreaStyle.width =  _imgOriginalWidth + "px";
    _setSelectAreaWidth( _imgOriginalWidth );

    centerSelectAreaInMapViewport();
    _updatePriceDisplay();
	}


  function resizeByPrice( targetPrice ) {

		var newSize = _computeSizeForPrice( targetPrice );

    _elSelectAreaStyle.height = newSize[1] + "px";
    //    _elSelectAreaStyle.width = newSize[0] + "px"; 
    _setSelectAreaWidth(newSize[0]);


		//    centerSelectAreaInMapViewport();
    _updatePriceDisplay();

  }



 	function makeBigger() {

		// blank out the free form price editing to prevent price confusion while resizing
		 _proxy_jslib_assign('', $("priceResize"), 'value', '=', ( ""));

		// get current size
		var info = getSelectAreaInfo();
		var curWidth = info.width;
		var curHeight = info.height;

		// get current price
		var curPriceNum = _computePrice( info.width, info.height );

		// keep incrementing the price until the size changes
		var newPrice = curPriceNum;
		var newWidth = curWidth;
		var newHeight = curHeight;
		while( newWidth == curWidth && newHeight == curHeight ){
			newPrice = Math.floor(newPrice) + 1;

			var newSize = _computeSizeForPrice( newPrice );
			newWidth = newSize[0];
			newHeight = newSize[1];
		}

		_hidePriceEdit();
		
		resizeByPrice( newPrice );
	};


	function makeSmaller() {
		// blank out the free form price editing to prevent price confusion while resizing
		 _proxy_jslib_assign('', $("priceResize"), 'value', '=', ( ""));

		// get current size
		var info = getSelectAreaInfo();
		var curWidth = info.width;
		var curHeight = info.height;

		// get current price
		var curPriceNum = _computePrice( info.width, info.height );

		// keep incrementing the price until the size changes
		var newPrice = curPriceNum;
		var newWidth = curWidth;
		var newHeight = curHeight;
		var lastPrice = newPrice;
		while( newPrice > 0 && newWidth == curWidth && newHeight == curHeight ){
			lastPrice = newPrice;
			newPrice = Math.ceil( newPrice ) - 1;
			var newSize = _computeSizeForPrice( newPrice );
			newWidth = newSize[0];
			newHeight = newSize[1];
		}
		
		if( newPrice <= 0 ){
			newPrice = lastPrice;
		}

		_hidePriceEdit();

		resizeByPrice( newPrice );
	};



	function _computeSizeForPrice( targetPrice ) {
		var originalWidthSquares = _imgOriginalWidth / SQUARE_SIZE_PIXELS;
    var originalHeightSquares = _imgOriginalHeight / SQUARE_SIZE_PIXELS;

    // computed this with fancy algebra using these two equations:
    //    1.   orignalWidthSquares / orignalHeightSquares = newHeight / newWidth
    //    2.   newHeight * newWidth * price = targetPrice
    // Had to round height to the nearest integer to keep the proportion as close as possible

    // raw values can be fractional
    var newHeightSquaresRaw = Math.sqrt( targetPrice * originalHeightSquares / originalWidthSquares / gPricePerSquare );
    var newWidthSquaresRaw = targetPrice / newHeightSquaresRaw / gPricePerSquare;
    
    var newWidthPixels = Math.round( newWidthSquaresRaw ) * SQUARE_SIZE_PIXELS;
    var newHeightPixels = Math.round( newHeightSquaresRaw ) * SQUARE_SIZE_PIXELS;

		return [newWidthPixels, newHeightPixels];
	}





  function _computePrice( widthPixels, heightPixels ) {
    var widthSquares = widthPixels / SQUARE_SIZE_PIXELS;
    var heightSquares = heightPixels / SQUARE_SIZE_PIXELS;

    return Math.round(widthSquares * heightSquares * gPricePerSquare * 100) / 100;
  };


  function getPriceDisplay( widthPixels, heightPixels ) {
    var price = _computePrice( widthPixels, heightPixels );
    var dollars = Math.floor(price);
    var cents = Math.floor((price * 100) % 100);
    if( cents == 0 ){
       cents = "00";
    }
    return dollars + "." + cents;
  };


  // **************************
  //    END NEW IMAGE UPLOAD
  // **************************

  
  return {
		getPriceDisplay: getPriceDisplay,
			isSelecting : isSelecting,
			isSelected : isSelected,
			clear : clear,
			init : init,
			isResizing : isResizing,
			endResizing : endResizing,
			whileSelectArea : whileSelectArea,
			startSelectArea : startSelectArea,
			endSelectArea : endSelectArea,
			isSelectAreaElement : isSelectAreaElement,
			getCursorValue : getCursorValue,
			selectAreaForImage : selectAreaForImage,
			getImageUrl : getImageUrl,
                       getSelectAreaInfo : getSelectAreaInfo,
			centerSelectAreaInMapViewport : centerSelectAreaInMapViewport,
			resizeToPriceUI: resizeToPriceUI,
			restoreOriginalSize : restoreOriginalSize,
			makeBigger : makeBigger,
			makeSmaller : makeSmaller
 };
  
}();
 ;
_proxy_jslib_flush_write_buffers() ;