// Translator.js

// === Utils ===
String.prototype.capitalize = function() {
    return this.charAt(0).toUpperCase() + this.slice(1);
};

// For browsers without consoles
if (!console) {
    var console = {};
    console.log = function(s) {};
}

// === Code for Handling Translation ===

// Regular expression for checking the end of a word  —
var separator = "(?=(;?[,\\.\\?!;:-—“”’]?(\\s|<|$))|[—-]\\w)";
// Regular expression for checking for URLs
var URLregex = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;

function log(word) {
    return function ($0) {
	console.log($0);
	return word;
    };
}

function translate(text, from, to) {
    for (var i = 0; i < dictionary.length; i++) {
	var regex = new RegExp(dictionary[i][from]+separator, "gm");
	text = text.replace(regex, log(dictionary[i][to]));

	regex = new RegExp(dictionary[i][from].capitalize()+separator, "gm");
	text = text.replace(regex, log(dictionary[i][to].capitalize()));
    }
    return text;
}

function translateToBritish(text) {
    return translate(text, 0, 1);
}

function translateToAmerican(text) {
    return translate(text, 1, 0);
}

// === Code for Handling Cookies ===
var cookieName = "lang";
var language = null;

function languageIsSet() {
    return document.cookie.search(RegExp(cookieName+"(?=\=)")) != -1;
}

function saveLanguage(lang) {
    var expires = new Date();
    expires.setTime(expires.getTime()+(365 *24*60*60*1000)); // last a year
    document.cookie = cookieName+"="+lang+"; expires="+expires.toUTCString()+"; path=/";
    console.log(cookieName+"="+lang+"; expires="+expires.toUTCString()+"; path=/");
    language = lang;
}

function getLanguage() {
    if (language) {
	return language;
    } else if (languageIsSet()) {
	var matches = document.cookie.match(RegExp("(?:"+cookieName+"=)([A-Za-z]+)"));
	return matches[1];
    } else {
	return detectLanguage();
    }
}

// === Code for Automagically Detect Location and Setting the Language ===
function detectLanguage() {
    // Use the timezone to guess whether to use British English or American English.
    var gmtHours = -((new Date()).getTimezoneOffset())/60; // range: [-12,12]
    if (gmtHours < -2) {
	return "us";
    } else {
	return "uk";
    }
}
function detectAndSetLanguage() {
    if (!languageIsSet()) {
	saveLanguage(detectLanguage());	
    }
}

// === Handle updating the page ===
function simplePageUpdate() {
    if (getLanguage() == "us") {
        jQuery("body").html(translateToAmerican(jQuery("body").html()));
    } else {
	jQuery("body").html(translateToBritish(jQuery("body").html()));
    }
}
function divPageUpdate() {
    var not = ":not(#foxboro_menu):not(#foxboro_menu div):not(#foxboro_body):not(#foxboro_container)";
    if (getLanguage() == "us") {
	var divs = jQuery("body div"+not);
	for (var i = 0; i < divs.length; i++) {
	    divs[i].innerHTML = translateToAmerican(divs[i].innerHTML);
	}
    } else {
	var divs = jQuery("body div"+not);
	for (var i = 0; i < divs.length; i++) {
	    divs[i].innerHTML = translateToBritish(divs[i].innerHTML);
	}
    }
}

// === Final API ===
function createLanguageToggle(id, update, cssClass) {
    jQuery(id).live("click", function handleClick() {
		   if (getLanguage() == "uk") {
		       jQuery(id).removeClass(cssClass);		       
		       saveLanguage("us");
		   } else {
		       jQuery(id).addClass(cssClass);
		       saveLanguage("uk");
		   }
		   update();
	       });
    if (getLanguage() == "uk") {
	saveLanguage("us");
	jQuery(id).click();
    }
}
