//MozCD Setup Preferences
//=======================

var mozcdProductName   = "Firemonger";
var mozcdProductPrefix = "firemonger";

var mozcdLiteVersion   = false;

//========End============

//Default install mode, changed via mozcdInstallType(type);
var mozcdInstallMode = "";
var mozcdQueue = new Array();

var mozcdLanguage = "";

function closeWindow() {
	window.close();
}

var codeOnLoad = null;

function reqLoadHandler() {

	var counter = this.responseText;

	var re = new RegExp("[0-9,]+");
	var numb = new String(re.exec(counter));

	if (numb.indexOf(',', numb.length - 1) >= (numb.length - 1)) {
		numb = numb.substr(0, numb.length - 1);
	}
	
	if (codeOnLoad) {
		eval(codeOnLoad);
	}
}

function req(url, code) {
try {
	codeOnLoad = code;
	netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");

	var p = new XMLHttpRequest();
	p.addEventListener("load", reqLoadHandler, false);
	p.open("GET", url, true);
	p.send(null);

	var numbCounter = new Number(p.responseText);
}
catch(err) {
} //Ignore errors...
}

function setLang(lang) {
	var prefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
	prefs.setCharPref("mozcd.lang", lang);
	prefs.setCharPref("general.useragent.locale", lang);
	
	mozcdLanguage = lang;
}

function mozcdResetLang() {
	var prefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
	
	prefs.setCharPref("mozcd.lang", "");
}

function saveAndOpenMain() {

	//Set language according to user preference
	var mozcdLanguage = document.getElementById("mozcd-language-list").selectedItem.value;
	setLang(mozcdLanguage);

	openMain();
}

function openMain() {	
	window.open("chrome://" + mozcdProductPrefix + "/content/" + mozcdProductPrefix + "_browse.xul","mozcd-main-window","chrome,centerscreen");
	closeWindow();
}

function openWindow(url) {	
	window.open(url,"mozcd-main-window","chrome,centerscreen");
	closeWindow();
}

//Check for a previously saved language
function mozcdCheckSavedLang() {
	var prefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
	var lang = prefs.getCharPref("mozcd.lang");

	if (lang != "") {
		setLang(lang);
		return true;
	}

	return false;
}

//Return the URL (without any parameters)
function mozcdGetURL(url) {
	var loc = new String(url);
	var arrSplit = loc.split("?");

	return arrParams[0];
}	

function mozcdGetURLParam(url, field) {
	var loc = new String(url);
	var arrParams = loc.split("?");

	if (arrParams.length < 2) {
		return false;
	}

	var arrParamSets = arrParams[1].split("&");

	for (var cur = 0; cur < arrParamSets.length; cur++ ) {
		arrParamValue = arrParamSets[cur].split("=");

		//If the paramter name matches the provided "field" return 
		//the value ([1]) if it exists. If not, just return true.
		if (arrParamValue[0] == field) {
			
			if (arrParamValue[1]) {

				var value = new String(unescape(arrParamValue[1]));
				value.replace(/\+/g, " ");

				return value;

			} else {
				return true;
			}
		}
	}

	//If we reached this point then we didn't find the requested field
	return false;
}

//Checks whether or not a file inside the chrome directory exists
//Useful for checking whether or not install files like themes
//and extensions exist
//This function is meant for xul files only (security privileges)
function mozcdXULPackageFileExists(filename) {

	var file = new String(filename);
	var mozcdDirService = Components.classes['@mozilla.org/file/directory_service;1'].getService(Components.interfaces.nsIProperties);
	var mozcdFile = mozcdDirService.get('CurProcD', Components.interfaces.nsILocalFile);
	
	with (mozcdFile) {
		append("chrome");
		append(mozcdProductPrefix);
		append("content");
		append(mozcdProductPrefix);
		append("install"); //Assume that all files are coming out of "install"

		var arrParts = file.split("/");

		for (var cur = 0; cur < arrParts.length; cur++) {
			append(arrParts[cur]);
		}
	}
	alert(filename + "\n\n" + mozcdFile.path);
	return mozcdFile.exists();
}

