


// constructs a new image that a user wants to put in beboland

var gNewImage = function(){
  
  var _imgLocation = null;  // file location string for the image stored in the database
  var _imgUrl = null;
  var _elImg = null;

  var _lastError = null;

  // used to keep track of timestamps from uploads so that they do not execute twice if the user hits the backbutton
  var _uploadTimestampRecord = {};  


  function displayLastError(){
    var errorWindow = window.open( "about:blank", "error_window" );
    errorWindow.document.write( _lastError );
  }



  function createNewImage( url, imgLocation ){

    // make a new image objet pointing at that URL
    var img = document.createElement("IMG");
    YUE.addListener(img, "error", _onImgError);
    YUE.addListener(img, "load", _onImgLoad);
    img.src = url;
    
    _imgLocation = imgLocation || null;
    _imgUrl = url;
    _elImg = img;
  };


// 	function getTempImageByUrl(){
// 		var input = $("tempImageUrl");
// 		if( input.value == "" ){
// 			alert( "Please enter a URL into the box." );
// 		} else {
//       $("downloadingUrlMessage").style.display = "block";
// 			createNewImage( input.value );
// 		}
// 	}


  function _testTimestampRecord( timestamp ){
    if( _uploadTimestampRecord[timestamp] ){
      //      alert( "timestamp " + timestamp + " found in record");
      return true;
    } else {
      // add the timestamp to the record
      //      alert("adding timestamp " + timestamp + " to record");
      _uploadTimestampRecord[ timestamp ] = true;
      return false;
    }
  };
    

  function handleUploadResponse(responseObj, timestamp){

    // see if the timestamp has already been used
    if( _testTimestampRecord( timestamp ) ){
      // i wanted to put a history.back() call here, but I realized that the user may have hit the forward button to get here too.
      return;
    } 

    try {
			if( responseObj.errors != false ) {

        // hack: map was locked to prevent history manager from taking action after the upload iframe submit
				gMap.unlockMap();
				
				// see if the error is the user not being logged in
				if( responseObj.errors[0] == "401 Unauthorized" ){
					gNewImageProcess.showLoginScreen();
				} else {
					gNewImageProcess.showErrorScreen(responseObj.errors.join("\n"));
				}
			}
			else {

        // taking out the private profile warning because it is confusing since the user can link to a band or group too.
//         if( !responseObj.publicProflie){
//           alert("We noticed your profile is currently set to private.   People will not be able to see your profile when they click your image.\n\nYou can make your proflie public by clicking the \"Edit Profile\" link on your profile page.");  // i18n
//         }

				var newImg = createNewImage("http://" + responseObj.fileUrl, responseObj.fileLocation);
				gNewImageProcess.showLoadingPanel();

			}
			
    } catch( e ){
      // Assuming that an error occurred because an HTML error docuemnt was returned

      // hack: map was locked to prevent history manager from taking action after the upload iframe submit
      gMap.unlockMap();

      _lastError = reponseObj.responseText;
      gNewImageProcess.showErrorScreen( "<div>The response from the server could not be parsed.</div><div style='color:blue;font-decoration:underline' onclick='gNewImage.displayLastError()'>See Error Response</div>.");  // i18n
    }
  };

	




  function confirmPlacement(){
    var info = gMapSelect.getSelectAreaInfo();
    if( gMap.isAreaInBounds( info.x, info.y, info.width, info.height ) ){
      // fetch the list of IDs that the use is a moderator for so that they can choose which profile to link to
      getModeratorList();
    } else {
      gNewImageProcess.showOutOfBoundsPanel();
    }
  };


  function getModeratorList(){
    var jsonrpcCallback = { success: _getModeratorListCallback,
                            failure: _getModeratorListCallback};
    JSON_RPC.send(jsonrpcCallback, "BeboNation.getModeratorList", null);
  };

  function _getModeratorListCallback( responseObj ){

    if( responseObj.error ){
			if( responseObj.error == "401 Unauthorized" ){
				gNewImageProcess.showLoginScreen();
			} else {
				gNewImageProcess.showErrorScreen("<div>" + responseObj.error + "</div>");  // $$$$$ terrible message
			}
    } else {

      var elConfirmLinkToRow = $("confirmLinkToRow");
      var elConfirmLinkToBox = $("confirmLinkToBox");

      if( responseObj.length == 0 ){
        elConfirmLinkToRow.style.display = "none";
      } else if ( responseObj.length == 1){ 
        elConfirmLinkToBox.innerHTML = "Your Profile"; // $$$$$ i18n
      } else {
        // build the select box to choose where the image will link to
        var options = [];
        options[0] = "<option value='EMPTY'>--Please choose--</option>";

        for( var i=0; i < responseObj.length; i++){
          var moderatorInfo = responseObj[i];
          var moderatorId = moderatorInfo.member_id;
          var displayName = moderatorInfo.display_name;
          var userName = moderatorInfo.username;
          options[options.length] = "<option value='" + moderatorId + "'>" + displayName + "</option>";
        }
        elConfirmLinkToBox.innerHTML = "<select id='confirmLinkToSelect' autocomplete='off'>" + options.join("") + "</select>";
        if( gIsIE ){
          elConfirmLinkToRow.style.display = "inline";
        } else {
          elConfirmLinkToRow.style.display = "table-row";
        }
      }

        
      // show the confirm image panel if the image is still in bounds  (checking boundaries again just to be safe)
      var info = gMapSelect.getSelectAreaInfo();
      var sizeStr = info.width + " x " + info.height + " pixels";
      var locationStr = "(" + info.x + " , " + info.y + ")";
      var priceStr = "$" + gMapSelect.getPriceDisplay( info.width, info.height ) + " USD";
      if( gMap.isAreaInBounds( info.x, info.y, info.width, info.height ) ){
        gNewImageProcess.showConfirmPanel( sizeStr, locationStr, priceStr );
      } else {
        gNewImageProcess.showOutOfBoundsPanel();
      }
    }
  };


  function placeOrder(){

    var info = gMapSelect.getSelectAreaInfo();
    if( gMap.isAreaInBounds( info.x, info.y, info.width, info.height ) ){

      var elLinkToSelect = $("confirmLinkToSelect");

      var linkToId = "";  // empty string causes a default to the logged in member id.  (note, not using null because I cant figure it out right now)
      if( elLinkToSelect ){
        var linkToId = elLinkToSelect.options[elLinkToSelect.options.selectedIndex].value;
        if( linkToId == "EMPTY" ){
          alert("Please choose the profile for users to see when they click on your map image.");  // i18n
          return;
        }
      }

      var jsonrpcCallback = { success: _placeOrderSuccessCallback,
                              failure: _placeOrderFailureCallback };
      
      JSON_RPC.send( jsonrpcCallback, "BeboNation.placeOrder",
                     info.x,
                     info.y,
                     info.width,
                     info.height,
                     info.imgOriginalWidth,
                     info.imgOriginalHeight,
                     info.imgUrl,
                     info.imgLocation,
                     linkToId);
      
			gNewImageProcess.showLoadingPanel();
      gNewImageProcess.hideConfirmPanel();
    } else {
			gNewImageProcess.hideLoadingPanel();
      gNewImageProcess.showOutOfBoundsPanel();
    }
  };




  function _placeOrderSuccessCallback( responseObj ){

    // $$$$$ development $$$$$
//     if( typeof(responseObj.jsUrl) != "undefined" ){
//       var scriptTag = document.createElement( "SCRIPT" );
//       scriptTag.src = "http://" + responseObj.jsUrl;
//       document.body.appendChild( scriptTag );
//       gNewImageProcess.showStartScreen();
//       return;
//     }
    // $$$$$ development $$$$$

    if( responseObj.success === true ){
			// go to the checkout screen
			gApp.navigatePage( responseObj.nextPage );
    } else {
			gNewImageProcess.hideLoadingPanel();
      gNewImageProcess.showErrorScreen(responseObj);
    }
  };
  
  function _placeOrderFailureCallback( responseObj ){
    var errorObj = responseObj.error;
		gNewImageProcess.hideLoadingPanel();
    if( errorObj == "401 Unauthorized" ){
      gNewImageProcess.showLoginScreen();
    } else {
      
      if( typeof(responseObj.conflictImage) != "undefined" ) {
        var conflictInfo = responseObj.conflictImage;
        
        var minGridX = conflictInfo.x_nbr;
        var maxGridX = conflictInfo.max_x_nbr;
        var minGridY = conflictInfo.y_nbr;
        var maxGridY = conflictInfo.max_y_nbr;

        // show the conflict on the map
        gMap.highlightSquares( minGridX, maxGridX, minGridY, maxGridY, true, "#ff0000" );

				gNewImageProcess.showOverlapPanel();
      } else if( typeof(responseObj.outOfBounds) != "undefined" ) {
        if( responseObj.outOfBounds ){
          gNewImageProcess.showOutOfBoundsPanel();
        }
      } else {
				gNewImageProcess.showErrorScreen( errorObj );
			}
    }
  };


  function _destroyTempImage(){
    // free all memory used by this object

    _elImg = null;
    _imgUrl = null;
    _imgLocation = null;
  };

  
  function cancelPlacement(){
    
    gMapSelect.clear();
    gNewImageProcess.showStartScreen();
  };
    



	// onerror is called when the image fails to load
  function _onImgError(){
    YAHOO.log("new image onerror happened", "error");
		gNewImageProcess.showErrorScreen("<p>The image you chose failed to load.</p><p>If you uploaded your image from your disk, please try again or use a different image.</p><p>If you uploaded your image from a URL, make sure that the URL points to an image file and not a web page.</p>");   // i18n
		_destroyTempImage();

  };
  
  
  // onload is called when the image element loads the image
  function _onImgLoad(e){

    gNewImageProcess.showPlacementScreen();
		gNewImageProcess.hideLoadingPanel();

	};

  function displayTempImage(){
    gMapSelect.selectAreaForImage( _elImg, _imgLocation );
    _destroyTempImage();
  };



  return {
    //  getTempImageByUrl:getTempImageByUrl,
			createNewImage: createNewImage,
                      //			uploadNewImage: uploadNewImage,
			confirmPlacement: confirmPlacement,
			cancelPlacement: cancelPlacement,
			placeOrder: placeOrder,
			displayTempImage : displayTempImage,
			displayLastError : displayLastError,
			handleUploadResponse:handleUploadResponse
			};
  
}();




