$(document).ready(function(){ 

  // autofocus on tag search field
  if (!("autofocus" in document.createElement("input"))) {
      $(".tagSearch:last").focus().val($(".tagSearch").val());
  }  

  // initialize hiding/showing/disabling of stuff on index
  $("#link_password_section").hide();
  $("#lookup_results_section").hide(); 
  $("#nodata_section").hide();
  $("p.link_data_msg").hide();
  $("a.link_data_url").hide();
  $("#lookup_section").show(); 
  $("#lookupButton").attr('disabled', 'disabled');
  var lookupRequestRunning = false; // prevents multiple lookup submits

  // lookup button clicked
  $(".notify_found").live('click', function(e) {
      performLookup(e);
  });
  
  $("#lookupButton").live('click', function(e) {
      performLookup(e);
  });
  
  // print button clicked, open a new tab and trigger print
  $("#lookupPrintButton").click(function(e) {
    if (!e) var e = window.event;
    e.preventDefault();
    printWindow = window.open("/print/" + $.trim($(".tagSearch").val()));
    setTimeout(function(){printWindow.print()}, 1000);
  });

  $("#st_email_large").click(function(e) {
    if (!e) var e = window.event;
    e.preventDefault();
    $( "#share_email" ).dialog('open');
  });
  
  function performLookup(e) {
    if (!e) var e = window.event;
    e.preventDefault();

    // hide intro banner/section
    $("#qr_background").hide();
    $("#action_section").addClass("top");
    $("#intro_section").slideUp("slow", function () {});

    var short_tag = $.trim($(".tagSearch").val().toLowerCase());

    if(short_tag.toLowerCase() == 'campusoracle'){
      $("span.small#error").hide();
      $("div#shadowBox").hide();
      $(".notify_found").hide();

      // prevents double clicks. 
      // no more submit till hte user types in the tag again 
      // (why would they need to re lookup a link they are on anyway)
      disableLookupButton();  

      setupSharingButtons(short_tag, $(".link_title_lookup_results").text());
    }
    else {
      if(!$("#lookupButton").is(":disabled") && !lookupRequestRunning) {
        lookupRequestRunning = true;
        $.ajax({
           type: "POST",
           url: "/do/lookup",
           data: {tag: short_tag, password: $("input#link_password").val()},
           success: function(data, status, jqXHR) {
              if(typeof data.code != 'undefined') {
                if(data.code === "1" || data.code === "4"){

                   // only if password
              	 if(data.code === "4") {
              		 lookup(data.link);
          	  	 }
          	  	 
                   $("span.small#error").hide();
                   $("div#shadowBox").hide();
                   $(".notify_found").hide();

                   // prevents double clicks. 
                   // no more submit till hte user types in the tag again 
                   // (why would they need to re lookup a link they are on anyway)
                   disableLookupButton();   
                   
                   // attempt to get location
                   if (geo_position_js.init()) {
                     geo_position_js.getCurrentPosition(
                       function(p){ 
                           
                           if(typeof data.info != 'undefined') {
                               data.info.longitude = p.coords.longitude;
                               data.info.latitude = p.coords.latitude;
                               
                               //this works
                                $.ajax({
                                   type: "POST",
                                   url: "/do/geoShare",
                                   data: data.info,
                                   success: function(data, status, jqXHR) {
                                       //alert(data);
                                   }
                                });
                           }
    //                       longitude = p.coords.longitude;
    //                       latitude = p.coords.latitude;
                         
                         // update location here
                         // must get lookup id, lbu id, lookup l idx, lbu l idx,
                       }, 
                       function(p){ 
                         //alert("fail");
                       
                       });
                   }
                   setupSharingButtons(short_tag, $(".link_title_lookup_results").text());
                 }
                 else if(data.code === "3"){
                   $("span.small#error").show();
                   disableLookupButton();
                 }
               }
           },
           complete: function() {
              lookupRequestRunning = false;
           }
        });
        return false;
      }
      else {
        return;
      }
    }
  }

  if($(".tagSearch").val() != ''){
      instantLookup($(".tagSearch").val()); 
  }
});

// when something is typed into tag search field
$(".tagSearch").live('keyup', function (event) {
    if(!event) {event = window.event;}

    // ignore the return/enter keypress
    if (event.keyCode != '13'){
      clearSocialIcons();
      disableLookupButton();
      hideAll();

      var value=$(".tagSearch").val();
      setTimeout(function(){
        if ($(".tagSearch").val() == value)
        {
          // if nothing in tagSearch
          if($(".tagSearch").val() == ""){
            $("#link_password_section").hide();
            $("#create_section").show();
            $("#lookup_results_section").hide();
            $(".notify_found").hide();
            $(".notify_notfound").hide();
            $("#shadowBox").hide();

            // magical fix
            $("#data_section").show();
          }
          // there's something in tagSearch, try to lookup the preview
          else{
            instantLookup(value);           
          }
        }
      },200);
    }
});

