//
// Share Javascript and AJAX functions.
// =======================================================================================
var share_data=null;

// AJAX function to share from a Facebook page
var share_last_comment = {p:null,t:null};
function share_internal_config(params) {
  var dialog=new pop_dialog('share_pop_dialog');
  if (share_last_comment.p == params) {
    params += '&c='+escapeURI(share_last_comment.t ? share_last_comment.t : '');
  } else {
    share_last_comment.p = params;
  }
  dialog.show_ajax_dialog('/ajax/share_dialog.php?'+params);
  return false;
}

// if the user hit the bookmarklet on an internal page we need to figure out what they really wanted to do...
function share_internal_bookmarklet() {
  if (/http:\/\/[^\/]*?\/posted?\.php/.test(document.location.href)) {
    var dialog=new pop_dialog('share_congratulations');
    dialog.show_message('Share', '<div class="status"><h2>You\'ve successfully installed the bookmarklet.</h2><p>Click it on an external site to share it with your friends.</p></div>');
  }
  else {
    throw 0;
  }
}

function share_show_comments(share_id, focus_textarea) {

  //share_log_play_content(share_id, 'view_comments');  // Worth tracking?
  
  var focus_textarea = (focus_textarea == null) ? false : focus_textarea;
  
  share_footer = ge('share_footer'+share_id);
  if (share_footer.className == 'share_footer hide_comments') {
    share_footer.className = 'share_footer show_comments';
  }
    
  if (focus_textarea) {
    textarea_id = 'comment'+share_id;
    ge(textarea_id).focus();
  }

  return false;
}

function share_show_add_comment(obj, share_id) {
  
  //  Remove "Add another comment..." node
  var node = obj.parentNode;
  remove_node(node);

  //  Reveal input
  var add_comment = ge('add_comment_input'+share_id);
  show(add_comment);

  //  Enable submit button
  var submit_button = ge('add_comment_button'+share_id);
  submit_button.disabled = false;

  //  Focus textarea
  var textarea_id = 'comment'+share_id;
  ge(textarea_id).focus();

  return false;
}

function share_add_comment_submit(obj, share_id) {

  var node=obj.parentNode;
  var comment=node.getElementsByTagName('textarea')[0].value;
  
  if (/^\s*$/.test(comment)) { // empty comment
    share_flash_comment_error(obj.parentNode.getElementsByTagName('textarea')[0]);
    return;
  }
  else if (comment.length > 1000) {
    ge('add_comment_error'+share_id).style.display='block';
    return;
  }

  var commentsNode = ge('share_comments_for_'+share_id);
  //var commentAgain = ge('comment_again_'+share_id);

  var ajax=new Ajax(function(obj, text) {
    hide(node);
    if (commentsNode != null) {
      commentsNode.innerHTML = commentsNode.innerHTML + text;
    }
    node.getElementsByTagName('textarea')[0].value='';
  });
  obj.disabled=true;
  ajax.post('/ajax/share_misc.php', 'share_id=' + share_id + '&comment=' + encodeURIComponent(comment));
  return true;
}

function share_delete_comment(obj, share_id, comment_id) {
  var dialog=new pop_dialog();
  while (obj.className.indexOf('share_other_comment') == -1 && obj != null) {
    obj = obj.parentNode;
  }

  if (obj != null) {
    var delete_function = function() {
        p = obj.parentNode;
        remove_node(obj);
        if (p.childNodes.length == 0) {
          hide(p);
        }
        
        var ajax=new Ajax(function(obj, text) {});
        ajax.post('/ajax/share_misc.php', 'share_id=' + share_id + '&delcomment=1&comment_id=' + comment_id);
        generic_dialog.get_dialog(this).hide();
    };
                    
    dialog.show_choice('Delete Comment?', 'Are you sure you want to delete this comment?', 
                       'Delete', delete_function, 'Cancel', function(){generic_dialog.get_dialog(this).hide()});
  }

  return true;
}

function share_flash_comment_error(obj) {
  obj.animStart=(new Date).getTime();
  if (obj.interval) {
    clearInterval(obj.interval);
  }
  obj.interval=setInterval(function() {
    var p=((new Date).getTime()-obj.animStart)/500;
    if (p>1) {
      obj.style.backgroundColor='#fff';
      clearInterval(obj.interval);
    }
    else {
      obj.style.backgroundColor='rgb(255,' + parseInt(p * 55 + 200) + ',' + parseInt(p * 55 + 200) + ')';
    }
  }, 10);
}

