﻿// JScript File

var tagging = false;
var tagging_initialized = false;
var ajax_done = false;
var friends = null;
var superfriends = null;
var frameWidth = 166;
var frameHeight = 166;
var activePersonID = -2;
var activePersonName ='';
var lastActivePersonName ='';
var activeImageMouseX;
var activeImageMouseY;
var pid = 0;
var id = 0;
var idname = "";
var user = 0;
var oid = 0;
var aid = 0;
var ajax_setter_uri = '/ajax/photo_tagging_ajax.php';
var ajax_getter_uri = '/ajax/photos_get_tag_options_ajax.php';
var foundCount = 0;
var lastFoundName = '';
var lastFoundID = 0;

function showBoxAt(percentX, percentY) {
  thePhoto = ge('myphoto');
  if( thePhoto == null )
    alert('null photo');
  thePhotoX = findX(thePhoto);
  thePhotoY = findY(thePhoto);
  
  ge('tagframeinside').innerHTML = "+ " + thePhotoX + "." + thePhotoY + "<br>";
  ge('tagframeinside').innerHTML += "% " + percentX + "." + percentY + "<br>";
  ge('tagframeinside').innerHTML += "d " + thePhoto.width + "." + thePhoto.height + "<br>";
  ge('tagframeinside').innerHTML += '= ' + ((percentX * thePhoto.width)/100) + "." + ((percentY * thePhoto.height)/100) + "<br>";
  
  newX = thePhotoX + ((percentX * thePhoto.width)/100) - (frameWidth/2);
  newY = thePhotoY + ((percentY * thePhoto.height)/100) - (frameHeight/2);
  ge('tagframeinside').innerHTML += "> " + newX + "." + newY;
  ge('tagframeinside').innerHTML = "";
  
  imageMinX = findX(thePhoto);
  imageMinY = findY(thePhoto);
  imageMaxX = imageMinX + thePhoto.width;
  imageMaxY = imageMinY + thePhoto.height;
  
  // Before constraints
  frameX = imageMinX + ((percentX * thePhoto.width)/100);
  frameY = imageMinY + ((percentY * thePhoto.height)/100);
  
  // Apply Constraints
  if(frameX < imageMinX + (frameWidth/2))
    frameX = imageMinX + (frameWidth/2);
  if(frameY < imageMinY + (frameHeight/2))
    frameY = imageMinY + (frameHeight/2);
  if(frameX > imageMaxX - (frameWidth/2))
    frameX = imageMaxX - (frameWidth/2);
  if(frameY > imageMaxY - (frameHeight/2))
    frameY = imageMaxY - (frameHeight/2);
//  alert("+" + frameX + " " + frameY);
  
  // Move and minus 8 for the frame border
  ge('tagframe').style.left = (frameX - (frameWidth/2) - 8) + "px";
  ge('tagframe').style.top = (frameY - (frameHeight/2) - 8) + "px";
  show('tagframe');
}

function hideBox()
{
  hide('tagframe');
}

function showNameFrame(percentX, percentY, context) {
  var snf_image = ge('myphoto');
  var snf_nameFrame = ge('nameframe');
  snf_nameFrame.innerHTML = context;
  snf_nameFrame.style.left = snf_nameFrame.style.top = '-10000px' ;
  show('nameframe');

  var snf_x=Math.min(Math.max((percentX*snf_image.width/100)-frameWidth/2, 0), snf_image.width - frameWidth);
  var snf_y=Math.min(Math.max((percentY*snf_image.height/100)-frameHeight/2, 0), snf_image.height - frameHeight);
  snf_nameFrame.style.left = findX(snf_image)+snf_x+(frameWidth-snf_nameFrame.offsetWidth)/2 + 'px';
  snf_nameFrame.style.top = findY(snf_image)+snf_y+frameHeight-snf_nameFrame.offsetHeight-8 + "px";
}

function hideNameFrame() {
  hide('nameframe');
}

