/**
 * 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>');

	// 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();

    },

    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;
	li = $("<li/>");
	if (item.inline === true) {
	    pre = $('<pre/>');
	    pre.css('white-space', 'pre-wrap');
	    code = $('<code/>');
	    code.text(item.contents);
	    code.append($('<br/>'));
	    pre.append(code);
	    li.append(pre);
	} else {
	    li.append(item.contents);
	    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 && message.urlData.removed != null) {

	    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> JS 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) {

		for (var i = 0; i < removedLen; i++) {

		    this.button1.fadeIn();
		    li = this.formatListScript(message.urlData.removed[i]);
		    $('ul.blocked-js').append(li);

		}

	    } 
	    
	    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> JS in " + $('<div/>').text(message.pageURL).html());

	    if (acceptedLen > 0) {

		for (var i = 0; i < acceptedLen; i++) {

		    li = this.formatListScript(message.urlData.accepted[i]);
		    $('ul.accepted-js').append(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();