function mozcdRestartSelf() {

	if (navigator.appVersion.indexOf("Win") != -1) { //Windows
		
		var mozcdDirService = Components.classes['@mozilla.org/file/directory_service;1'].getService(Components.interfaces.nsIProperties);
		var mozcdProgram = mozcdDirService.get('CurProcD', Components.interfaces.nsILocalFile);
		var mozcdProcess = Components.classes["@mozilla.org/process/util;1"].getService(Components.interfaces.nsIProcess);
		var args = ["force"];

		mozcdProgram.append("..");
		mozcdProgram.append(mozcdProductPrefix + ".exe");

		mozcdProcess.init(mozcdProgram);
		mozcdProcess.run(false, args, args.length);

		//Close mozcd so as not to interfere with the installation (can't install while ff is running)
		setTimeout("window.parent.close()", 100);
	} else {
		alert(strings["OS_NOT_SUPPORTED"]);
	}	
}

function mozcdInstall(app) {

	//Setup the install service and get the current process directory
	var mozcdInstallDirService = Components.classes['@mozilla.org/file/directory_service;1'].getService(Components.interfaces.nsIProperties);
	var mozcdInstallProgram = mozcdInstallDirService.get('CurProcD', Components.interfaces.nsILocalFile);
	var mozcdInstallLang = mozcdInstallDirService.get('CurProcD', Components.interfaces.nsILocalFile);

	//The current process will be running in the "autorun" directory (or whatever you called it)
	//Installation files must be one level underneath (hence the ..) and in a directory called "installdata"
	//Note: Use of "append" is OS-independant... very important!
	mozcdInstallProgram.append("..");
	mozcdInstallProgram.append("installdata");
		
	//Make sure language variables are set up properly
	mozcdCheckSavedLang();

	//Check to see whether or not the program exists in a language specific directory
	//all defaults should be in "en-US" - cause thats where we look if we can't find 
	//a language specific file
	
	mozcdInstallLang.path = mozcdInstallProgram.path;

	mozcdInstallLang.append(mozcdLanguage);				//Append language specific directory
	mozcdInstallLang.append(mozcdApps[app].installdir); //Append program directory
	mozcdInstallLang.append(mozcdApps[app].installer);	//Append program's installer file
		
	//Note that if the current language IS en-US we are running through this twice
	//not really that important...
	if (mozcdInstallLang.exists()) {
		mozcdInstallProgram = mozcdInstallLang;
	} else  {
		mozcdInstallProgram.append("en-US");
		mozcdInstallProgram.append(mozcdApps[app].installdir);
		mozcdInstallProgram.append(mozcdApps[app].installer);
	}

	if (mozcdInstallProgram.exists()) {
		if (mozcdApps[app].reqclose) {
			var mozcdLauncher = mozcdInstallDirService.get('CurProcD', Components.interfaces.nsILocalFile);
			mozcdLauncher.append("..");

			if (navigator.appVersion.indexOf("Win") != -1) { //Windows
				mozcdLauncher.append(mozcdProductPrefix + ".exe");

				var mozcdInstallProcess = Components.classes["@mozilla.org/process/util;1"].getService(Components.interfaces.nsIProcess);

				try {
					var args = [mozcdInstallProgram.path, mozcdApps[app].redirect];
					
					mozcdInstallProcess.init(mozcdLauncher);
					mozcdInstallProcess.run(false, args, args.length);
				}
				
				//catch and alert about execution errors
				catch (err) {
					alert(err);
					//TODO: Display error on an error page...
					return false; //so as not to close down mozcd
				}

				//Close mozcd so as not to interfere with the installation (can't install while ff is running)
				setTimeout("window.parent.close()", 2000);

			} else { 
				alert(strings["OS_NOT_SUPPORTED"]);
			}
		} else {
			var mozcdInstallProcess = Components.classes["@mozilla.org/process/util;1"].getService(Components.interfaces.nsIProcess);
			
			mozcdInstallProcess.init(mozcdInstallProgram);
			mozcdInstallProcess.run(false,[],0);
			
			if (mozcdApps[app].redirect) {
				setTimeout("window.location = '" + mozcdApps[app].redirect + "'", 2000);
			}

			return true;
		}
	} else {
		//If we are arrive here the file does not exist in either a language-specific location or in the default.
		if (mozcdApps[app].url) { //Lets get the user to download the file
			var prefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
			var boolDownload = false;

			//Reset the "DontAskBeforeDownload" preference...
			//useful for first runs or corrupt settings
			if (prefs.getPrefType("mozcd.DontAskBeforeDownload") != prefs.PREF_BOOL){
				prefs.setBoolPref("mozcd.DontAskBeforeDownload", false);
			}

			if (prefs.getBoolPref("mozcd.DontAskBeforeDownload")) {
				boolDownload = true;
			} else {
				var promptService = Components.classes["@mozilla.org/embedcomp/prompt-service;1"].getService(Components.interfaces.nsIPromptService);

				var checkResult = {};
				var flags = promptService.BUTTON_TITLE_YES * promptService.BUTTON_POS_0 +
							promptService.BUTTON_TITLE_NO * promptService.BUTTON_POS_1;

				checkResult.value = true;
				var retVal = promptService.confirmEx(window, strings["DOWNLOAD_FILE"].title,
													 strings["DOWNLOAD_FILE"].text + "\n\nURL:\n" + mozcdApps[app].url + "\n\n",
													 flags, null, null, null,
													 strings["DOWNLOAD_FILE"].question, checkResult);

				if (retVal == 0) { //i.e. == YES
					boolDownload = true;
					
					if (checkResult.value == false) {
						prefs.setBoolPref("mozcd.DontAskBeforeDownload", true);
					}
				} else {
					setTimeout("window.location = '" + mozcdApps[app].dl_cancel + "'", 10);
					return false;
				}
			}

			if (boolDownload) {
				window.open(mozcdApps[app].url, mozcdApps[app].name, "scrollbars=yes, width=800,height=600,toolbar=1,resizable=1,location=1,status=1,menubar=1");

				window.location = mozcdApps[app].redirect;
			} else {
				setTimeout("window.location = '" + mozcdApps[app].redirect + "'", 2500);
			}

		} else {
			alert(eval(strings["LAUNCH_ERROR"]));
		}
	}
	
	return false;
}

