if(top.location != self.location)top.location = self.location;

function qrCode(id) {
  if(document.getElementById("qrcode_div")) {
    $('#qrcode_div').remove();
  } else {
    var obj = $('#content_'+id);
    var islast = false;
    if (obj.length == 0) {
      obj = $('#lastentry');
      islast = true;
    }
    if (obj.length == 0) return false;
    var html = '<div id="qrcode_div" style="background: #fff; width:470px; text-align:center; min-height:130px; left:35%; -moz-opacity: .90; opacity: .90; filter: alpha(opacity=90);"><div class="close_window"><h2>QR Code <a class="info_blue" target="_blank" href="/help#what_qrcode" title="What is QR Code and what is it used for?">(What is this?)</a></h2> <a href="#" class="close" onclick="closeWindow(); return false;" title="Close window">close</a></div><img src="/qr/'+id+'" alt="QR Code" /><div class="close_window" style="background: #fff; text-align: center"><a href="#" class="close" onclick="closeWindow(); return false;" title="Close window">close</a></div></div>';
    if (!islast) {
      obj.html(obj.html()+html);
    } else {
      obj.after(html);
    }
  }
  return false;
}

function closeWindow() {
  if(document.getElementById("qrcode_div")) {
    $('#qrcode_div').remove();
  }
  return false;
}

function removeContent(id) {
  if(id != '' && id != null) {
    ajax = new newAjax();
    ajax.open("POST", "/new/rm_content",true);
    if ($("#content_"+id).size() != 0) 
      $("#content_"+id).fadeOut("slow");
    else
      $("#lastentry").fadeOut("slow");
    //document.getElementById('contents').removeChild(document.getElementById('content_'+id));
    ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
      ajax.send("id="+id);
  }
  return false;
}

