function isPost(requestType) {
  return requestType.toLowerCase() == 'post';
}

$(document).ajaxSend(function(event, xhr, settings) {
  xhr.setRequestHeader("Accept", "text/javascript, application/javascript");     
});



$(function() {
  $(window).load( function() { 
    updateSize(); 
    setResizable();  
  });	
	
  function updateSize() {
    $("#height").text($("form img:first").height());
    $("#width").text($("form img:first").width());
  }

  function updateCoordinates(c) {
    if(c.w === 0) {
      $("#x1, #y1, #x2, #y2").removeAttr("value");    
    }
    else {
      $("#x1").val(c.x);
      $("#y1").val(c.y);    
      $("#x2").val(c.x2);
      $("#y2").val(c.y2);
    }
  }  

  function updateDom(response) {
    $(".pop").slideFadeToggle(function() {
      var selectedId = $(":radio:checked").attr("id");
      $("#content").html(response);
      if(selectedId) { 
        $("#" + selectedId).attr("checked", "checked"); 
        setRatio();
      } else {
        $("#crop_form img:first").Jcrop({onSelect: updateCoordinates});
      }
      var u = $("form").attr("action");
      u = u.substring(0, u.lastIndexOf("/"));
      $.getJSON(u, updateImageStats);
      $("form#crop_form").submit(submitCropRequest);
    });
  }

  function submitCropRequest(event) {
    $(":submit").parent().append("<div class='pop'><p>Right now we have 1000 monkeys at 1000 supercomputers working on your file.</p></div>");
    $(".pop").slideFadeToggle(function() {
      $("form").ajaxSubmit({success: updateDom});
    });
    return false;
  }

  function submitEditRequest(event) {
    $("#x").val($("#user").width());
    $("#y").val($("#user").height());
    $(":submit").parent().append("<div class='pop'><p>Right now we have 1000 monkeys at 1000 supercomputers working on your file.</p></div>");
    $(".pop").slideFadeToggle(function() {
      $("form").ajaxSubmit({success: updateImage, dataType: 'json'});
    });
    return false;
  }
  
  function updateImageStats(json) {
    var r = json.resizable_image;
    $("#height").text(r.height);
    $("#width").text(r.width);
    $("#filesize a").text(r.human_size);
    $("#height, #width, #filesize").effect("highlight", {}, 1500);    
  }
  
  function updateImage(json) {
    updateImageStats(json);
    $("form img").attr("src", json.resizable_image.public_filename + "?" + new Date().getTime());
    $("#original").attr("checked", "checked");
    $(".pop").slideFadeToggle(function() { 
      $(".pop").remove();
    });
  }

  function setResizable() {
    $(".resizable").resizable("destroy").resizable({ 
      handles: "e, se, s", 
      ghost: true,
      aspectRatio: $("#preserve_ratio").is(":checked"), 
      helper: "ui-state-highlight", 
      stop: updateSize });
  }

  function basicResize() {
	  var multiplier = parseFloat($("input[name='size']:checked").val());
	  var img = $("#user");
    var hidden = $("#hidden");
	  var naturalWidth = parseInt(hidden.width(), 10);
	  var naturalHeight = parseInt(hidden.height(), 10);

	  img.effect("size", 
		  { to: { width: naturalWidth, height: naturalHeight }
		  }, 250);
	
	  img.effect("size", 
		  { from: { width: naturalWidth, height: naturalHeight },
		    to: { width: naturalWidth * multiplier, height: naturalHeight * multiplier }
		  }, 500, updateSize);
  }

  function showFileSizeInfo() {
    $("#filesizeinfo").fadeIn("slow");
  }

  function hideFileSizeInfo() {
    $("#filesizeinfo").fadeOut("slow");
  }

  function setRatio() {
    var ratio = null;
    var selectedValue = $("input[name='ratio']:checked").val();

    if(selectedValue == $("#square").val()) {
      ratio = 1;
    } 
    else if(selectedValue == $("#same").val()) {
      ratio = parseFloat($("#crop").width() / $("#crop").height());    
    }

    $("#crop").Jcrop({ onSelect: updateCoordinates, aspectRatio: ratio });
  }
  
  $("a[href*='facebook']").click(function() {
    u=location.href;
    t=document.title;
    window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');
    return false;   
  });

  $("input[name='ratio']").live("click", setRatio);
  
  $("#crop_form img:first").Jcrop({onSelect: updateCoordinates});
  $("#filesize a").hover(showFileSizeInfo, hideFileSizeInfo);
  $("form#edit_form").submit(submitEditRequest);
  $("form#crop_form").submit(submitCropRequest);
  $("#preserve_ratio").click(setResizable);
  $("input[name='size']").click(basicResize); 
  $("form#email_form").ajaxForm({
       success: function() {
        $("form img:first").parent().prepend("<div class='pop'><p>Our crack team of 1000 monkeys at 1000 supercomputers just sent your email!</p></div>");
        $(":input, :submit, label, h1, .pop, form img, br").slideFadeToggle();
       }, dataType: 'json'});
       
  $("#image_uploaded_data").change(function() {
    $(".pop").slideFadeToggle();
  });     
       
  $("#image_form").submit(function() {
    if($("#image_uploaded_data").val().length === 0) {
      if($(".pop").length === 0) {
        $(":submit").parent().append("<div class='pop'><p>The monkeys that run Resize Image are pretty good, but they told me you need to pick a file before they get to work.</p></div>");
      }
      if($(".pop:hidden").length) {
        $(".pop").slideFadeToggle();
      } 
      else {
        $(".pop").effect("shake", {}, 100);
      }
      return false;
    }
  });
  
  function hasChanges() { 
    var m = $("form img:first");
    var o = $("form img:last");
    if($("#x1").length) {
      return $("#x1").val().length;
    }
    return  m.width() != o.width() || m.height() != o.height();
  }
  
  $("#menu a").click(function() {
    if(hasChanges()) {
      return confirm("Steve, our top monkey saw that you made some changes. If you stay on this page you can click the 'Save changes' button to save your changes and get rid of this warning.\n\nClick OK to navigate away from this page or Cancel to stay on this page.");    
    }
  });
  
  $("#info a").click(function() {
    if(hasChanges()) {
      return confirm("Hold on! You've made some changes and you're trying to download the image. You probably want to update your image before downloading it. To do this click 'Cancel' and then click the 'Save changes' button. If you want to download your image anyway, click 'OK'.");
    }
  });
  
});

$.fn.showLoading = function() {
    return  this.append($(document.createElement("img"))
      .attr("alt","loading...")
      .attr("src","/images/loading.gif")
      .addClass("loading"));
};


$.fn.slideFadeToggle = function(easing, callback) {
  return this.animate({opacity: 'toggle', height: 'toggle'}, "fast", easing, callback);
};
