//
// options.js
//
// Content script for the options page
//

var ieObject = null;

function getLocalStorage(key, fnResponse)
{
    var request = { type: "GETLS", key: key };
    chrome.extension.sendRequest(request, fnResponse);
}

function setLocalStorage(key, value, fnResponse)
{
    var request = { type: "SETLS", key: key, value: value };
    if(typeof(fnResponse) != "undefined")
        chrome.extension.sendRequest(request, fnResponse);
    else
        chrome.extension.sendRequest(request);
}

function onAddressKey(event)
{
    var characterCode;

    // First, check for the enter key
    if(event && event.which)
        characterCode = event.which;
    else
        characterCode = event.keyCode;

    if(characterCode == 13)
    {
        onAdd();
        return false;
    }
}

function xonAddressKey(event) {
	var characterCode;

	// First, check for the enter key
	if (event && event.which)
		characterCode = event.which;
	else
		characterCode = event.keyCode;

	if (characterCode == 13) {
		xonAdd();
		return false;
	}
}

function setDirty(isDirty)
{
    if(isDirty)
        window.onbeforeunload = onBeforeUnload;
    else
        window.onbeforeunload = null;
}

function initializeAddressList()
{
    getLocalStorage("filterUrls", function(filterUrls) {
        if(!filterUrls) return;
        var addressList = document.getElementById("addressList");
        for(var i=0; i<filterUrls.length; i++)
        {
            addressList.add(new Option(filterUrls[i],filterUrls[i]), null);
        }
    });
}

function onAdd()
{
    var addressText = document.getElementById("addressText");
    var addressList = document.getElementById("addressList");
    var str = addressText.value;
    if(str)
    {
        addressList.add(new Option(str, str), null);
        addressText.value = "";
    }
    updateUrlStore();
}

function onRemove()
{
    var addressList = document.getElementById("addressList");
    for(var i=addressList.options.length-1; i>=0; i--)
    {
        if(addressList.options[i].selected)
        {
            addressList.removeChild(addressList.options[i]);
        }
    }
    updateUrlStore();
}

function updateUrlStore()
{
    var arrSelected = [];
    var addressList = document.getElementById("addressList");
    for(var i=0; i<addressList.options.length; i++)
    {
        arrSelected.push(addressList.options[i].value);
    }
    setLocalStorage("filterUrls", arrSelected); 
}

function initializeAddressList() {
	getLocalStorage("filterUrls", function(filterUrls) {
		if (!filterUrls) return;
		var addressList = document.getElementById("addressList");
		for (var i = 0; i < filterUrls.length; i++) {
			addressList.add(new Option(filterUrls[i], filterUrls[i]), null);
		}
	});
}

function xonAdd() {
	var addressText = document.getElementById("xaddressText");
	var exclusionList = document.getElementById("exclusionList");
	var str = addressText.value;
	if (str) {
		exclusionList.add(new Option(str, str), null);
		addressText.value = "";
	}
	xupdateUrlStore();
}

function xonRemove() {
	var exclusionList = document.getElementById("exclusionList");
	for (var i = exclusionList.options.length - 1; i >= 0; i--) {
		if (exclusionList.options[i].selected) {
			exclusionList.removeChild(exclusionList.options[i]);
		}
	}
	xupdateUrlStore();
}

function xupdateUrlStore() {
	var arrSelected = [];
	var exclusionList = document.getElementById("exclusionList");
	for (var i = 0; i < exclusionList.options.length; i++) {
		arrSelected.push(exclusionList.options[i].value);
	}
	setLocalStorage("exclusionUrls", arrSelected);
}

function initializeExclusionList() {
	getLocalStorage("exclusionUrls", function(filterUrls) {
		if (!filterUrls) return;
		var exclusionList = document.getElementById("exclusionList");
		for (var i = 0; i < filterUrls.length; i++) {
			exclusionList.add(new Option(filterUrls[i], filterUrls[i]), null);
		}
	});
}

function updateChromePopupsEnabled()
{
    var checkbox = document.getElementById("enableChromePopups");
    if(checkbox.checked)
        setLocalStorage("enableChromePopups", true);
    else
        setLocalStorage("enableChromePopups", false);
}

function updateShowSearchBox() {
	var checkbox = document.getElementById("showSearchBox");
	if (checkbox.checked)
		setLocalStorage("showSearchBox", true);
	else
		setLocalStorage("showSearchBox", false);
}

function updateDisableAutoSearch() {
	var checkbox = document.getElementById("disableAutoSearch");
	if (checkbox.checked)
		setLocalStorage("disableAutoSearch", true);
	else
		setLocalStorage("disableAutoSearch", false);
}

