function tag_this(data) {
  $('#thumbnail').css('cursor', 'move');
  $('#thumbnail').imgAreaSelect({ aspectRatio: '1:1', enable: true, outerColor: '', onSelectChange: preview });
  //$('#thumbnail').imgAreaSelect({ aspectRatio: '1:1', enable: true, outerColor: '', onSelectChange: preview, movable: true, resizable: false, maxWidth: 100, maxHeight: 100, minWidth: 100, minHeight: 100, show: true });
  $('#tagphoto').css('display', 'none');
  $('#done_tagging').css('display', 'block');
  tag_autocomlete(data);
}

function preview(img, selection) {
  $('#x1').val(selection.x1);
  $('#y1').val(selection.y1);
  $('#x2').val(selection.x2);
  $('#y2').val(selection.y2);
  $('#w').val(selection.width);
  $('#h').val(selection.height);
  var l_eft = 163;
  var t_op = 220;
  $('#tag_form').css({
    position: 'absolute',
    left: parseInt(selection.x1 + l_eft)+ 'px',
    top: parseInt(selection.y2 + t_op) + 'px',
    display: 'block'
  });
}

function tag_cancel() {
  $('#tag_form').css({display: 'none'});
  $('#tag').val('');
  $('#thumbnail').imgAreaSelect({ hide: true });
  
}

function tag_complete(data) {
  $('#thumbnail').css('cursor', 'pointer');
  $('#thumbnail').imgAreaSelect({ disable: true, hide: true });
  $('#tag_form').css({display: 'none'});
  $('#tag').val('');
  $('#tagphoto').show();
  $('#done_tagging').hide();
}

function tag_save() {
  var x1 = $('#x1').val();
  var y1 = $('#y1').val();
  var x2 = $('#x2').val();
  var y2 = $('#y2').val();
  var w = $('#w').val();
  var h = $('#h').val();
  var tag = $('#tag').val();
  var cid = $('#cid').val();
  var ccid = $('#ccid').val();
  var user_id = $('#user_id').val();
  if(x1=="" || y1=="" || x2=="" || y2=="" || w=="" || h==""){
    alert("You must make a selection first");
    return false;
  }
  else if ( tag == '' ) {
    alert("Please enter a tag");
    return false;
  }
  else{
    save_photo_tag(x1, y1, w, h, tag, cid, ccid, user_id);
    $('#thumbnail').imgAreaSelect({ hide: true }); 
    $('#tag_form').css({display: 'none'});
    $('#tag').val('');
  }
}

function save_photo_tag(x1, y1, w, h, tag, cid, ccid) {
  $.get(
    base_url+'/ajax/save_photo_tag.php',
    {
      'x1':x1,
      'y1':y1,
      'w':w,
      'h':h,
      'tag':tag,
      'cid':cid,
      'album_id':ccid,
      'random': (new Date().getTime())
    },
    function(htmlData) {
      if ( htmlData == 'Please enter a tag' ) {
        alert(htmlData);
      }
      else {
        $('#phototags').css('display', 'block');
        $('#photopipe').css('display', 'block');
        $('#photo_parent').html(htmlData);
      }
    }     
  );  
}

function tag_autocomlete(data) {
  lookupLocal();
  $("#tag").autocompleteArray(
    data,
    {
      delay:10,
      minChars:1,
      matchSubset:1,
      autoFill:false,
      height:200
//      maxItemsToShow:10
    }
  )
}

function lookupLocal(){
  var oSuggest = $("#tag")[0].autocompleter;
  return false;
}