var hpIas = null; // imgAreaSelect instance

function f_makeSimpleAjaxPost(p_url, p_data, success_cb, error_cb) {
  if( !error_cb ) {
    var error_cb = null;
  }
  $.ajax({ type: "POST", url: p_url, data: p_data, error: error_cb, success: success_cb, dataType: "xml" });
}

function f_makeSimpleAjaxGet(p_url, p_data, success_cb) {
  $.ajax({ type: "GET", url: p_url, data: p_data, success: success_cb, dataType: "xml", error: f_ajax_error });
}

function f_ajax_error(XMLHttpRequest, textStatus, errorThrown) {
  alert("Error: " + XMLHttpRequest.responseText + "\n" +
    textStatus + "\n" + errorThrown);
}

/**** DOCUMENT READY *********/

$(document).ready(function () {
  if( is_admin ) { // is_admin global set in admin.php
    var crop_select_x1 = $('#photo-crop-x1');
    var crop_select_x2 = $('#photo-crop-x2');
    var crop_select_y1 = $('#photo-crop-y1');
    var crop_select_y2 = $('#photo-crop-y2');
    var crop_select_w = $('#photo-crop-w');
    var crop_select_h = $('#photo-crop-h');

    var bricks = $('div.brick, div.large-brick');
    
    bricks.click(function () {
      var img = $(this).children('img');
      var timestamp = new Date().getTime(); // because image may have been cropped, ensure refresh of image
      var ratio = "1.45:1";
      var is_large = $('#photo-is-large');
      var img_id = img.attr('id');
      var url = $('#'+img_id+'_link');
      var url_val = "";
      
      if( url.length ) {
        url_val = url.text();
      }
      
      if( $(this).hasClass('large-brick') ) {
        ratio = "1.46:1";
        is_large.val('1');
      }
      else {
        is_large.val('0');
      }

      $('#photo-detail-id').val(img_id);
      $('#photo-url').val(url_val);

      $('#photo-crop-img').attr('src',img.attr('src') + '?' + timestamp).load(function () {
        $.fn.colorbox({
          inline: true,
          href: '#photo-update',
          onComplete: function () {
            if( hpIas == null ) {
              hpIas = $('#photo-crop-img').imgAreaSelect({
                aspectRatio: ratio,
                instance: true,
                hide: true,
                zIndex: 999999,
                onSelectChange: function(img, selection) {
                  crop_select_x1.val(selection.x1);
                  crop_select_y1.val(selection.y1);
                  crop_select_x2.val(selection.x2);
                  crop_select_y2.val(selection.y2);
                  crop_select_w.val(selection.width);
                  crop_select_h.val(selection.height);
                }
              }); // end imgAreaSelect
            }
            else {
              hpIas.setOptions({ aspectRatio: ratio });
            }
          },
          onCleanup: function () {
            hpIas.setOptions({ hide: true });
            crop_select_x1.val("-1");
            crop_select_x2.val("-1");
            crop_select_y1.val("-1");
            crop_select_y2.val("-1");
            crop_select_w.val("-1");
            crop_select_h.val("-1");
          }
        }); // end fn.colorbox
      }); // end photo-crop-img load
    }); // end bricks.click
    
    $('#photo-detail').submit(function () {
      var pId = $('#photo-detail-id').val();
      var pUrl = $('#photo-url').val();
      var pIsLarge = $('#photo-is-large').val();
      $('#photo-detail-submit').attr('disabled','disabled');    
      $('#photo-crop-spinner').show();

      f_makeSimpleAjaxPost("include/crop_resize_intro_image.php", {
        id: pId,
        url: pUrl,
        is_large: pIsLarge,
        x1: crop_select_x1.val(),
        x2: crop_select_x2.val(),
        y1: crop_select_y1.val(),
        y2: crop_select_y2.val(),
        width: crop_select_w.val(),
        height: crop_select_h.val()
      },
      function (data, textStatus, xHR) {
        var response = $(data).children('response');
        if( response.children('success').eq(0).length ) {
          var photo_id = $.trim($(response).children('photo_id').text());
          var photo_url = $.trim($(response).children('url').text());
          var path = $.trim($(response).children('path').text());
          var file = $.trim($(response).children('photo_name').text());
          var timestamp = new Date().getTime(); // because image may have been cropped, ensure refresh of image
          var img_src = path + file + '?' + timestamp;

          if( $.trim($(response).children('crop').text()) == "yes" ) {
            // update image in popup and on main page
            $('#photo-crop-img').attr('src',img_src);

            timestamp = new Date().getTime();
            img_src = path + file + '?' + timestamp;

            $('#' + photo_id).attr('src',img_src);
          }

          $('#' + photo_id + '_link').text(photo_url);

          $('#photo-crop-spinner').hide();
          $('#photo-crop-updated').fadeIn('fast',function () {
            setTimeout("$('#photo-crop-updated').fadeOut('slow')",1000);
          });
        }
        else {
          // handle error here ('error:' above handles transport/parser errors, here we handle any errors trapped by our php script)
          var err = $.trim(response.children('error').text());
          alert(err);
        }
        $('#photo-detail-submit').removeAttr('disabled');
        $('#photo-crop-spinner').hide();
      },
      function (xHR, textStatus, errorThrown) {
        $('#photo-detail-submit').removeAttr('disabled');
        $('#photo-crop-spinner').hide();
      });
      return false;
    });

    /****** UPLOAD PHOTO *******/
    new AjaxUpload($('#upload-photo'), {
      action: "include/upload_home_photo.php",
      name: 'uploadfile',
      onSubmit: function(file, ext) {
        if( ! (ext && /^(jpg|png|jpeg|gif)$/.test(ext)) ) {
          $('#upload-status').text('Only JPG, PNG, or GIF files are allowed');
          return false;
        }
        this.setData({
          id: $('#photo-detail-id').val(),
          is_large: $('#photo-is-large').val()
        });
        $('#upload-status').text("Uploading...");
      },
      onComplete: function(file, data) {
        var response = $(data).children('response');
        $('#upload-status').text("");
        if( $(response).children('success').length ) {
          var photo_id = $.trim($(response).children('photo_id').text());
          var path = $.trim($(response).children('path').text());
          var file = $.trim($(response).children('photo_name').text());
          var timestamp = new Date().getTime(); // because image may have been cropped, ensure refresh of image
          var img_src = path + file + '?' + timestamp;

          // update image in popup and on main page
          $('#photo-crop-img').attr('src',img_src);
          $('#' + photo_id).attr('src',img_src);
        }
        else {
          if( $(response).children('error').length ) {
            alert($.trim($(response).children('error').text()));
          }
          else {
            alert(data);
          }
        }
      }
    });
  } // end if is_admin
}); // end document.ready