// when something is typed into tag password field
$("input#link_password").live('keyup', function () {
  // remove password error
  $("span.small#error").hide();
  var value=$("input#link_password").val();
  setTimeout(function(){
    if ($("input#link_password").val() == value)
    {
      // if nothing in password
      if($("input#link_password").val() == ""){
        disableLookupButton();
      }
      // there's something in password, enable lookup button
      else{
        enableLookupButton();
      }
    }
  },200);
});

function enableLookupButton(){
  $("#lookupButton").removeAttr('disabled');  
  $("input#link_password").addClass("#password_" + $(".tagSearch").val());
}

function disableLookupButton(){
  $("#lookupButton").attr('disabled', 'disabled'); 
  $('#action_title').focus(); // we just want to take the focus off from tagSearch
}

function instantLookup(tag){
  var bundle = {};
  bundle.tag = tag;
  $.get("/q/" + tag, bundle, function(returnBundle){
      $(".link_data_msg").text('');
      $("#create_section").hide();              
      $("#shadowBox").show();
      $("#lookup_results_section").show();
      hideIcons();

      // if some data was returned
      if(returnBundle != '1'){
        
        if(returnBundle.passwordPresent == '0'){
          // no password required
          $("div#link_password_section").hide();
          enableLookupButton();
          $(".link_data_msg").text('');
          lookup(returnBundle.link);
        }
        // password required
        else if(returnBundle.passwordPresent == '1'){
          $("div#link_password_section").show();
          $("span.small#error").hide();
          $(".link_data_url").hide();
          $(".link_data").hide();
          $(".link_title_lookup_results").hide();
          $(".tagSearch").attr("id", tag);
        }
        linkFound();
      }
      // no data returned, link doesn't exist
      else{
        $("div#link_password_section").hide();
        $("#data_section").hide();
        $(".notify_found").hide();
        $(".notify_notfound").show();
      }
  }, "json");
}

function setupSharingButtons(tag, title){

  // set the correct url for the share icons
  var message = '';
  if(title == ''){
    title = 'LookupLink';
    message = 'Check out my link! ' + ' Lookup the short tag: ' + tag + ' at http://www.lookuplink.com';
  }
  else{
    message = 'Check out my link: ' + title + '! ' + ' Lookup the short tag: ' + tag + ' at http://www.lookuplink.com';
  }

  var image = "https://chart.googleapis.com/chart?chs=500x500&cht=qr&chld=L|1&chl=http%3A%2F%2Fwww.lookuplink.com%2F" + tag + ".png";
  
  // twitter
  stWidget.addEntry({
         "service":"twitter",
         "element":document.getElementById('st_twitter_large'),
         "url":"http://www.lookuplink.com/" + tag,
         "title":'@LookupLink ' + message + ' or go to: ',
         "type":"large",
         "text":"Tweet this" ,
         "image":image,
         "summary":message
  });

  // facebook
  stWidget.addEntry({
         "service":"facebook",
         "element":document.getElementById('st_facebook_large'),
         "url":"http://www.lookuplink.com/" + tag,
         "title":$(".create_url#title").val(),
         "type":"large",
         "text":"Post this" ,
         "image":image,
         "summary":"Check out my link! Lookup the tag: " + tag
  });

  // share
  stWidget.addEntry({
         "service":"sharethis",
         "element":document.getElementById('st_sharethis_large'),
         "url":"http://www.lookuplink.com/" + tag,
         "title":title,
         "type":"large",
         "text":"Share this" ,
         "image":image,
         "summary":message
  });

  if(tag.toLowerCase() == 'campusoracle'){
    $('#lookupPrintButton').hide();
  }
  else{
    $('#lookupPrintButton').show();
  }
  $('#lookup_social_icons').show();
  $('#st_email_large').show();
}

function passwordPresent(){
  // no password, we don't care
  if($("input#link_password").is(':hidden')){
    return true;
  }
  // password present, there better be something in the field
  else if($("input#link_password").is(':visible') && $("input#link_password").val() != ""){
    return true;
  }
  // password present, there's nothing in the pw field
  else{
    return false;
  }
}

function linkFound() {
    $(".notify_notfound").hide();
    $("#nodata_section").hide();
    $("#data_section").show();
    $(".notify_found").show();
}

function lookup(link){
  if(link.title != ""){
    $(".link_title_lookup_results").text(link.title);
    $(".link_title_lookup_results").show();
  }
  else{
    $('.link_title_lookup_results').text('');
    $(".link_title_lookup_results").hide();
  }
  if(link.type === 0){
    lookupUrl(link);
  }
  else if (link.type === 1){
    lookupContact(link);
  }
  else if (link.type === 2){
    lookupMessage(link);
  }
  else{
    $(".link_data_url").hide();
    $(".link_data").hide();
    $(".link_data_msg").show();
    $(".link_data_msg").text("This link is currently unavailable");
  }

  adjustShadowHeight();
}