function share_show_delete_dialog(context, href) {
  var dialog=new contextual_dialog();
  dialog.set_context(context);
  dialog.show_choice('Are you sure you want to delete this item?', 'Deleting this item will also remove all its comments.',
                     'Delete Item', function(){share_delete_clicked(this, context, href)},
                     'Cancel', function(){generic_dialog.get_dialog(this).hide()});
  return false;
}

function share_delete_clicked(button, context, href) {
  
  //  [soleio] This technique, while clever, is dangerous.
  //  If it doesn't find a 'sharebox_item' it nukes the topmost parentNode... the DOM.
  while (context.parentNode && context.className.indexOf('sharebox_item ')==-1) {
    context=context.parentNode;
  }
  generic_dialog.get_dialog(button).hide();
  var ajax = new Ajax();
  ajax.post(href);
  remove_node(context);
}

function share_play_video(share_id) {
  share_log_play_content(share_id, 'video');
  
  // Write Video
  write_function = eval('video_to_write_for_'+share_id);
  write_function();
  
  // Toggle Viz on blocks
  show('video_for_share_'+share_id);
  hide('video_thumb_for_'+share_id);
  hide('video_thumb_fallback_for_'+share_id);

  // Set CSS attribute on container if necessary
  if (container = ge('s'+share_id)) {
    container.className += ' playing';
  }
  return false;
}

function feed_play_video(ad_id) {
  // Same as share play video, but no logging.
  
  // Write Video
  write_function = eval('video_to_write_for_'+ad_id);
  write_function();
  
  // Toggle Viz on blocks
  show('video_for_sponsored_story_'+ad_id);
  hide('video_thumb_for_'+ad_id);
  hide('video_thumb_fallback_for_'+ad_id);
  return false;
}

function share_video_thumb_load(img, share_id) {
  
  if((img.complete==null && img.width==20 && img.height==20) || // safari - failed images are 20x20
     (img.mimeType!=null && img.complete && img.mimeType=='') || // ie - failed images have no mime type
     (img.naturalHeight!=null && img.complete && img.naturalHeight==0)) // firefox - failed images have 0 naturalheight
     { // opera - falls into one of these categories and simply works
  } // 35 x 29
}

function share_log_play_content(share_id, media_type) {
  var ajax = new Ajax();
  ajax.post('/ajax/shareplay_ajax.php?s='+share_id+'&m='+media_type);
}

function share_composer_tab(obj, sel) {
  // Update the tag classes
  var tabs = obj.parentNode.parentNode.getElementsByTagName('a');
  tabs[0].className = sel ? '' : 'selected';
  tabs[1].className = sel ? 'selected' : '';

  // Update the main class
  while (obj.className.indexOf('share_composer') == -1) {
    obj = obj.parentNode;
  }
  obj.className = 'share_composer share_status_' + (sel ? 'post' : 'send');

  return false;
}

function share_send_onsubmit(obj) {
  // Sanity checks
  var ids = ge('ids');
  if (!ids.tokenizer || ids.tokenizer.count_names() == 0) {
    alert('You must specifiy at least one recipient for this message.');
    return false;
  }

  // Build the post string and disable the inputs
  var post = ['action=send'];
  var inputs = obj.getElementsByTagName('input');
  for (var i=0; i<inputs.length; i++) {
    if (inputs[i].type != 'button' && inputs[i].name) {
      post.push(inputs[i].name+'='+escapeURI(inputs[i].value));
    }
    inputs[i].disabled = true;
  }
  var inputs = obj.getElementsByTagName('textarea');
  for (var i=0; i<inputs.length; i++) {
    post.push(inputs[i].name+'='+escapeURI(inputs[i].value));
    inputs[i].disabled = true;
  }
  share_last_comment.t = inputs[0].value;
  var divs = obj.getElementsByTagName('div');
  for (var i=0; i<divs.length; i++) {
    if (typeof divs[i].tokenizer != 'undefined') {
      divs[i].tokenizer.disable();
    } else if (divs[i].className.indexOf('tokenizer') != -1) {
      divs[i].className += ' tokenizer_locked';
    }
  }

  // Retreive the base element
  while (obj.className.indexOf('dialog_content') == -1) {
    obj = obj.parentNode;
  }

  // Post it!
  var ajax = new Ajax();
  ajax.onDone = share_post_send_callback.bind(obj);
  ajax.post('/ajax/share.php', post.join('&'));
}

