$(document).ready(function() {

  if (isUserLoggedIn()) {
    new AjaxUpload('#recipe_image_button', {
      // Location of the server-side upload script
      // NOTE: You are not allowed to upload files to another domain
      action: '/user/recipeimageupload',
      // File upload name
      name: 'userrecipeimage',
      // Additional data to send
      data: {
        recipe_id : $('#recipe_id').val()
      },
      // Submit file after selection
      autoSubmit: true,
      title: 'Add a photo',
      // The type of data that you're expecting back from the server.
      // HTML (text) and XML are detected automatically.
      // Useful when you are using JSON data as a response, set to "json" in that case.
      // Also set server response type to text/html, otherwise it will not work in IE6
      responseType: "json",
      onSubmit: function(file , ext) {

        if (! (ext && /^(jpg|png|jpeg|bmp)$/i.test(ext))){
          // extension is not allowed
          alert('Yummly supports .jpg and .png image files. Please try a valid image file.');
          // cancel upload
          return false;
        }
        else {
          var recipeBubble = $('#image-bubble');

          var currDate = new Date();
          $.getJSON("/login/ajaxLoggedIn", {}, function(json) {
            if (json.loggedIn) {
              GA.trackPageview('recipe/imageUpload');
              $.nui.waitStart({content:'Uploading Photo...', object:$(recipeBubble)});
            } else {
              $.nui.windowOpen({title:'Log In to Yummly', url:'/window/auth'});
              return false;
            }
          });
        }
      },
      onComplete: function(file, response) {
        $.nui.waitStop();
        $.handleImageStep2(file, response);
      }
    });
  } else {
    $('#recipe_image_button').click($.displayLoginDialog);
  }
});

$.handleImageStep2 = function(file, response) {
  //$('#recipe-photo-div').css("background-image", "url("+response.filename+")");
  $.nui.windowOpen({
    maxWidth:'1024px',
    onOpen: function() {
      $.initializeRecipeImageModal(response);
    },
    title:'Upload Picture',
    url:'/window/addrecipeimage'
  });
};

$.initializeRecipeImageModal = function(response) {

  var html = [];

  html.push(
    '<img src="'+response.filename+'" height="'+response.height+'" width="'+response.width+'" id="recipe-cropbox" border="0" /><div class="yummly-divider"></div><a class="nui-button nui-submit" href="#" id="image_save">Crop and Save</a>'
    ,'<form>'
    ,'<input type="hidden" name="x1" id="x1" value="0" />'
    ,'<input type="hidden" name="x1" id="y1" value="0" />'
    ,'<input type="hidden" name="x1" id="x2" value="720" />'
    ,'<input type="hidden" name="x1" id="y2" value="480" />'
    ,'<input type="hidden" name="originalFilename" id="originalFilename" value="'+response.filename+'" />'
    ,'</form>'
  );

  $('#recipe-image-modal').html(html.join(''));
  $('#recipe-cropbox').Jcrop({
    bgColor:     'black',
    bgOpacity:   .4,
    setSelect:   [ 0, 0, 720, 480 ],
    aspectRatio: 1.5,
    onSelect : saveCoords,
    allowSelect: false,
    allowResize: false
  });


  $('#image_save').click(function(event) {
    var recipeBubble = $('#recipe-image-modal');
    $.nui.waitStart({content:'Cropping and Saving Photo...', object:$(recipeBubble)});
    event.preventDefault();
    var x1 = $('#x1').val();
    var y1 = $('#y1').val();
    var x2 = $('#x2').val();
    var y2 = $('#y2').val();

    $.postJSON("/user/recipeimagecrop", {x1 : x1, y1 : y1, x2 : x2, y2 : y2, recipe_id : $('#recipe_id').val(), filename : $('#originalFilename').val() }, function(json) {
      if (json.success) {
        //$('#recipe-photo-div').css('background-image', 'url('+json.filename+')');
        
        $("#recipe-photo-div").attr("src", json.filename);
        $.nui.waitStop();
        $.nui.windowClose('.nui-window-frame-content');
      }
      else {
        $.nui.windowClose('.nui-window-frame-content');
        var errorHTML = [];

        errorHTML.push(
          'Unable to add your image at this time.'
        );
        $('#recipe-image-modal').html(errorHTML.join(''));
      }

    });

    //alert('x1: ' + x1 + ' y1: ' + y1 + ' x2: ' + x2 + ' y2: ' + y2);
  });
  
  $('#image_cancel').click(function(event) {
    event.preventDefault();
    $.nui.windowClose();
  });
  $.nui.framePosition();
}

function saveCoords(c) {
  $('#x1').val(c.x);
  $('#y1').val(c.y);
  $('#x2').val(c.x2);
  $('#y2').val(c.y2);
}

