/**
 * GNU LibreJS - A browser add-on to block nonfree nontrivial JavaScript.
 * *
 * Copyright (C) 2011, 2012 Loic J. Duros
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see  <http://www.gnu.org/licenses/>.
 *
 */
var arraySrc, pageURL, urlData;


var displayPanel = {
  
  complainButton: null,
  button1: null,  
  button2: null, 
  pageURL: null,
  urlData: null,
  
  init: function () {

	  // add the buttons to the panel dynamically.
	  $('body').prepend('<a id="complain-contact" class="button white" href="#"><span>Complain to site owner</span></a><a id="allow-button" class="button white" href="#"><span>Allow all scripts in this page</span></a><a id="disallow-button" class="button white" href="#"><span>REMOVE all scripts from this page</span></a><a id="open-in-tab" class="button white" href="#"><span>Open this report in a new tab</span></a>');

	  // assign properties to these new elements.
	  this.complainButton = $('#complain-contact');
	  this.button1 = $('#allow-button');
	  this.button2 = $('#disallow-button');
	  
	  // start listening for messages sent from modules.
	  this.messageListen();
    this.openInNewTab();

  },
  openInNewTab: function () {
    $('#open-in-tab').click(function (e) {
      console.log("open in tab clicked");
      try {
        var html = $("#info").html();
      var text = window.btoa(unescape(encodeURIComponent(html)));
      self.port.emit('openInTab', text);
      } catch (x) {
        console.log("error", x.lineNumber, x.message);
      }
      return false;
    });

  },
  messageListen: function () {
	  var that = this;
	  self.on("message", function onMessage(message) {
	    that.handleMessage(message);
	  });
  },

  getHostname: function (str) {
	  var re = new RegExp('^(http(?:s)?\://[^/]+)', 'im');
	  return str.match(re)[1].toString();
  },

  /**
   * formatListScript
   * Depending on the type of script in the item,
   * will return a preformatted code element with
   * on-page JavaScript or a link to an external
   * JavaScript file.
   */ 
  formatListScript: function (item) {
	  var li, pre, code, a, reason = '';
	  li = $("<li/>");
    if (item.reason != undefined) {
      reason = item.reason + ":";
    }
	  if (item.inline === true) {
	    pre = $('<pre/>');
	    pre.css('white-space', 'pre-wrap');
	    code = $('<code/>');
	    code.text(reason + item.contents);
	    code.append($('<br/>'));
	    pre.append(code);
	    li.append(pre);
	  } else {
	    li.text(item.contents + reason);
	    li.append($('<br/>'));
	    a = $('<a/>');
	    a.attr('href', item.url);
	    a.attr('target', '_blank');
	    a.text(item.url);
	    li.append(a);
	  }
	  return li;
  },

  resetButtons: function (message) {
	  this.complainButton.hide().unbind('click');
	  if (message.contact == undefined) {
	    this.button1.hide();
	    this.button2.hide();
	  }
  },

  siteContactFound: function (url) {
	  this.complainButton.show();

	  this.complainButton.bind('click', 
				                     function (e) {
				                       e.preventDefault();
				                       self.port.emit('complainButtonClicked');
				                       window.open(url,'_blank');
				                     });

  },

  handleMessage: function (message) {
	  var removedLen, acceptedLen;

	  this.resetButtons(message);
	  
	  // handle complaint feature message
	  if (message.event ===  'contactLinkFound' || 
	      message.event === 'uncertainLinkFound') {
	    this.siteContactFound(message.absolute);
	    return;
	  } else if (message.event === 'contactLinkNotFound') {
	    // no contact link was found.
	    this.complainButton.hide();
	  }

	  
	  if (message.isAllowed != undefined) {
	    this.button2.show();
	  } else if (message.contact == undefined) {
	    this.button1.show();
	  }

	  var li, code, pre, len;

	  if (message.pageURL != undefined) {

	    this.button1.attr('href', message.pageURL);
	    this.button2.attr('href', message.pageURL);

	    $('#info').css({'opacity': 0});
	    $('h2.blocked-js').html("List of <span class='blocked'>blocked</span> JavaScript in " + $('<div/>').text(message.pageURL).html());
	    
	    $('ul.blocked-js').empty();
	    $('ul.accepted-js').empty();


	    removedLen = message.urlData.removed.length;
	    acceptedLen = message.urlData.accepted.length;
	    
	    if (removedLen > 0) {
        $("#blocked").insertBefore($('#accepted'));
		    for (var i = 0; i < removedLen; i++) {
		      this.button1.fadeIn();
		      li = this.formatListScript(message.urlData.removed[i]);
		      $('ul.blocked-js').append(li);
          //$(li).prepend('<a class="small button white" href="#">Whitelist/reload</a>');

		    }

	    } 
	    
	    else {

		    this.button1.hide();

		    $('ul.blocked-js').append('<li>LibreJS did not block any script on this page: \n\n<ul><li>There may be no script on this page (check source, C-u).</li><li>All the scripts on this page may be trivial and/or free.</li><li>You may have whitelisted this domain name or url from the preferences (Type about:addons in your location bar to check)</li><li>You may have clicked the "allow all scripts" button, which causes LibreJS to load all JavaScript on a page regardless of whether it is free, trivial, nontrivial or nonfree. This policy is effective for the entire duration of a Firefox session.</li><li>If for any reason you think LibreJS should have blocked JavaScript code on this page, please report this issue to: <a id="report" href="" target="_blank">lduros@gnu.org</a></li></ul></li>');

		    $('#report').attr('href', 'mailto:lduros@gnu.org?subject=LibreJS bug Report&body=LibreJS issue with page: ' + message.pageURL);

	    }

	    // get accepted scripts.
	    $('h2.accepted-js').html("List of <span class='accepted'>accepted</span> JavaScript in " + $('<div/>').text(message.pageURL).html());

	    if (acceptedLen > 0) {
        $('#accepted').insertBefore($('#blocked'));
		    for (var i = 0; i < acceptedLen; i++) {

		      li = this.formatListScript(message.urlData.accepted[i]);
		      $('ul.accepted-js').append(li);

		    }

	    } else {
        $('ul.accepted-js').append('<li>LibreJS did not allow the execution of any script on this page: \n\n\''
                                   + '<ul>'
                                   + '<li>There may be no script on this page (check source, C-u)</li>'
                                   + '<li>The inline and on-page JavaScript code may not be free and/or may not have proper license information and external scripts (if present) may have been removed by default.</li>'
                                   + '<li>External scripts may not be free and/or may not have proper licensing and are not part of the whitelist of free JavaScript libraries.</li></ul></li>');
      }

	    $('#info').animate({opacity: 1});

	    // emit allowAllClicked when button is clicked.
	    this.button1.bind('click', 
			                  function(e) {
				                  //console.log('clicked allow button');
				                  e.preventDefault();
				                  var url = $(this).attr('href');
				                  
				                  var urlForDisplay = (url.length > 100) ? url.substr(0,100) + '…' : url;
				                  var areYouSure = window.confirm("Allow all nonfree/nontrivial scripts on this page?\n\n" + urlForDisplay);

				                  if (areYouSure) {
				                    self.port.emit('allowAllClicked', url);
				                  }

			                  });

	    this.button2.bind('click', 
			                  function(e) {
				                  e.preventDefault();
				                  var url = $(this).attr('href');
				                  self.port.emit('disallowAllClicked', url);
			                  });
	  }
  }
};

displayPanel.init();