var tag_mouse_move_counter = 0;
var tag_current_frame_index = -1;
function findTag(event) {
  if (!event) {
    hideNameFrame();
    tag_current_frame_index = -1;
    return;
  } else if (!document.onmousemove) {
    document.onmousemove = function(){findTag()};
  } else if (event) {
    event.cancelBubble = true;
  }

  // this seems like it has the potential to be expensive on the user's computer so only do it every 3 events
  if (tag_mouse_move_counter++ % 3 != 0) {
    return;
  }

  var ft_image = ge('myphoto');
  var ft_activeImageMouseX = mousePosX(event) - findX(ft_image);
  var ft_activeImageMouseY = mousePosY(event) - findY(ft_image);
  
  var frame_percent_x = frameWidth / ft_image.width / 2 * 100;
  var frame_percent_y = frameHeight / ft_image.height / 2 * 100;
  var frame_min_x = frameWidth / 2 / ft_image.width * 100;
  var frame_min_y = frameHeight / 2 / ft_image.height * 100;
  var percent_x = ft_activeImageMouseX / ft_image.width * 100;
  var percent_y = ft_activeImageMouseY / ft_image.height * 100;
  var min_dist = -1;
  var min_index = -1;
  var dist;
  var dx;
  var dy;
  
  if (photo_tags) {
    for (i in photo_tags) {
      dx = Math.abs(Math.min(Math.max(frame_min_x, photo_tags[i][0]), 100-frame_min_x) - percent_x);
      dy = Math.abs(Math.min(Math.max(frame_min_y, photo_tags[i][1]), 100-frame_min_y) - percent_y);
      if (dx <= frame_percent_x && dy <= frame_percent_y) {
        dist = Math.pow(dx,2)+Math.pow(dy,2); // no need to sqrt here since it's all relative anyway
        if (min_dist == -1 || dist < min_dist) {
          min_dist = dist;
          min_index = i;
        }
      }
    }

    if (min_index != -1) {
      if (tag_current_frame_index != min_index) {
      
        showNameFrame(photo_tags[min_index][0], photo_tags[min_index][1], photo_tags[min_index][2]);
      }
    } else {
      hideNameFrame();
    }
    tag_current_frame_index = min_index;
  }
}

function removeTag(params) {
  var ajax = new Ajax();

  ajax.onDone = function (ajaxObj, responseText) {
    hideBox();
    eval(responseText);
    ge("phototags").innerHTML = tag_html;
  }
  
  ajax.onFail = function (ajaxObj) {}
  
  ajax.post(ajax_setter_uri, params);
  return false;
}

function submitTag() {

  if(ge("phototags").getElementsByTagName("span").length > 29) {
    successMessage = '<b>Unable to save tag. A photo may only have up to 30 tags. To add a new tag, you must first remove one of the existing tags on the photo.</b>';
    hide('tagging_instructions_default_message');                                                     
    ge('tagging_instructions_status_message').innerHTML = successMessage;                             
    focusInstructions();  
    return false;
  }  

  var ajax = new Ajax();

  ajax.onDone = function (ajaxObj, responseText) {
    eval(responseText);

    ge("phototags").innerHTML = tag_html;

    //indicate success to the user
    var successName;
    var requestText;
    var successMessage = "";
    if (id == user) {
        requestText = " ";
        tagAction = " tag ";
    } else {
        requestText = " request ";
        tagAction = " request tags in ";
    }
    
    if (!activePersonName) {
        //sometimes ajax is slow so we use what's in lastActivePersonName
        //b/c we may have overridden the old activePersonName b/c of
        //asynchronous ajax call
        successName = lastActivePersonNameEscaped; 
    } else {
        successName = activePersonNameEscaped; 
    }
    if (isCurrentUser(successName)) {
        successName = "yourself";
    }

    if (invite_saved == '1') {
      successMessage = '<b>Tag' + requestText + 'for ' + successName;
  
      if (id == user) {
        successMessage  += ' saved';
      } else {
        successMessage  += ' sent to ' + idname + ' for approval';
      }
      successMessage += '</b>.<br/>';
    }
  
    if(invite_message) {
      if (invite_error == '0') {
        successMessage += '<b style="color: green">' + invite_message + '</b><br/>';
      } else {
        successMessage += '<b style="color: red">' + invite_message + '</b><br/>';
      }
    }

    successMessage += 'You can continue to' + tagAction + 'the photo below.<br/>When you are done, click the "Done Tagging" button to resume browsing.';
  
    hide('tagging_instructions_default_message');
    ge('tagging_instructions_status_message').innerHTML = successMessage;
    focusInstructions();
    return false;
  }
  
  ajax.onFail = function (ajaxObj) {}
  
  tagImage = ge('myphoto');
  percentX = (activeImageMouseX*100)/tagImage.width;
  percentY = (activeImageMouseY*100)/tagImage.height;
  
  var personEmail = ge('invite_email').value;

  params = 'pid=' + pid
         + '&id='  + id 
         + '&subject=' + escapeURI(activePersonID)
         + '&name=' + (activePersonName ? 
                       escapeURI(activePersonName) : escapeURI(lastActivePersonName))
         + '&email=' + escapeURI(personEmail)
         + '&action=add'
         + '&x=' + percentX 
         + '&y=' + percentY;
  ajax.post(ajax_setter_uri, params);

  resetSelector();

  //remove that id from the tagging list 
  removeTagOption(activePersonName, activePersonID);
}

