// DMS2.0 :: Dust-Me Selectors
//***************************************************************************
// Copyright 2007 SitePoint Pty Ltd -- http://www.sitepoint.com/
// Written by brothercake -- http://www.brothercake.com/
// MIT License -- http://opensource.org/licenses/mit-license.php
//***************************************************************************

/* NOTE:
this script is included by browser.xul, preferences.xul and spider.xul
however the dialogs are child windows of the main browser
so each of those instances expects a different window heirarchy
*/

//dust-me selectors preferences object
DustMeSelectors_preferences = new Object();

//this version
DustMeSelectors_preferences.version = '2.0';

//default accepted mime-types
DustMeSelectors_preferences.mimetypes = {
	'sitemap' : 'text/html,application/xhtml+xml,text/xml,application/xml', 
	'pages' : 'text/html,application/xhtml+xml'
	};

//define a list of user preferences
//and their associated default values
DustMeSelectors_preferences.defaults = {
	'disable' : false,
	'showinstatus' : true,
	'saveperhost' : true,
	'ignorewww' : true,
	'ignoreports' : false,
	'clearconfirm' : true,
	'restart' : true, 
	'nofollow' : true, 
	'ignorefragment' : true, 
	'ignorequery' : false, 
	'includeelements' : true,
	'accountforhacks' : true,
	'autorun' : false,
	'mutation' : true,
	'openafterautorun' : false,
	'openafterfind' : true,
	'remember' : true,
	'openafterspider' : true,
	'usepreffolder' : true,
	'specifyfolder' : false,
	'datafolder' : '',
	'version' : ''
	};



//create a preferences service for storing and retrieving data
//(btw. I got this code, and the basis of code for working with it, from greasemonkey)
DustMeSelectors_preferences.prefservice = Components.classes["@mozilla.org/preferences-service;1"]
	.getService(Components.interfaces['nsIPrefService']).getBranch('extensions.dustmeselectors.');




//preferences dialog loaded
DustMeSelectors_preferences.preferencesDialogLoaded = function()
{
	//if we have an options flag in the query string
	//disable the disable checkbox, because we
	//won't be able to refer to the main window to update the UI
	if(location.search && location.search.indexOf('options=true') != -1)
	{
		document.getElementById('dms-preference-disable').setAttribute('disabled', true); 
	}
	
	//for each of the preference widgets, get the associated preference
	//and then modify the value as applicable
	for(var i in this.defaults)
	{
		if(!this.defaults.hasOwnProperty(i)) { continue; }

		//checkboxes
		var checkbox = document.getElementById('dms-preference-' + i);
		if(checkbox)
		{
			checkbox.setAttribute('checked', this.getPreference('boolean', i));
			this.handleCheckboxChange(checkbox);
			continue;
		}

		//radio buttons
		var radio = document.getElementById('dms-preference-radio-' + i);
		if(radio)
		{
			radio.setAttribute('selected', this.getPreference('boolean', i));
			this.handleRadioChange(radio);
			continue;
		}

		//textboxes
		var text = document.getElementById('dms-preference-text-' + i);
		if(text)
		{
			text.setAttribute('value', this.getPreference('string', i));
			continue;
		}
	}
};



//handle a change event on a particular checkbox
DustMeSelectors_preferences.handleCheckboxChange = function(checkbox)
{
	//is this checkbox checked?
	var ischecked = checkbox.getAttribute('checked') == 'true' ? true : false;

	//switch by checkbox
	switch(checkbox.id.replace('dms-preference-', ''))
	{
		//"Save data for each site separately" and
		//"Run at page load"
		case 'saveperhost' :
		case 'autorun' :

			//get the collection of related checkboxes in the next sibling box
			//then iterate through them and set them enabled or disabled accordingly
			var options = checkbox.nextSibling.getElementsByTagName('checkbox');
			for(var i=0; i<options.length; i++)
			{
				options[i].setAttribute('disabled', !ischecked);
			}

			break;
	}
};



//handle a change event on a particular radio
DustMeSelectors_preferences.handleRadioChange = function(radio)
{
	//is this radio selected?
	var isselected = radio.getAttribute('selected') == 'true' ? true : false;

	//switch by radio
	switch(radio.id.replace('dms-preference-radio-', ''))
	{
		//use preferences folder
		case 'usepreffolder' :

			//disable the folder textbox and browse button if this is selected
			document.getElementById('dms-preference-text-datafolder').setAttribute('disabled', isselected);
			document.getElementById('dms-preference-browsebutton').setAttribute('disabled', isselected);

			break;

		//specify folder folder
		case 'specifyfolder' :

			//disable the folder textbox and browse button if this is not selected
			document.getElementById('dms-preference-text-datafolder').setAttribute('disabled', !isselected);
			document.getElementById('dms-preference-browsebutton').setAttribute('disabled', !isselected);

			break;
	}
};



