/**
* @preserve jQuery Plugin: Highlight Search Terms - version 0.3
* http://github.com/hail2u/jquery.highlight-search-terms
* Highlight search terms in referrer URL from Google, Yahoo!, Bing and custom site.
*
* Copyright (c) 2009 Kyo Nagashima <kyo@hail2u.net>
* This library licensed under MIT license:
* http://opensource.org/licenses/mit-license.php
*
* 06/20/2011 Modified by Luca De Angelis to work with the main 3 search engines.
* 	     Various mod to the highlighting process.
*	     Inserted a warning box after the h1 to disable the highlightings.
*/

(function ($) {
	$.fn.highlightSearchTerms = function (options) {
	var o = $.extend({}, $.fn.highlightSearchTerms.defaults, options);
	$.merge(o.referrerPatterns, $.fn.highlightSearchTerms.builtinReferrerPatterns);
	var ref = o.referrer || document.referrer.replace(/\%20|\+/g, "\+");

		if (ref) {
			var terms = extractSearchTerms(ref, o);

			// Highlight terms
			if (terms !== "") {
				terms = new RegExp("(" + terms + ")", "gi");
				var 	t = encodeEntities(o.tagName),
					c = encodeEntities(o.className),
					highlighted = "<" + t + " class=\"" + c + "\">$1</" + t + ">";

				// Language
				var 	url = window.location.href,
					lang = url.match(/_en./) ? "en" : "it",
					mex = lang == "it" ? '<p>Arrivando da un motore di ricerca, sono state <span class="mark" title="Le parole trovate sono state evidenziate con questo stile">evidenziate</span> le parole cercate.</p><a href="#" class="close">Disabilita <img src="Img/Close.png" alt="" /></a>' : '<p>Coming from a search engine, searched terms have been <span class="mark" title="The words found are highlighted with this style">highlighted</span></p><a href="#" class="close">Disable <img src="Img/Close.png" alt="" /></a>';

				// Warning box
				$("h1").after('<div id="highlight-warning" class="highlight-box">' + mex + '</div>');

				var $highlightWarning = $("#highlight-warning");
				$highlightWarning.find("a").click(function(e){
					e.preventDefault();
					$highlightWarning.slideUp();
					$("#content span.mark").removeClass("mark");
				});

				// Replacing the words with the marked ones
				this.find(":not(iframe, option, script, textarea)").contents().each(function () {
					if (this.nodeType === 3) {
						var s = encodeEntities(this.nodeValue).replace(terms, highlighted);
						$(this).replaceWith(s);
					}
				});
			}
		}
		return this;
	};

	// Private: Extract terms from referrer
	function extractSearchTerms (ref, o) {
		var terms = [];

		$.each(o.referrerPatterns, function () {
			var pattern = new RegExp(this, "i");

			if (pattern.exec(ref)) {
				var unsafe = new RegExp(o.unsafeChars, "g");
				var termsTemp = decodeURIComponent(RegExp.$1).replace(unsafe, "+").replace(/^\+*(.*?)\+*$/, "$1").replace(/\++/g, "|").split('|');
				// Keeping only the terms >= than 3 characters
				$.each(termsTemp, function(k, v) {
					if (v.length > 2) {
						// Excluding the safewords
						var excluded = 0;
						for (var i=0, len=o.safeWords.length; i<len; i++) {
							if (v.toLowerCase() == o.safeWords[i].toLowerCase()) {
								excluded = 1;
								break;
							}
						}
						if (!excluded) terms.push(v);
					}
				})
				return false; // break $.each
			}
		});
		return terms.join("|");
	}

	// Private: Encode entities
	function encodeEntities (s) {
		return $("<u/>").text(s).html(); // jQuery magic
	}

	// Public: default options
	$.fn.highlightSearchTerms.defaults = {
		tagName: "span",
		className: "mark",
		referrerPatterns: [],
		unsafeChars: "[!-*,-/:-@[-`{-~]",
		safeWords: ["elettra", "progetti", "servizi", "spa"]
	};

	// Public: built-in referrer patterns for Google(com|co.jp), Yahoo!(com|co.jp), Bing.
	$.fn.highlightSearchTerms.builtinReferrerPatterns = [
		".*\.google\..*.+[&?]q=([^&]+).*$",
		".*\.yahoo\..*.+[&?]p=([^&]+).*$",
		".*\.bing\..*.+[&?]q=([^&]+).*$"
	];

})(jQuery);

$(document).ready(function(){
	$("#content :not(#breadcrumb, #highlight-warning, h1)").highlightSearchTerms();
});