function removeTagOption(removeName, removeID) {
    superfriends = removeFromList(removeName, removeID, superfriends);
    friends = removeFromList(removeName, removeID, friends);
}

function removeFromList(removeName, removeID, list) {
  listCount = list.length;
  for (i=0;i<listCount;i++) {
      if( list[i]['name'] == removeName && 
          list[i]['id'] == removeID
        ) {
          list.splice(i, 1);
          break;
      }
  }
  return list;
}

function show_tagging_ui(photo_id, owner_id, owner_name, 
                         user_id, album_id, obj_id) {
    pid = photo_id;
    id = owner_id;
    user = user_id;
    aid = album_id;
    oid = obj_id;
    idname = owner_name;

    tagging = true;
    if (!tagging_initialized) {
        //get them ajax style
        var ajax = new Ajax(onGetTagOptionsSuccessFn, onGetTagOptionsFailFn);
        ajax.get(ajax_getter_uri + 
                '?id='+id+'&pid='+pid+'&aid='+aid+'&oid='+oid);
        tagging_initialized = true;
        registerKeys();
    }
    show('tagging_instructions');
    ge('name').value='';
    ge('invite_email').value='';
    ge('myphoto').style.cursor = 'crosshair';
    ge('myphotolink').href= '#';
    ge('tagging_instructions_status_message').innerHTML = '';
    show('tagging_instructions_default_message');
}

function focusInstructions() {
    window.location.hash = 'tagging_instructions';
}

function hide_tagging_ui(href) {
    tagging = false;
    hide('tagging_instructions');
    ge('myphoto').style.cursor = '';
    ge('myphotolink').href= href;

    //hide these, they may be showing
    hide('selector');
    hide('tagframe');
}

function onGetTagOptionsSuccessFn(ajaxObj, responseText) {
    eval(responseText);
    //take out the people who are tagged already- wish list
    //show super of "Me" ( wish list - if you are not already tagged )

    superfriends = superfriends_ajax;
    friends = friends_ajax;
    me_text = me_text_ajax;
    populateSelector();
    ajax_done = true;
}

function tagHit() {
    if ((activePersonID == -2 || activePersonName == "") && 
            ge('name').value == "") {
        return;
    }
    if (activePersonID == -2) {
        activePersonName = ge('name').value; //text tagging
        activePersonNameEscaped = htmlspecialchars(activePersonName);
        if (isCurrentUser(activePersonName)) {
            activePersonID = user; 
        } else {
            activePersonID = 0; //don't need neg flags here
        }
    }
    else {
      activePersonNameEscaped = activePersonName;
    }

    lastActivePersonName = activePersonName;
    lastActivePersonNameEscaped = activePersonNameEscaped;
    
    submitTag();
}

function resetSelector() {
  hide('selector');  
  hide('tagframe');  
  activePersonID = -2;
  activePersonName = "";
  ge('name').value = "";  
  ge('invite_email').value='';
  populateSelector();
}

function populateSelector() {
    var i = 0;
    var filter = ge('name').value.toLowerCase();
    var filterLen = filter.length;
    var superContents = "";
    var friendContents = "";
    var sepContents = "";
    var superCount = 0;

    if (filter == "") {
        filter = null;
    }
    
    foundCount = 0;

    superContents = render_userlist(superfriends, filter);
    superCount = foundCount;

    // Maybe add a Divider 

    friendContents = render_userlist(friends, filter);
    
    // If only one, we don't need divider
    if (superCount > 0 && foundCount > 1) {
        sepContents = "<hr/>";
    }

    ge('userlist').innerHTML = superContents + sepContents + friendContents; 

    if (foundCount == 1) {
        activePersonID = lastFoundID;
        activePersonName = lastFoundName;
        ge('f0').checked = true; //check it
    }


    hide('invite_section');
    // If no user is Chosen, might hide userlist
    if(foundCount == 0) {
        hide('userlist');
        hide('userlistlabel');

        // currently we don't support email invites to tuna objects
        if(id == user && !oid)
        {
          maybe_show_invite_section(filter);
        }
    } else {
        show('userlist');
        show('userlistlabel');
    }
}