//Used to return a link to either an extension or theme - locally or remote (according to Lite or not)
function mozcdGetInstallLink(name) {
	if (mozcdLiteVersion) {
		return mozcdInstallData[name].url;
	} else {
		return mozcdInstallData[name].file;
	}
}

function mozcdInstallTheme(arInstallData) {

	if (mozcdLiteVersion) {
		InstallTrigger.installChrome(InstallTrigger.SKIN, arInstallData.link, arInstallData.fullname);
	} else {
		InstallTrigger.installChrome(InstallTrigger.SKIN, arInstallData.file, arInstallData.fullname);
	}
}

function mozcdInstallExtensionEx(arrExtensions) {

	var xpi = new Object();

	for (var cur = 0; cur < arrExtensions.length; cur++) {
		xpi[arrExtensions[cur][0]] = arrExtensions[cur][1];
	}

	InstallTrigger.install(xpi);

	return true;
}

function mozcdInstallExtension(arInstallData) {

	var xpi = new Object();

	if (mozcdLiteVersion) {
		xpi[arInstallData.fullname] = arInstallData.url;
	} else {
		xpi[arInstallData.fullname] = arInstallData.file;
	}

	InstallTrigger.install(xpi); // second parameter = call back function on completion

	return true;
}


function htmlHideAll() {
	var i;

	var tabs = document.getElementById("tabs_content");

	for (i = 0; i < tabs.childNodes.length; i++) {
		var tag = tabs.childNodes[i];

		if ((tag.tagName && tag.tagName.toLowerCase() == "div") && (tag.id && tag.id.indexOf("mozcd_") == 0)) {
			htmlHide(tag.id);
		}
	}
}

function htmlHide(div) {
	document.getElementById(div).style.visibility = "hidden";
}

function htmlDisplay(div) {
	document.getElementById(div).style.visibility = "visible";
}

function htmlDisplayOnly(div) {
	var divname = "mozcd_" + div;
	htmlHideAll();

	htmlDisplay(divname);
}

function DisplayTab(tab) {
	var tabname = "tab_" + tab;
	var tabs = document.getElementById("tabs");
try {
	for (i = 0; i < tabs.childNodes.length; i++) {
		var curtab = tabs.childNodes[i];

		if (curtab.tagName) {
			if (curtab.tagName.toLowerCase() == "li" && (curtab.getAttribute("name") && curtab.getAttribute("name").indexOf("tab_") == 0)) {
				if (curtab.getAttribute("name") == tabname) {
					curtab.style.border = "3px ridge";
				} else {
					curtab.style.border = "1px solid";
				}
			}
		}
	}
} 
catch(err) {
	alert(err);
}
	htmlDisplayOnly(tab);
}

function mozcdFindqueueInstall(id) {

	for (var cur = 0; cur < mozcdQueue.length; cur++) {
		if (mozcdQueue[cur] == id) {
			return cur;
		}
	}
	
	// Install not queue
	return -1;
}

function mozcdAddInstall(id) {
	if (mozcdFindqueueInstall(id) < 0) {
		mozcdQueue[mozcdQueue.length] = id;

		var option = document.createElement("option");
		option.value = id;
		option.textContent = mozcdInstallData[id].name;
		document.getElementById('install_list').appendChild(option);

		if (document.getElementById('mozcd-queue-installbox').style.display == "none") {
			mozcdFloatInstallList();
		}
	}

}