function counter() {
  field = document.getElementById('status');
  if (!field) field = document.getElementById('summary');
  if (!field) field = document.getElementById('message');

  var text = !field? '' : field.value.replace(/(https?:\/\/)?([\w\d_]+\.)+[\w\d_]{2,3}(([\w\d\/\.#\?%=_&-]+))*/i, '%%%');
  
  if (field && (text.length > 140)) {
    if (field.value != text ) {
      var partes = text.split('%%%');
      field.value = field.value.replace(partes[1], partes[1].substring(0, 140-(partes[0]).length));
    } else {
      field.value = field.value.substring(0, 140);
    }
  } else if (field) {
    if (document.getElementById("remaining")) {
      if (document.getElementById("remaining")) document.getElementById("remaining").firstChild.nodeValue = 140 - text.length >= 0? 140 - text.length : 0;
  
      if ( text.length > 140) {
          document.getElementById("remaining").style.color = "#d40d12";
      } else if (text.length > 115) {
          document.getElementById("remaining").style.color = "#aa0000";
      } else {
        document.getElementById("remaining").style.color = "#93A33D";
      }
    }
  }
}

function setFocus() {
  if ($("#url-pub").length == 1) $("#url-pub").focus(); else $("#status").focus();
}

//   
function saveText(status_e) {
  $.ajax({
    type: 'POST',
    url: '/new/text/create',
    data: 'status='+status_e.replace(/&/g, '%26').replace(/%/g, '%25').replace(/\+/g, '%2B')+'&show_data=1',
    beforeSend: function(bef) { $('#load').html('<img src="/i/ajax-loader3.gif" alt="" />'); },
    success: function(data_received){
      try {
        object = JSON.parse(data_received);
        s = new String(document.getElementById('photo-user').src);
        $('#contents').html('<div class="entry-user" id="content_'+object.content_id+'"><dl class="vcard"><dt><a href="/'+object.user+'" class="url"><img src="'+s.replace(/big/g,"mid")+'" class="photo fn" /></a></dt><dd class="post"><a href="/'+object.user+'" class="bold">'+object.user+'</a>: '+object.content_data+'</dd><dd class="date"><span class="time"><a href="/'+object.user+'/'+object.permalink+'">A few seconds ago</a></span> <span class="favorite"><a href="#" id="favourite_'+object.content_id+'" onclick="return favourite('+object.content_id+');" class="favorite" title="Add to favourites!"><strong>Favorite</strong></a></span> <span class="delete"><a href="#" title="Delete content" onclick="if(confirm(\'Do you want to DELETE this content?\')) { removeContent(\''+object.content_id+'\'); } return false;"><strong>Delete</strong></a></span> <span class="qrcode"><a href="#" title="QR Code" rel="qrcode" id="'+object.content_id+'" onclick="return qrCode('+object.content_id+');"><strong>QR Code</strong></a></span></dd></dl></div>'+$('#contents').html());
        $('#status').val('');
        $('#load').html('');
        $('#url-pub').val('');
        $('a[rel~=external]').each(function() {this.target='_blank'});
        counter();
      } catch(e) {
        $('#load').html('');
        $('#main').html(data_received + $('#main').html());
        $('#status').val(status_e);
        setTimeout(function(){
        $('#err').fadeOut('slow');
        }, 5000);
      }
    }
  });
}

//Video
function saveVideo(url, status_e) {
  $.ajax({
    type: 'POST',
    url: '/new/video/create',
    data: 'url-pub='+escape(url)+'&show_data=1&video_description='+status_e.replace(/&/g, '%26').replace(/%/g, '%25').replace(/\+/g, '%2B'),
    beforeSend: function(bef) { $('#load').html('<img src="/i/ajax-loader3.gif" alt="" />'); },
    success: function(data_received){
      try {
        object = JSON.parse(data_received);
        s = new String($('#photo-user').attr("src"));
        $('#contents').html('<div class="entry-user" id="content_'+object.content_id+'"><dl class="vcard"><dt><a href="/'+object.user+'" class="url"><img src="'+s.replace(/big/g,"mid")+'" class="photo fn" /></a></dt><dd class="post"><a href="/'+object.user+'" class="bold">'+object.user+'</a>: '+object.content_description+' <a href="/'+object.user+'/'+object.permalink+'" class="content_1">'+object.video_permalink+'</a></dd><dd class="date"><span class="time"><a href="/'+object.user+'/'+object.permalink+'">A few seconds ago</a></span> <span class="favorite"><a href="#" id="favourite_'+object.content_id+'" onclick="return favourite('+object.content_id+');" class="favorite" title="Add to favourites!"><strong>Favorite</strong></a></span> <span class="delete"><a href="#" title="Delete content" onclick="if(confirm(\'Do you want to DELETE this content?\')) { removeContent(\''+object.content_id+'\'); } return false;"><strong>Delete</strong></a></span> <span class="qrcode"><a href="#" title="QR Code" rel="qrcode" id="'+object.content_id+'" onclick="return qrCode('+object.content_id+');"><strong>QR Code</strong></a></span></dd></dl></div>'+$('#contents').html());
        $('#status').val('');
        $('#load').html('');
        $('#url-pub').val('');
        $('a[rel~=external]').each(function() {this.target='_blank'});
        counter();
      } catch(e) {
        $('#load').html('');
        $('#main').html(data_received + $('#main').html());
        $('#url-pub').val(url);
        $('#status').val(status_e);
        setTimeout(function(){
        $('#err').fadeOut('slow');
        }, 5000);
      }
    }
  });
}


// Image
function saveImage(url, status) {
  ajax = new newAjax();
    ajax.open("POST", "/new/image/create", true);

  ajax.onreadystatechange = function() {
    if (ajax.readyState == 4) {
      try {
        object = JSON.parse(ajax.responseText);
        s = new String(document.getElementById('photo-user').src);
        $('#contents').html('<div class="entry-user" id="content_'+object.content_id+'"><dl class="vcard"><dt><a href="/'+object.user+'" class="url"><img src="'+s.replace(/big/g,"mid")+'" class="photo fn" /></a></dt><dd class="post"><a href="/'+object.user+'" class="bold">'+object.user+'</a>: '+object.content_description+' <a href="/'+object.user+'/'+object.permalink+'" class="content_2">'+object.image_permalink+'</a></dd><dd class="date"><span class="time"><a href="/'+object.user+'/'+object.permalink+'">A few seconds ago</a></span> <span class="favorite"><a href="#" id="favourite_'+object.content_id+'" onclick="return favourite('+object.content_id+');" class="favorite" title="Add to favourites!"><strong>Favorite</strong></a></span> <span class="delete"><a href="#" title="Delete content" onclick="if(confirm(\'Do you want to DELETE this content?\')) { removeContent(\''+object.content_id+'\'); } return false;"><strong>Delete</strong></a></span> <span class="qrcode"<a href="#" title="QR Code" rel="qrcode" id="'+object.content_id+'" onclick="return qrCode('+object.content_id+');"><strong>QR Code</strong></a></span></dd></dl></div>'+$('#contents').html());
        document.getElementById('status').value = '';
        document.getElementById('load').innerHTML = '';
        document.getElementById('url-pub').value = '';
        $('a[rel~=external]').each(function() {this.target='_blank'});
        counter();
      } catch(e) {
        document.getElementById('load').innerHTML = '';
        document.getElementById('main').innerHTML = ajax.responseText + document.getElementById('main').innerHTML;
        $('#url-pub').val(url);
        $('#status').val(status);
        setTimeout(function(){
        $('#err').fadeOut('slow');
        }, 5000);
      }
    }else if(ajax.readyState==1)
      document.getElementById('load').innerHTML = '<img src="/i/ajax-loader3.gif" alt="" />';
  }

    ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    ajax.send("url-pub="+escape(url)+"&show_data=1&image_description="+status.replace(/&/g, '%26').replace(/%/g, '%25').replace(/\+/g, '%2B'));
}

// Change Image
function upload() {
  ajax = newAjax();
  ajax.open("GET", "/new/load_content/image_upload", true);
  ajax.onreadystatechange = function() {
    if (ajax.readyState == 4) {
      document.getElementById('new_content').innerHTML = ajax.responseText;
    }
  }
  ajax.send(null);

  ajax2 = new newAjax();
  ajax2.open("POST", "/setstatus",true);
  ajax2.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  ajax2.send("status=image_upload");
  return false;
}


function uploadImage(){
    p_url = document.getElementById('upload_file').value;
    if(!p_url || p_url == "") {
        //showErrorMessage("Please select a photo to upload.");
    alert("Please select a photo to upload.");
        return false;
    }
    // show loading graphic
  document.getElementById('image-form').style.display = 'none';
  document.getElementById('image-loading').style.display = 'block';
    document.getElementById('form_upload_image').submit();
    return false;
}

function pushMessage(type_c) {
  var lon = 0;
    switch(type_c) {
      case 'text':
        var text = !document.getElementById('status')? '' : document.getElementById('status').value.replace(/(https?:\/\/)?([\w\d_]+\.)+[\w\d_]{2,3}(([\w\d\/\.#\?%=_&-]+))*/i, '');
        lon = text.length;
        if((lon > 1 && lon <=140) || (document.getElementById('status') && document.getElementById('status').value.length > 0))
          saveText(document.getElementById('status').value);
      break;
      case 'video':
        lon = document.getElementById('url-pub').value.length;
        if(lon > 1) // && lon <=140) No entiendo por que la URL tiene que estar restringida a 140
          saveVideo(document.getElementById('url-pub').value, document.getElementById('status').value);
        else {
          if(document.getElementById('err') == null) {
             showMessage('err', 'error', 'You need to insert a valid URL');
          }
        }
      break;
      case 'image':
        lon = document.getElementById('url-pub').value.length;
        if(lon > 1 && lon <=140)
          saveImage(document.getElementById('url-pub').value, document.getElementById('status').value);
        else {
          showMessage('err', 'error', 'You need to insert a valid URL');
        }
      break;
    }
  return false;
}

function favourite(id) {
  $("#favourite_"+id).fadeOut('fast', function() {
    if($("#favourite_"+id).hasClass('favorite_done')) {
      $("#favourite_"+id).removeClass('favorite_done');
      $("#favourite_"+id).addClass('favorite');
      $("#favourite_"+id).attr("title", "Add to favorites!");
      $.ajax({
        type: 'POST',
        url: '/new/rm_favourite/'+id
      });
    } else {
      $("#favourite_"+id).removeClass('favorite');
      $("#favourite_"+id).addClass('favorite_done');
      $("#favourite_"+id).attr("title", "Favorite!");
      $.ajax({
        type: 'POST',
        url: '/new/favourite/'+id
      });
    }

    $("#favourite_"+id).fadeIn('normal');});
  return false;
}

function updateContacts() {
  stack = 126;
  $("input[@name=friends]").each(function() {
    if(this.type == 'checkbox' && !this.checked) {
      switch(this.value) {
        case 'fri': stack -= 2; break;
        case 'met': stack -= 4; break;
        case 'cow': stack -= 8; break;
        case 'col': stack -= 16; break;
        case 'acq': stack -= 32; break;
        case 'fam': stack -= 64; break;
      }
    }
  });

  var pag = document.location.href.match(/files\/(\d)+/);
  addMessage('lightbox', 'lightbox', 'Filtering updates...');

  $.ajax({
    type: 'POST',
    url: '/new/load_content',
    data: 'stack='+stack+(pag?'&pag='+pag[1]:''),
    success: function(data_rec) {
        $('#contents').html(data_rec);
        removeMessage('lightbox');
      }
  });
  
}

function showMessage(id, clase, msg) {
  if(document.getElementById(id) == null) {
    document.getElementById('main').innerHTML = '<div id="'+id+'" class="'+clase+'"><ul><li>'+msg+'</li></div>' + document.getElementById('main').innerHTML;
    setTimeout(function(){
    $('#'+id).fadeOut(clase == 'error'? 10000:'slow');
    $('#'+id).remove();
    }, 4000);
  }        
}


function addMessage(id, clase, msg) {
  if(document.getElementById(id) == null) {
    $('#skip').before('<div id="'+id+'" class="'+clase+'"><ul><li>'+msg+'</li></div>');
    var topPos = (window.pageYOffset? window.pageYOffset : document.documentElement.scrollTop) + ((window.innerHeight?window.innerHeight : document.documentElement.clientHeight)/2);

    $('#lightbox').css({"z-index": 1000, left : Math.round((document.body.clientWidth - document.getElementById('lightbox').offsetWidth) / 2)+'px', top : Math.round((topPos - (document.getElementById('lightbox').offsetHeight / 2)))+'px'});
  }

}

function removeMessage(id) {
  $('#'+id).fadeOut('slow');
  $('#'+id).remove();
}

function clickRSS() {
  var obj = $('#rss');
  
  if (obj) {
    obj.hover(function() {
      $('#content-rss:first').css({'display':'block'});
    }, function() {
      $('#content-rss:first').css({'display':'none'});
    });
    $('#content-rss:first').fadeTo(0, 0.9);
  }
}

var external_link = {
  init: function() {
    $('a[rel~=external]').each(function() {this.target='_blank'});
  }
}

function reply_To(user_name) {
  document.getElementById('status').value = '@'+user_name+' ';
  document.getElementById('status').focus();
}

function forward(id) {
  var elem = $('#content_'+id+' dl dd.post');
  var txt = 'FW @'+elem.text();
  elem.find('a:not(:first)').each(function() {
    if (!this.innerHTML.match(/^[@#]/)) {
      txt = txt.replace(this.innerHTML, this.href);
    }
  });
  txt = txt.replace(':  ', ': ');
  document.getElementById('status').value = txt;
  document.getElementById('status').focus();
  counter();
}

addEvent(window, 'load', external_link.init, false);
addEvent(window, 'load', counter, false);
addEvent(window, 'load', setFocus, false);
addEvent(window, 'load', clickRSS, false);
addEvent(window, 'load', function() {setTimeout(function() {$('#message_status').fadeOut(2000)}, 5000)});
addEvent(window, 'load', function() {
  if (document.location.href.match(/\/(search|favorites|world|followers|following)/)) $('input#q').focus(); 
  if (document.location.search.match(/^\?text=/)) $('#status').attr('value', unescape(document.location.search.substring(6)));
});

      function onYouTubePlayerReady() {
        // Calcula los segundos de un tiempo
        var segundos = function(tiempo) {
            var fact = 1;
            var segs = 0;
            for(var j=tiempo.length-1; j>=0; j--) {
              segs += tiempo[j]*fact;
              fact *= 60;
            }
            return segs;
        }
        // Modifico los anchors del video
        var enlaces = document.getElementById('marcadores').getElementsByTagName('a');
        for(var i=0; i<enlaces.length; i++) {
          enlaces[i].addEventListener('click', function() {
            var tiempo=this.href.substring(this.href.indexOf('#')+1).split(':');
            var player = document.getElementById('myytplayer');
            player.seekTo(segundos(tiempo), true);                      
            player.playVideo();   
            return false;
          }, true);
        }
        // Accedo al tiempo especÃ­fico de la URL
        var href = document.location.href;
        if ((pos = href.indexOf('#')+1)) {
          var player = document.getElementById('myytplayer');
          player.seekTo(segundos(href.substring(pos).split(':')));
          player.playVideo();        
        }
      }