function render_userlist(list, filter) {
    var listCount = list.length;
    var str = "";
    for (i=0; i< listCount; i++) {        
        if(!filter || list[i]['name'].toLowerCase().indexOf(filter) != -1 ) {            str += "<input type=checkbox onclick=\"pHit(this);\" name='f"+foundCount+"' id='f"+foundCount+"' friend=\"" + list[i]['name'] + "\" value=" + list[i]['id'] + "><label for='f"+foundCount+"'>" + list[i]['name'] + "</label><br>";
            lastFoundName = list[i]['name'];
            lastFoundID = list[i]['id'];
            foundCount++;

        }
    }
    return str;
}

function onGetTagOptionsFailFn() {
}

function imageMouseUp() {
    if (tagging) {
        ge('name').focus();
        ge('name').select();
    }
}

function imageMouseDown(event, image, tagsID) {
    if (tagging) {
        activeImageMouseX = mousePosX(event) - findX(image);
        activeImageMouseY = mousePosY(event) - findY(image);
    
        updateFrame(image, activeImageMouseX, activeImageMouseY);
        return false;
    }
}

function frameMouseDown(event)
{   
    if (tagging) {
        image = ge('myphoto');
        activeImageMouseX = mousePosX(event) - findX(image);
        activeImageMouseY = mousePosY(event) - findY(image);
        updateFrame(image, activeImageMouseX, activeImageMouseY);
    }
}   

function frameMouseUp()
{   
    if (tagging) {
        ge('name').focus();
        ge('name').select();
    }
}   

function updateFrame(image, imageMouseX, imageMouseY)
{
  imageMinX = findX(image);
  imageMinY = findY(image);
  imageMaxX = imageMinX + image.width;
  imageMaxY = imageMinY + image.height;

  // Before constraints
  frameX = findX(image) + imageMouseX;
  frameY = findY(image) + imageMouseY;
  //dpd("+" + frameX + " " + frameY);
  //dpd("c" + imageMouseX + " " + imageMouseY);

  // Apply Constraints
  if(frameX < imageMinX + (frameWidth/2))
    frameX = imageMinX + (frameWidth/2);
  if(frameY < imageMinY + (frameHeight/2))
    frameY = imageMinY + (frameHeight/2);
  if(frameX > imageMaxX - (frameWidth/2))
    frameX = imageMaxX - (frameWidth/2);
  if(frameY > imageMaxY - (frameHeight/2))
    frameY = imageMaxY - (frameHeight/2);
  //dpd("+" + frameX + " " + frameY);

  // Move and minus 8 for the frame border
  var tagMinX = frameX - (frameWidth/2) - 8;
  var tagMinY = frameY - (frameHeight/2) - 8;

  ge('tagframe').style.left = tagMinX + "px";
  ge('tagframe').style.top = tagMinY + "px";

  // Move Editor to the left of the click 
  //dpd("min" + imageMinX + " " + imageMinY);
  
  //if you are less than half of 300
  if (imageMouseX < 300) {
      ge('selector').style.left = (tagMinX + frameWidth + 16 + 10) + "px";
  } else {
      ge('selector').style.left = (tagMinX - 190) + "px";
  }
  ge('selector').style.top = tagMinY + "px";

  //ge('selector').style.top = tagMinY + "px";

  //bottom-move
  //ge('selector').style.left = (tagMinX) + "px";
  //ge('selector').style.top = (imageMaxY + 10) + "px";

  // Make sure they're visible
  if (ajax_done) {
      //safari needs below to have options after you drop 1st tag
      populateSelector();
  }
  show('selector');
  show('tagframe');
}


function isCurrentUser(name) {
  return name.toLowerCase() == 'me' || name.indexOf(me_text) != -1;
}

 