//choose a data folder
DustMeSelectors_preferences.chooseDataFolder = function()
{
	//create and show a folder picker interface
	var nsIFilePicker = Components.interfaces.nsIFilePicker;
	var filepointer = Components.classes["@mozilla.org/filepicker;1"].createInstance(nsIFilePicker);
	filepointer.init(window, '', nsIFilePicker.modeGetFolder);
	var result = filepointer.show();

	//if we get a successful result from the dialog
	//(ie, a folder has been named or selected)
	if(result == nsIFilePicker.returnOK || result == nsIFilePicker.returnReplace)
	{
		//write it to the text field
		document.getElementById('dms-preference-text-datafolder').setAttribute('value', filepointer.file.path);
	}
};



//accept preferences changes
DustMeSelectors_preferences.acceptChanges = function()
{
	//get all the active checkboxes and radios in the dialog
	//then itereate through them and save each of their values to preference
	var widgets = ['checkbox', 'radio'], attrs = ['checked', 'selected'];
	for(var n=0; n<widgets.length; n++)
	{
		var elements = document.getElementsByTagName(widgets[n]);
		for(var i=0; i<elements.length; i++)
		{
			if(elements[i].id == '') { continue; }
			this.setPreference('boolean',
				elements[i].id.replace(/(dms\-preference\-(radio\-)?)/, ''),
				elements[i].getAttribute(attrs[n]) == 'true' ? true : false);
		}
	}

	//if specifyfolder is selected and the value of the datafolder textbox is not empty
	//set the path to the folder in preferences,
	var datafolder = document.getElementById('dms-preference-text-datafolder').getAttribute('value');
	if(datafolder != '' && document.getElementById('dms-preference-radio-specifyfolder').getAttribute('selected'))
	{
		this.setPreference('string', 'datafolder', datafolder);
	}
	//if it wasn't selected or the datafolder was empty
	//set an empty string for the datafolder, and reset the folder preferences
	else
	{
		this.setPreference('string', 'datafolder', '');
		this.setPreference('boolean', 'usepreffolder', true);
		this.setPreference('boolean', 'specifyfolder', false);
	}

	//if we have an open parent window with the browser object in it
	//run the management functions to update its UI
	//but without updating any preferences, just reflecting them
	if(window.opener && !window.opener.closed 
		&& typeof window.opener.DustMeSelectors_browser != 'undefined')
	{
		window.opener.DustMeSelectors_browser.doSetAutorunPreference(false);
		window.opener.DustMeSelectors_tools.initialiseDataSavingOptions();
		window.opener.DustMeSelectors_browser.updateControlSettings();
		window.opener.DustMeSelectors_browser.setDisabledPreference(false);
	}
	
	//hide or show the status overlay according to preference
	window.opener.DustMeSelectors_browser.setUIState('statusoverlay', 
		!document.getElementById('dms-preference-showinstatus').checked);
};



//get a preference from the preference service
//or return the default value if none exists
//or a default [type of] object if no default exists
//the prefservice throws an exception if the specified preference doesn't exist
//hence the use of try..catch to read it
DustMeSelectors_preferences.getPreference = function(preftype, prefname)
{
	var prefmethods = {
		'boolean' : 'getBoolPref',
		'string' : 'getCharPref'
		};

	if(typeof this.defaults[prefname] != 'undefined')
	{
		var def = this.defaults[prefname];
	}
	else
	{
		switch(preftype)
		{
			case 'string' : def = ''; break;
			case 'boolean' : def = false; break;
			case 'number' : def = 0; break;
		}
	}

	try
	{
		var pref = this.prefservice[prefmethods[preftype]](prefname);
		if(pref === '') { pref = def; }
	}
	catch(err)
	{
		pref = def;
	}

	return pref;
};



//set a preference in the preference service
DustMeSelectors_preferences.setPreference = function(preftype, prefname, prefvalue)
{
	var prefmethods = {
		'boolean' : 'setBoolPref',
		'string' : 'setCharPref'
		};

	this.prefservice[prefmethods[preftype]](prefname, prefvalue);
};