function share_post_onsubmit(obj) {
  // Build the post string and disable the inputs
  var post = ['action=post'];
  var inputs = obj.getElementsByTagName('input');
  for (var i=0; i<inputs.length; i++) {
    if (inputs[i].type != 'button' && inputs[i].name) {
      post.push(inputs[i].name+'='+escapeURI(inputs[i].value));
    }
    inputs[i].disabled = true;
  }
  var inputs = obj.getElementsByTagName('textarea');
  for (var i=0; i<inputs.length; i++) {
    post.push(inputs[i].name+'='+escapeURI(inputs[i].value));
    inputs[i].disabled = true;
  }
  share_last_comment.t = inputs[0].value;

  // Retreive the base element
  while (obj.className.indexOf('dialog_content') == -1) {
    obj = obj.parentNode;
  }

  // Post it!
  var ajax = new Ajax();
  ajax.onDone = share_post_send_callback.bind(obj);
  ajax.post('/ajax/share.php', post.join('&'));
}

function share_post_send_callback(whatevs, text) {
  eval('var response = '+text);
  if (response['html']) {
    this.innerHTML = response['html'];
    if (response['redr']) {
      setTimeout(function() {
        goURI(response['redr'])
      }, 3000);
    } else {
      var gd = generic_dialog.get_dialog(this);
      gd && gd.fade_out(500, 2000) || setTimeout(function(){self.close()}, 3000);
    }
  } else if (response['redr']) {
    goURI(response['redr']);
  } 
}

//
// inline editor object... takes a simple element and makes it an input onclick
// =======================================================================================
function inline_editor(obj, name, textarea) {
  this.name = name;
  this.obj = obj;
  this.more_than_meets_the_eye = true;
  var edit = document.createElement(textarea ? 'textarea' : 'input');
  this.edit = edit;
  this.original_value = edit.value = obj.firstChild.nodeValue;
  edit.className = 'inputtext inline_edit';
  if (this.is_textarea = textarea) {
    edit.style.width = (obj.offsetWidth-16)+'px';
  }
  obj.parentNode.insertBefore(edit, obj);
  obj.parentNode.removeChild(obj);
  edit.onblur = this._onblur.bind(this);
  edit.onchange = this._onchange.bind(this);
  edit.onkeypress = function(event){return this._onkeypress(event ? event : window.event)}.bind(this);
  edit.focus();
  edit.select();
}

inline_editor.prototype._onkeypress = function(event) {
  switch(event ? event.keyCode : 0) {
    case 27: // esc
      this.edit.value = this.original_value;
    case 13: // enter
      this._onblur();
      return false;
  }
}

inline_editor.prototype._onblur = function() {
  if (!this.more_than_meets_the_eye) {
    return false;
  }
  this.more_than_meets_the_eye = false;
  this._onchange();
  var anchor = document.createElement('a');
  var name = this.name;
  var is_textarea = this.is_textarea;
  anchor.appendChild(document.createTextNode(this.edit.value));
  anchor.href = '#';
  anchor.onclick = function(){new inline_editor(this, name, is_textarea); return false};
  anchor.onmousedown = function(){return false};
  anchor.className = 'inline_edit';
  this.edit.parentNode.insertBefore(anchor, this.edit);
  this.edit.parentNode.removeChild(this.edit);
}

inline_editor.prototype._onchange = function() {
  var target = this.edit.form[this.name];
  if (!target) {
    target = document.createElement('input');
    target.name = this.name;
    target.type = 'hidden';
    this.edit.form.appendChild(target);
  }
  target.value = this.edit.value;
}


//
// share ajax stuff
// =======================================================================================
function composer_attachment() {
}

/* static */ composer_attachment.from_url = function(url) {
  if (!/(?:https?:\/\/)?\w+\.\w+/.test(url)) {
    return false;
  }
  var attachment = new composer_attachment();
  attachment.url = url;

  var ajax = new Ajax(attachment.ajax_callback.bind(attachment));
  ajax.post('/inbox/ajax/ajax.php', {action:'attachment', url:url});

  return attachment;
}

composer_attachment.prototype.container_ready = function(obj) {
  this.container = obj;
  var inputs = obj.getElementsByTagName('input');
  var html = ['&nbsp;'];
  for (var i=0; i<inputs.length; i++) {
    if (inputs[i].type == 'text' || inputs[i].type == 'hidden') {
      html.push('<input type="hidden" name="'+htmlspecialchars(inputs[i].name)+'" value="'+htmlspecialchars(inputs[i].value)+'" />');
    }
  }
  obj.innerHTML = html.join('');
  obj.className += ' attachment_loading';
}

composer_attachment.prototype.render_inputs_recursive = function(name, params) {
  var html = [];
  if (typeof params == 'object') {
    for (var i in params) {
      html.push(this.render_inputs_recursive(name+'['+i+']', params[i]));
    }
  } else {
    html.push('<input type="hidden" name="',name,'" value="',htmlspecialchars(params),'" />');
  }
  return html.join('');
}