// ***************
//   DDTickMover
// ***************

// var DDTickMover = function( id, sGroup, config ){
// 	this.tickSize = 10;
	
// 	// used for caching where event occurred
// 	this._startDragEventX = null;
// 	this._startDragEventY = null;
	
// 	// used for caching current position of element
// 	this._elLastX = null;   // cache last x position of the element
// 	this._elLastY = null;   // cache last y position of the element

// 	if( id ) {
//     this.init( id, sGroup, config );
//     this.logger = this.logger || YAHOO;
//   }
// };
// YAHOO.lang.extend( DDTickMover, YAHOO.util.DD );


// DDTickMover.prototype.b4MouseDown = function(e){
// 	// cache where the event started
// 	var eventPos = YUE.getXY(e);
// 	this._startDragEventX = eventPos[0];
// 	this._startDragEventY = eventPos[1];
	
// 	// cache the current position of the element
// 	var elPos = YAHOO.util.Dom.getXY(this.getEl());
// 	this._elLastX = elPos[0];
// 	this._elLastY = elPos[1];
	
// 	DDTickMover.superclass.b4MouseDown.call(this,e);
// };


// DDTickMover.prototype.b4Drag = function(e){
	
// 	// cache start drag event position
// 	var startX = this._startDragEventX;
// 	var startY = this._startDragEventY;

// 	// get the current position of the event
// 	var eventPos = YUE.getXY(e);
	
// 	// figure out the delta
// 	var deltaX = eventPos[0] - startX;
// 	var deltaY = eventPos[1] - startY;
	
// 	var newLeft = startX + (Math.floor( deltaX / this.tickSize ) * this.tickSize);
// 	var newTop = startY + (Math.floor( deltaY / this.tickSize ) * this.tickSize);

// 	if( newLeft != this._elLastX || newTop != this._elLastY ){
// 		this.setDragElPos(newLeft, newTop);
// 		this._elLastX = newLeft;
// 		this._elLastY = newTop;
// 	}
// };


// interesting, the ondrag still fires even if the object didnt move
// DDTickMover.prototype.onDrag = function(e){
// 	YAHOO.log("onDrag");
// }
	
// DDTickMover.prototype.endDrag = function(e){
// 	YAHOO.log("endDrag");

// 	// null out cached fields
// 	this._startDragEventX = null;
// 	this._startDragEventY = null;
// 	this._elLastX = null;
// 	this._elLastY = null;

// 	DDTickMover.superclass.endDrag.call(this, e);
// }	

// *********************
//    END DDTickMover
// *********************