function lookupUrl(link){
  $(".link_data_msg").hide();
  $("#contact_data").hide();

  var tUrl = link.data.url;
  
  //console.log(tUrl);
  $(".link_data_url").show();
  $(".link_data_url").attr("href", tUrl);
  $(".link_data_url").text(tUrl);
  var limit = 250;
  if(tUrl.length > limit){
    $(".link_data_url").text(tUrl.substr(0,limit) + "...");
  }
  else{
    $(".link_data_url").text(tUrl);
  }
}

function lookupMessage(link){
  $(".link_data_url").hide();
  $("#contact_data").hide();
  $(".link_data_msg").show();
  var temp = replaceURLWithHTMLLinks(link.data.msg);
  temp = replaceNewLinesWithBreaks(temp);
  $(".link_data_msg").html(temp);
}

function replaceURLWithHTMLLinks(text) {
    var msg = text;
    
    // get all domains, turn into a hyperlink, and prepend an http:// in the front
    var exp = new RegExp(
        // protocol identifier
        "(((https?|ftp|file)://)?" +
          // host name
          "([a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+" +
          // domain name
          "(\\.([a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)*" +
          // TLD identifier
          "(\\.([a-z\\u00a1-\\uffff]{2,}))" +
        // port number
        "(:\\d{2,5})?" +
        // resource path
        "(/[^\\s]*)?)", "ig"
    );
    var temp = msg.replace(exp,"<a href='http://$1'>$1</a>");

    // get double http://'s
    var httpExp = /(\b(https?|ftp|file):\/\/(https?|ftp|file):\/\/)/ig;
    temp = temp.replace(httpExp,'http://');

    return temp;
}

function replaceNewLinesWithBreaks(text){
  var msg = text;
  if(msg != ''){
    var temp = msg.replace(new RegExp(/\n/g),'<br>');
    return temp;
  }
}

function lookupContact(link){
  var data_height = 0;
  $(".link_data_url").hide();
  $(".link_data_msg").hide();
  $("#contact_data").show();
  var information;
  if(link.data.first != ''){
    $('p.link_data#first_name').text("First Name: " + link.data.first);
    $("p.link_data#first_name").show();
    data_height += $('p.link_data#first_name').height();
  }
  else{
    $("p.link_data#first_name").hide();
  }

  if(link.data.last != ''){
    $('p.link_data#last_name').text("Last Name: " + link.data.last);
    $('p.link_data#last_name').show();
  }
  else{
    $("p.link_data#last_name").hide();
  }

  if(link.data.phone != ''){
    $('p.link_data span#phone').text(link.data.phone);
    $('p.link_data#phone_p').show();
    $("a.action1#call").attr('href', 'callto:' + link.data.phone);
    $("a.action2#sms").attr('href', 'sms:' + link.data.phone);
    $("a.action1#call").show();
    $("a.action2#sms").show();
  }
  else{
    $("p.link_data#phone_p").hide();
    $("a.action1#call").hide();
    $("a.action2#sms").hide();
  }

  if(link.data.email != ''){
    $('p.link_data span#email').text(link.data.email);
    $('p.link_data#email_p').show();
    $("a.action1#email").attr('href', 'mailto:' + link.data.email);
    $("a.action1#email").show();
  }
  else{
    $("p.link_data#email_p").hide();
    $("a.action1 #email").hide();
  }

  if(link.data.postal != ''){
    $('p.link_data span#postal').text(link.data.postal);
    $('p.link_data#postal_p').show();
    $("a.action1#postal").attr('href', 'http://maps.google.com/maps?q=' + link.data.postal);
    $("a.action1#postal").show();
  }
  else{
    $("p.link_data#postal_p").hide();
    $("a.action1#postal").hide();
  }
}

function adjustShadowHeight(){
  $('#shadowBox').height($(".wrapper").height() - 195);
  if($('#shadowBox').height() < 420)
    $('#shadowBox').height(420);
}

function hideAll(){
  $(".link_data_msg").hide();
}

function replaceAll(txt, replace, with_this) {
  return txt.replace(new RegExp(/\n/g),with_this);
}

function hideIcons(){
  $("a.action1#postal").hide();
  $("a.action1#email").hide();
  $("a.action1#call").hide();
  $("a.action2#sms").hide();
}

function clearSocialIcons(){
  $('#lookupPrintButton').hide();
  $('#st_email_large').hide();
  $('span#st_twitter_large').empty();
  $('span#st_facebook_large').empty();
  $('span#st_sharethis_large').empty();
}

// lookup a tag
/*
function lookupTag(shortTag, latitude, longitude, user_id){
  var bundle = {'tag':shortTag, 'latitude':latitude, 'longitude':longitude, 'user_id':user_id};
  $.get("/do/lookup" + bundle, {}, 
            function(data){
              if(data ==)
            });
}*/
