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 bricks = $('.home_photo');
		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');    
    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.71:1";
      var img_id = img.attr('id').split('__');
						$('#photo-url').val($('#photos__photo_url__'+img_id[1]).html());
      $('#photo-detail-id').val(img_id[1]);
						$('#photo-file-name').val(img.attr('src'));
      $('#photo-crop-img').attr('src',img.attr('src') + '?' + timestamp).load(function () {
        $.fn.colorbox({
          inline: true,
										maxWidth:1000,
          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 pfna =	$('#photo-file-name').val();
						
						var imgWd = $("#photo-crop-img").width();
						var imgHt = $("#photo-crop-img").height();
						if ( imgWd!=314 && imgHt!=184) {
							 if (  crop_select_w.val() <=0 || crop_select_h.val() <=0  ) {
									alert('Please select/crop Image to upload..');
									return false;
								}							
						}

      $('#photo-detail-submit').attr('disabled','disabled');    
      $('#photo-crop-spinner').show();
      f_makeSimpleAjaxPost("include/crop_resize_intro_image.php", {
        id: pId,
        url: pUrl,
								fn: pfna,
        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__' + photo_id).attr('src',img_src);
          }
          $('#photo-crop-spinner').hide();
          $('#photo-crop-updated').fadeIn('fast',function () {
            setTimeout("$('#photo-crop-updated').fadeOut('slow')",1000);
          });
										setTimeout('window.location.reload()', 3000); 
        }
        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()
        });
        $('#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;
          $('#photo-crop-img').attr('src',img_src);
										$('#photo-file-name').val(path + file);				
        }
        else {
          if( $(response).children('error').length ) {
            alert($.trim($(response).children('error').text()));
          }
          else {
            alert(data);
          }
        }
      }
    });
  } // end if is_admin
}); // end document.ready