function mozcdRemoveInstall(id) {
	
	var pos = mozcdFindqueueInstall(id);

	if (pos > -1) {
		mozcdQueue[pos] = "";

		mozcdListRemove(id);
	}
}

function mozcdAddRemoveInstall(id) {
	var checked = document.getElementById(id).checked;

	if (checked) {
		mozcdAddInstall(id);
	} else {
		mozcdRemoveInstall(id);
	}
	
}

function mozcdListRemove(id) {
	var list = document.getElementById('install_list');
	
	for (var cur = 0; cur < list.length; cur++) {
		if (list[cur].value == id) {
			list[cur] = null;
		}
	}

	if (list.options.length == 0) {
		document.getElementById('mozcd-queue-installbox').style.display = "none";
		document.getElementById('mozcd-queue-minibar').style.display = "none";
	}
}

function mozcdListRemoveInstall(id) {
	mozcdRemoveInstall(id);

	document.getElementById(id).checked = false;

	mozcdListRemove(id);
}

function mozcdFloatInstallList() {

	if (document.getElementById('mozcd-queue-installbox').style.display == "inline") {
		document.getElementById('mozcd-queue-installbox').style.display = "none";
		document.getElementById('mozcd-queue-bg').style.display = "none";
		document.getElementById('mozcd-queue-list').style.display = "none";
		document.getElementById('mozcd-queue-minibar').style.display="inline";
	} else {
		document.getElementById('mozcd-queue-installbox').style.display = "inline";
		document.getElementById('mozcd-queue-bg').style.display = "inline";
		document.getElementById('mozcd-queue-list').style.display = "inline";
		document.getElementById('mozcd-queue-minibar').style.display="none";
	}

}

function mozcdInstallType(type) {
	if (type) {
		mozcdInstallMode = type;
	}

	return mozcdInstallMode;
}

function mozcdWait(seconds) {
	var start = new Date();
	var diff = 0;

	do {
		var cur = new Date();
		diff = (cur.getTime() - start.getTime());
		//alert("cur: " + cur.getTime() + "\nStart: " + start.getTime() + "\nDiff: " + diff);
	
	} while (diff < (1000 * seconds));
}

function mozcdStartQueueInstall() {
	var install = "";
	var arrExtensions = new Array();
	//var arrThemes = new Array();
	var timeout = 0;
	
	for (var i = 0; i < mozcdQueue.length; i++) {
		if (mozcdQueue[i] != "" && mozcdInstallData[mozcdQueue[i]].file) {
			if (mozcdInstallType() == "themes") {
				mozcdInstallTheme(mozcdInstallData[mozcdQueue[i]]);
				//arrThemes[arrThemes.length] = [mozcdInstallData[mozcdQueue[i]].fullname, mozcdInstallData[mozcdQueue[i]].file];
				mozcdListRemoveInstall(mozcdQueue[i]);
			} else if (mozcdInstallType() == "ext") {
	
				if (mozcdLiteVersion) {
					arrExtensions[arrExtensions.length] = [mozcdInstallData[mozcdQueue[i]].fullname, mozcdInstallData[mozcdQueue[i]].url];
				} else {
					arrExtensions[arrExtensions.length] = [mozcdInstallData[mozcdQueue[i]].fullname, mozcdInstallData[mozcdQueue[i]].file];
				}

				mozcdListRemoveInstall(mozcdQueue[i]);
			} else {
				alert("Invalid install type called!");
			}
		}
	}

	if (mozcdInstallType() == "ext") {
		mozcdInstallExtensionEx(arrExtensions);
	}/* else if (mozcdInstallType() == "themes") {
		mozcdInstallThemesEx(arrThemes);
	}*/
}		
/*
function mozcdInstallThemesEx(arThemes) {

	var timeout = 100;

	for (var i = 0; i < arThemes.length; i++) {
		var strInstall = "InstallTrigger.installChrome(InstallTrigger.SKIN, '" + arThemes[i][1] + "','" +  arThemes[i][0] + "')";
		alert(eval(strInstall));
		setTimeout("alert(" + strInstall + ")", 100);
		mozcdWait(0.25);

		//alert(strInstall);
		timeout += 100;
	}

}*/

function mozcdScrollWorkaround(div) {
    var s = document.getElementById(div).scrollTop;
    document.getElementById(div + '_anchor').focus()
    document.getElementById(div).scrollTop = s;
}