composer_attachment.prototype.ajax_callback = function(obj, text) {
  eval(text);

  // build out the params
  var html = [__result.html];
  html.push(this.render_inputs_recursive('attachment[params]', __result.params));
  html.push('<input type="hidden" name="attachment[type]" value="', __result.type, '" />');

  // create the container
  this.container.innerHTML = html.join('');
  this.container.className = this.container.className.replace('attachment_loading', '');
  var scripts = this.container.getElementsByTagName('script');
  for (var i=0; i<scripts.length; i++) {
    eval(scripts[i].innerHTML);
  }
}

/* static */ composer_attachment.setup_thumbnails = function(imgs, obj) {
  var sandbox = new image_sandbox();
  sandbox.onfinish = function() {
    imgs = sandbox.get_imgs();
    for (var i=imgs.length-1; i>=0; i--) {
      if (imgs[i].width && (imgs[i].height < 50 || imgs[i].width < 50 || imgs[i].height/imgs[i].width > 3 || imgs[i].width/imgs[i].height > 3)) {
        imgs.splice(i,1);
      }
    }
    if (!imgs.length) {
      return;
    }

    // javascript's sort method doesn't provide enough consistency with elements of the same value, with the way it rearranges stuff
    // so we implement a basic bubble sort here to sort the imgs from largest to smallest while maintaining order if the images are the same size
    for (var si=0; si<imgs.length-1; si++) {
      for (var sj=imgs.length-1; sj>=si; sj--) {
        if (imgs[si].width * imgs[si].height < imgs[sj].width * imgs[sj].height) {
          temp = imgs[si];
          imgs[si] = imgs[sj];
          imgs[sj] = temp;
        }
      }
    }

    // find the input for our image
    var input = obj;
    while (input.parentNode && input.tagName.toLowerCase() != 'form') {
      input = input.parentNode;
    }
    input = input.getElementsByTagName('input');
    for (var i=0; i<input.length; i++) {
      if (input[i].name.indexOf('[params][images]')!=-1) {
        input = input[i];
        break;
      }
    }
    new thumbnail_selector(obj, input, imgs);

  }.bind(this);
  sandbox.load_images(imgs);
}

//
// this is the thumbnail widget with left\right arrows for choosing an image
// =======================================================================================
function thumbnail_selector(obj, input, images) {
  var html = ['<div class="thumbnail_stage"><h4>Choose a Thumbnail</h4><div class="selector clearfix"><div class="arrows clearfix">',
            '<span class="left"><a href="#" class="arrow disabled">&nbsp;</a></span>',
            '<span class="right"><a href="#" class="arrow ',images.length > 1 ? 'enabled' : 'disabled', '">&nbsp;</a></span>',
            '</div><div class="counter"><span>1 of ',images.length,'</span></div></div>'];
  for (var k in images) {
    html.push('<div class="thumbnail', k==0 ? ' thumbnail_selected' : ' thumbnail_unselected', '">',
              '<img class="img_loading" src="', images[k].src, '" onload="adjustImage(this, \'thumbnail\', 100)" />',
              '</div>');
  }
  html.push('<label style="white-space:nowrap"><input type="checkbox" onclick="this.parentNode.parentNode.parentNode.thumbnail.use_thumbnail(this.checked)" /> No Picture</label></div>');
  obj.innerHTML = html.join('');

  this.images = images;
  this.input = input;
  input.value = this.images[0].src;
  this.obj = obj;
  this.obj.thumbnail = this;
  this.label = obj.getElementsByTagName('span')[2];
  this.index = 0;
  var anchors = obj.getElementsByTagName('a');
  this.left = anchors[0];
  this.right = anchors[1];
  this.left.onclick = this.left_arrow_press.bind(this);
  this.right.onclick = this.right_arrow_press.bind(this);
  this.left.onselectsart = this.right.onselectstart = function(){return false}; // disable selections
  this.left.onmousedown = this.right.onmousedown = this._onmousedown;
  this.left.onmouseout = this.right.onmouseout = this._onmouseout;
}

// called from the "None" checkbox
thumbnail_selector.prototype.use_thumbnail = function(checkbox) {
  if (!checkbox) {
    this.move_selection(0);
    remove_css_class_name(this.obj, 'thumbnail_dont_use');
  } else {
    this.input.value = '';
    add_css_class_name(this.obj, 'thumbnail_dont_use');
  }
}

// not called in context of the class!
thumbnail_selector.prototype._onmousedown = function() {
  add_css_class_name(this, 'active');
  return false;
}

