$(document).ready(function(){  
  var url =  $(".link_data_url").text();
  $(".link_data_url").attr("href", url);
  var limit = 150;
  if(url.length > limit){
    $(".link_data_url").text(url.substr(0,limit) + "...");
  }
  else{
    $(".link_data_url").text(url);
  }
  
  replaceURLWithHTMLLinks();
  replaceNewLinesWithBreaks();

  setupSharingButtons($('.link_title_lookup_results').attr('id'), $('.link_title_lookup_results').text());

  // 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/" + $('.link_title_lookup_results').attr('id') );
    setTimeout(function(){printWindow.print()}, 1000);
  });

  // user clicks to share via email
  $("#st_email_large").click(function(e) {
    if (!e) var e = window.event;
    e.preventDefault();
    $( "#share_email" ).dialog('open');
  });

  $( "#share_email" ).dialog({
    autoOpen: false,
    width: 305,
    modal: true,
    resizable: false,
    buttons: {
      "Submit": function() {
        var email = $('.share_email_form#email_field').val();
        var body = $('textarea.share_email_form').val();

        // email share clicked for a lookup action
        var short_tag = $('.link_title_lookup_results').attr('id');
        var title = $('.link_title_lookup_results').text();    
        
        requestShareEmail(email, body, short_tag, title);
      },
      Cancel: function() {
        $( this ).dialog( "close" );
      }
    },
    close: function() {
    }
  });

  $("#share_email_confirm").dialog({
    autoOpen:false,
    modal: true,
    resizable: false,
    width: 250,
    buttons:{
      "Ok":function(){$(this).dialog('close');}
    }
  });
});

function requestShareEmail(email, body, short_tag, title){
    var bValid = true;
    $('#email_field').removeClass( "ui-state-error" );

    bValid = bValid && checkLength( $( "#validateTips" ), $('#email_field'), "email", 6 );
    bValid = bValid && checkRegexp( $( "#validateTips" ), $('#email_field'), /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "Please enter a valid email." );

    if ( bValid ) {          
      $( "#share_email" ).dialog('close');
      $.ajax({
          type: "POST",
          url: "/email/share",
          data: {'email': email, 'body':body, 'short_tag': short_tag, 'title': title},
          complete: function() {
             $("#share_email_confirm").dialog('open');
          }
       });
    }  
}

function replaceURLWithHTMLLinks() {
    var msg = $('p.link_data_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://');

    $('p.link_data_msg').text(temp);
}

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

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":title,
         "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();
  }
  $('#lookup_social_icons').show();
}