function updateAutoUrlsEnabled()
{
    var checkbox = document.getElementById("enableAutoUrls");
    if(checkbox.checked)
        setLocalStorage("enableAutoUrls", true);
    else
        setLocalStorage("enableAutoUrls", false);
}

function initializeAutoUrlsEnabled()
{
    var el = document.getElementById("enableAutoUrls");
    
    getLocalStorage("enableAutoUrls", function(value) {
        el.checked = value;
    });
    el.addEventListener("click", updateAutoUrlsEnabled, false);
}

function initializeChromePopupsEnabled()
{
    var el = document.getElementById("enableChromePopups");
    
    getLocalStorage("enableChromePopups", function(value) {
        el.checked = value;
    });
        
    el.addEventListener("click", updateChromePopupsEnabled, false);
}

function initializeShowSearchBox()
{
	var el = document.getElementById("showSearchBox");

	getLocalStorage("showSearchBox", function(value) {
		el.checked = value;
	});

	el.addEventListener("click", updateShowSearchBox, false);
}

function initializeAutoSearch() {
	var el = document.getElementById("disableAutoSearch");

	getLocalStorage("disableAutoSearch", function(value) {
		el.checked = value;
	});

	el.addEventListener("click", updateDisableAutoSearch, false);
}


function initializeUrlBox()
{
    var myUrl = document.location.href;
    var regex = /[?&]initial=([^&].*)/;
    var match = myUrl.match(regex);
    var el = document.getElementById("addressText");
    if(match)
        el.value = decodeURIComponent(match[1]);
       el.addEventListener("keypress", function(event) { onAddressKey(event); }, false);

   el = document.getElementById("xaddressText");
   el.addEventListener("keypress", function(event) { xonAddressKey(event); }, false);
       
}

var modes = ["IE7S", "IE8S", "IE8F", "IE9S", "IE9F"];

function modeClicked() {
	var newMode = "IE7S";
	for (var i = 0; i < modes.length; i++) {
		var el = document.getElementById("mode" + modes[i]);
		if(el.checked) {
			newMode = modes[i];
			break;
		}
	}
	
	var request = { type: "SETCOMPATMODE", mode: newMode };
	chrome.extension.sendRequest(request);

	alert('Note: Chrome must be re-started for this change to take effect!');
}

function initializeCompatMode()
{
	var request = { type: "GETCOMPATMODE" };
	chrome.extension.sendRequest(request, function(result) {
		if (!result)
			result = "IE7S";
		for (var i = 0; i < modes.length; i++) {
			var el = document.getElementById("mode" + modes[i]);
			if (modes[i] == result) {
				el.checked = true;
			}
			else {
				el.checked = false; 
			}

			el.addEventListener("click", modeClicked, false);
		}
	});
	
}

//
// initLocalizedStrings
//
// Use i18n to retrieve localized text
//
function initLocalizedStrings()
{
	// Find all spans with the attribute "loctext"
	var keys = [];
	var all = document.getElementsByTagName("*");
	for(var i=0; i<all.length; i++)
	{
		var locText = all[i].getAttribute("loctext");
		if(locText)
			keys.push(locText);
	}
	
	// Get the loczlied values
	chrome.extension.sendRequest({ type: "GETLOCTEXT", keys: keys }, function(result) {
		if (!result)
			return;

		// And set them
		var locStrings = {};
		for (var i = 0; i < all.length; i++) {
			var el = all[i];
			var locText = el.getAttribute("loctext");
			if (locText && result[locText]) {
				var attr = el.getAttribute("locattr");
				if (attr)
					el.setAttribute(attr, result[locText]);
				else
					el.textContent = result[locText];
			}
		}
	});
}

function onOptions()
{
    var request = { type: "SHOWOPTIONS" };
    chrome.extension.sendRequest(request);
}

function init()
{
	initializeAddressList();
	initializeExclusionList();
    initializeAutoUrlsEnabled();
    initializeChromePopupsEnabled();
    initializeShowSearchBox();
    initializeAutoSearch();
    initializeUrlBox();
    initializeCompatMode();
    document.getElementById("addressText").focus();
    document.getElementById("addButton").addEventListener("click", onAdd, false);
    document.getElementById("removeButton").addEventListener("click", onRemove, false);
    document.getElementById("xaddButton").addEventListener("click", xonAdd, false);
    document.getElementById("xremoveButton").addEventListener("click", xonRemove, false);
    document.getElementById("showIEOptions").addEventListener("click", onOptions, false);
    
    initLocalizedStrings();
}

window.onload = init;