// not called in context of the class!
thumbnail_selector.prototype._onmouseout = function() {
  remove_css_class_name(this, 'active');
}

thumbnail_selector.prototype.left_arrow_press = function() {
  remove_css_class_name(this.left, 'active');
  this.move_selection(-1);
  return false;
}

thumbnail_selector.prototype.right_arrow_press = function() {
  remove_css_class_name(this.right, 'active');
  this.move_selection(1);
  return false;
}

thumbnail_selector.prototype.move_selection = function(offset) {
  var index = this.index + offset;
  if (index >= 0 && index < this.images.length) {
    var divs = this.obj.getElementsByTagName('div');
    var j = 0;
    this.index = index;
    for (var i=0; i<divs.length; i++) {
      var className = divs[i].className;
      if (className.indexOf('thumbnail ') == -1) {
        continue;
      }
      var selected = j == index;
      if (className.indexOf(selected ? '_unselected' : '_selected') != -1) {
        divs[i].className = className.replace(/thumbnail_(?:un)?selected/, selected ? 'thumbnail_selected' : 'thumbnail_unselected');
      }
      j++;
    }
    this.label.innerHTML = (index+1) + ' of ' + j;
    this.left.className = this.left.className.replace(/[^ ]+abled/, index == 0 ? 'disabled' : 'enabled');
    this.right.className = this.right.className.replace(/[^ ]+abled/, index == this.images.length - 1 ? 'disabled' : 'enabled');
    this.input.value = this.images[index].src;
  }
}

//
// takes a list of images, loads them, filters out the bad ones and then hooks a callback 
// =======================================================================================
function image_sandbox() {

  // construct the sandbox
  this.obj=document.createElement('div');
  this.obj.style.left=this.obj.style.top='-100px';
  this.obj.style.width=this.obj.style.height='1px';
  this.obj.style.overflow='hidden';
  this.images=0;
  this.done=0;
  document.body.appendChild(this.obj);

  this.load_images=function(imgs) {
    this.images=imgs.length;
    for (var i=0; i<imgs.length; i++) {
      new images_sandbox_loader(this, imgs[i]);
    }
  }

  this.image_loaded=function(img) {
    this.done++;
    this.state_change();
  }

  this.image_failed=function(img) {
    img.destroy();
    this.images--;
    this.state_change();
  }

  this.get_imgs=function() {
    var imgs=new Array();
    var collection=this.obj.getElementsByTagName('img');
    for (var i=0; i<collection.length; i++) {
      imgs.push(collection[i]);
    }
    return imgs;
  }

  this.state_change=function() {
    if (this.done==this.images) {
      if (this.onfinish) {
        this.onfinish();
      }
    }
  }
}

function images_sandbox_loader(sandbox, img) {
  this.timeout=4000; // after 4 seconds we give up
  this.start=(new Date).getTime();
  this.sandbox=sandbox;

  if (typeof img!='object') { // allow a list of src's instead of objects
    img={src:img};
  }
  this.obj=document.createElement('img');
  this.obj.onload=function(){if(this.poll_image)this.poll_image(1)}.bind(this);
  this.obj.onerror=function(){if(this.poll_image)this.poll_image(2)}.bind(this);

  for (var key in img) {
    this.obj[key] = img[key];
  }

  this.sandbox.obj.appendChild(this.obj);
  if (this.poll_image != null) {
    this.poll_image();
  }
}

images_sandbox_loader.prototype.poll_image = function(state) {
  if (state==1) { // load
    this.poll_image=null; // we don't want this function to be called a bunch of times
    this.sandbox.image_loaded(this);
  } else if (state==2) { // fail
    this.poll_image=null;
    this.sandbox.image_failed(this);
  } else {
    if (
        (this.obj.complete==null && this.obj.width==20 && this.obj.height==20) ||        // safari - failed images are 20x20
        (this.obj.mimeType!=null && this.obj.complete && this.obj.mimeType=='') ||       // ie - failed images have no mime type
        (this.obj.naturalHeight!=null && this.obj.complete && this.obj.naturalHeight==0) // firefox - failed images have 0 naturalheight
       ) {                                                                               // opera - falls into one of these categories and simply works
      this.poll_image(2); // fail
    } else if (this.obj.complete) {
      this.poll_image(1); // load
    } else if (this.start+this.timeout<(new Date).getTime()) {
      this.poll_image(2); // fail
    } else {
      setTimeout(function(){if(this.poll_image)this.poll_image()}.bind(this), 20);
    }
  }
}

images_sandbox_loader.prototype.destroy = function() {
  remove_node(this.obj);
  this.obj=null;
}

