onX = {
	onCreate:  function(){
		if ($("loading")) return;
		
		$$('body')[0].insert(
			new Element("div", {id:'loading'}).update(
				TWEETSWITCH.Lang.Generic.Loading
			)
		);
	    TWEETSWITCH.ConfigPanel.darkCloack();
	},
	onComplete: function(){
		$('loading').remove();
        $('bodyWrapper').remove();
	}
}
		
TWEETSWITCH = {};
TWEETSWITCH.Config={
	FIRST_TIME_LOGIN: true,
	TWEETSWITCH_AJAX_HELPER: "http://"+document.domain+"/lib/ajaxUtils.php",
	BEDOWN: false
};

TWEETSWITCH.ConfigPanel = {
	loginData: "",//The login data returned by the backend
	oauth_token: "",
	customTabs:[],
	
	loadingConfigPanel: function(){
		onX.onCreate();
		$("loading").insert(
			new Element("a", {className:"cancelLogin", onClick:"TWEETSWITCH.ConfigPanel.logout();"}).update(TWEETSWITCH.Lang.Generic.login.cancelLogin)
		)
	},
	
	/**
	 * Returns the configuration in plain English
	 */
	getHumanLanguageSettings: function(){
		var s = "<h1>" + TWEETSWITCH.Lang.Generic.HumanLanguageSettings.config + "</h1>";
		
		var config = '';
		for (var i = 1, j = COMUFY.UI.ConfigPanel.content_boxes.length; i < j; i++) {
			if (i != 1 && COMUFY.UI.ConfigPanel.content_boxes[i].length > 0) {
				config += "<br/><h2>" + TWEETSWITCH.Lang.Generic.HumanLanguageSettings.not_available + TWEETSWITCH.Lang.Generic.HumanLanguageSettings.receiveTweets + "</h2>";
				config += "<ul>";
			}
			
			for (k = 0, l = COMUFY.UI.ConfigPanel.content_boxes[i].length; k < l; k++) {
				config += "<li>";
				var pname = COMUFY.Protocol.Core.getDescFromProtoID(COMUFY.UI.ConfigPanel.content_boxes[i][k].protocol);
				config += pname + " (" + COMUFY.UI.ConfigPanel.content_boxes[i][k].acname + ")";
				config += "</li>";
			}
			
			if (i != 1 && COMUFY.UI.ConfigPanel.content_boxes[i].length > 0) {
				config += "</ul>";
			}
		}
		
		if (config == '') {
			s += "<h2>" + TWEETSWITCH.Lang.Generic.HumanLanguageSettings.not_configured + "</h2>";
		}
		else {
			s += "<h2>" + TWEETSWITCH.Lang.Generic.HumanLanguageSettings.receiveTweets + "</h2>" + config;
		}
		
		return s;
	},
	
	/**
	 * Inserts the human language window
	 */
	insertHumanLanguagePanel: function(){
		TWEETSWITCH.ConfigPanel.insertHelpMenu("humanLanguageHelp", TWEETSWITCH.ConfigPanel.getHumanLanguageSettings());
	},
	
	
	/**
	 * Inserts the human language window
	 */
	insertPrefBoxesHelp: function(){
		TWEETSWITCH.ConfigPanel.insertHelpMenu("prefBoxesHelp", "<h1>" + TWEETSWITCH.Lang.Generic.PrefBoxesHelp.boxesHelpH1 + "</h1><h2>" + TWEETSWITCH.Lang.Generic.PrefBoxesHelp.boxesHelpH2 + "</h2>" +
		"<p><ul>" +
		"<li>" +
		TWEETSWITCH.Lang.Generic.PrefBoxesHelp.boxesHelpLi1 +
		"</li>" +
		"<li>" +
		TWEETSWITCH.Lang.Generic.PrefBoxesHelp.boxesHelpLi2 +
		"</li>" +
		"<li>" +
		TWEETSWITCH.Lang.Generic.PrefBoxesHelp.boxesHelpLi3 +
		"</li>" +
		"</ul>" +
		"</p>");
	},
	
	/**
	 * Inserts a new help menu with the specified text
	 * @param {String} panelID The id to be given to the panel
	 * @param {String} txt to be inserted in the panel
	 */
	insertHelpMenu: function(panelID, txt){
		//Now update the DOM
		if (!$("helpContainer")) {
			$$('body')[0].insert(new Element('div', {
				className: 'helpContainer',
				id: 'helpContainer'
			}));
		}
		
		var panel;
		if ($(panelID)) {
			panel = $(panelID);
		}
		else {
			panel = new Element('div', {
				className: "helpBox",
				id: panelID
			});
			$("helpContainer").insert(panel);
		}
		
		panel.update(new Element("span", {
			className: "top"
		})).insert(new Element("span", {
			className: "middle"
		}).update(txt)).insert(new Element("span", {
			className: "bottom"
		}));
	},
	/**
	 * Automatically refreshes the content of the Human language when a move happens
	 */
	autoRefreshHumanLanguage: function(){
		//COMUFY.UI.ConfigPanel.load_access_points();
		var oldLoad = COMUFY.UI.ConfigPanel.load_access_points;
		COMUFY.UI.ConfigPanel.load_access_points = function(current_conf_panel_grp){
			oldLoad(current_conf_panel_grp);
			TWEETSWITCH.ConfigPanel.insertHumanLanguagePanel();
		}
		TWEETSWITCH.ConfigPanel.insertHumanLanguagePanel();
	},
	
	/**
	 * Creates the box that users can tweet from.
	 */
	insertTweetBox: function(){
		$$('body')[0].insert(new Element('div', {
			className: 'tweetContainer'
		}).update(new Element('h2').update(TWEETSWITCH.Lang.Generic.TweetBox.whatAreYouDoing)).insert(new Element('div', {
			className: "charsCounter",
			id: "charsCounter"
		}).update("140")).insert(new Element('textarea', {
			className: 'tweetBox',
			id: 'tweetBox'
		})).insert(new Element('div', {
			className: "updateTweetOff",
			id: "updateTweetButton"
		}).update(TWEETSWITCH.Lang.Generic.TweetBox.update)));
		
		/**
		 * Now, put a watcher on the textarea to decrease the counter
		 */
		$("tweetBox").observe("keyup", function(e){
			var counter = $("tweetBox").value.length;
			if (counter > 0) {
				$("charsCounter").update(140 - counter);
				$("updateTweetButton").className = "updateTweetOn";
			}
		});
		
		/**
		 * Set the onclick button
		 */
		$("updateTweetButton").observe("click", function(e){
			//Don't do anything if the user hasn't types anything
			if ($("tweetBox").value.length == 0) 
				return;
			
			TWEETSWITCH.ConfigPanel.dispTempMsg(TWEETSWITCH.Lang.Generic.UpdateTweet.statusUpdated, 5000);
			$("tweetBox").value = "";
			$("updateTweetButton").className = "updateTweetOff";
			$("charsCounter").update(140);
		});
	},
	
	/**
	 * Displays a message at the top of the screen for a number of seconds
	 * @param {String} msg Message to be published
	 * @param {int} timer How long should the message be displayed for (in ms)
	 */
	dispTempMsg: function(msg, timer){
		timer = null || 5000;
		$$('body')[0].insert(new Element('div', {
			className: "tempMsg",
			id: "tempMsg"
		}).update(msg));
		window.setTimeout(function(){
			$("tempMsg").remove();
		}, timer);
	},
	
	dispTwitterWidget: function(){
		twitterWidget.render().TWEETSWITCH.ConfigPanel.setUser(COMUFY.Config.USERNAME).start();
		$("twtr-widget-1").setStyle({
			position: "absolute",
			top: "150px",
			left: "1020px"
		});
	},
	
	/**
	 * Puts a dark cloack around the entire page
	 */
	darkCloack: function(){
		$$('body')[0].insert(new Element('div', {
			id: 'bodyWrapper',
			style: 'background-color:#000000;  opacity:0.25;'
		}));
	},
	
	/**
	 * Close the registration form and removes the dark cloack
	 */
	closeRegForm: function(){
		$('bodyWrapper').remove();
		$('registerForm').remove();
	},
	
	/**
	 * Closes the error form and removes the dark cloack
	 */
	closeErrorForm: function(){
		$('errorDialog').remove();
		$('bodyWrapper').remove();
	},
	
	/**
	 * Closes the error form and removes the dark cloack
	 */
	closeMsgDialog: function(){
		$('msgDialog').remove();
		$('bodyWrapper').remove();
	},
	
	/**
	 * Adds a user to the waiting list
	 * If only the twitter name is provided, then only the twitter name is stored in the DB.
	 * If all is provided, then we check if the twitter name was alredy in the DB. If it was, we update the record. If not, we create a new one.
	 * @param {String} myEmail
	 * @param {String} myName
	 * @param {String} twitter
	 */
	addToWaitingList: function(myEmail, myName, twitter){
		var ACTION_SUCCESS = "";
		if (myEmail != "" && myName != "") {
			ACTION_SUCCESS = "$('sentSpan').update('" + TWEETSWITCH.Lang.Generic.AddToWaitingList.done + "');";
		}
		
		var responseHandler = new COMUFY.Protocol.Com.Tweetswitch.ResponseHandler([COMUFY.Protocol.Codes._ADD_TO_WAITING_LIST_OK], [], [], ACTION_SUCCESS, "");
		
		var pars = 'function=registerInterest&email=' + myEmail + '&name=' + myName + '&twitter=' + twitter;
		COMUFY.Protocol.Core.ajaxMonitor(pars, [], responseHandler, TWEETSWITCH.Config.TWEETSWITCH_AJAX_HELPER);
	},
	
	/**
	 * Registers a user to the DB
	 * This is performed once the user accepts the TNCs
	 * @param {String} name
	 */
	registerUser: function(name){
		new Ajax.Request(TWEETSWITCH.Config.TWEETSWITCH_AJAX_HELPER, {
			method: "post",
			postBody: "function=registerUser&name=" + name
		});
	},
	
	/**
	 * Checks if the user is allowed to login.
	 * If he is, ACTION_SUCCESS is executed.
	 * If not, ACTION_REVERT is executed
	 * @param {Object} name: Name of the contact
	 * @param {Object} ACTION_SUCCESS: Code to be executed in case of success
	 * @param {Object} ACTION_REVERT: Code to be executed in case of failure.
	 */
	loginAllowed: function(name, ACTION_SUCCESS, ACTION_REVERT){
		var responseHandler = new COMUFY.Protocol.Com.Tweetswitch.ResponseHandler([COMUFY.Protocol.Codes._LOGIN_ALLOWED], [], [COMUFY.Protocol.Codes._ERROR_REGISTRATION_CLOSE], ACTION_SUCCESS, ACTION_REVERT);
		var pars = 'function=loginAllowed&name=' + name;
		COMUFY.Protocol.Core.ajaxMonitor(pars, [], responseHandler, TWEETSWITCH.Config.TWEETSWITCH_AJAX_HELPER);
	},
	
	/**
	 * Checks if the user is already registered.
	 * If he is, ACTION_SUCCESS is executed.
	 * If not, ACTION_REVERT is executed
	 * This is useful to see if we should display the TNCs or not.
	 * @param {Object} name: Name of the contact
	 * @param {Object} ACTION_SUCCESS: Code to be executed in case of success
	 * @param {Object} ACTION_REVERT: Code to be executed in case of failure.
	 */
	/*isUserRegistered: function(name, ACTION_SUCCESS, ACTION_REVERT){  
	 ACTION_SUCCESS = "TWEETSWITCH.Config.FIRST_TIME_LOGIN = false;"+ACTION_SUCCESS;
	 ACTION_REVERT = "TWEETSWITCH.Config.FIRST_TIME_LOGIN = true;"+ACTION_REVERT;
	 var responseHandler = new COMUFY.Protocol.Com.Tweetswitch.ResponseHandler(
	 [COMUFY.Protocol.Codes._USER_IS_REGISTERED],[],[COMUFY.Protocol.Codes._USER_IS_NOT_REGISTERED],ACTION_SUCCESS,ACTION_REVERT
	 );
	 var pars='function=TWEETSWITCH.ConfigPanel.isUserRegistered&name='+name;
	 COMUFY.Protocol.Core.ajaxMonitor(pars, [], responseHandler, TWEETSWITCH.Config.TWEETSWITCH_AJAX_HELPER);
	 },*/
	/**
	 * Registration is closed.
	 * Display a form to allow them to be adde to the waiting list.
	 */
	/*dispRegClosed: function(){
		//We register the twitter username first. Always useful.
		TWEETSWITCH.ConfigPanel.addToWaitingList("", "", COMUFY.Config.USERNAME);
		
		//Then we ask him to input email address is he wants to.
		var str = "<div id='registerForm'>";
		str += "<div class='closeForm' onclick='TWEETSWITCH.ConfigPanel.closeRegForm()'></div>";
		str += "<h1>" + TWEETSWITCH.Lang.Generic.RegClosed.regClosed + "</h1>";
		str += "<p>" + TWEETSWITCH.Lang.Generic.RegClosed.registerEmailBelow + "</p>";
		str += "<h3 id='sentSpan'>" + TWEETSWITCH.Lang.Generic.RegClosed.addMeToWaitingList + "</h3>";
		str += "	<div class='formDivider'></div>";
		str += "		<table><tr><th>" + TWEETSWITCH.Lang.Generic.RegClosed.fname + "</th><th>" + TWEETSWITCH.Lang.Generic.RegClosed.email + "</th></tr>";
		str += "		<tr><td><input type='text' id='myName' value='First name' class='login_text_box' size='20' onclick='this.value=\"\";'/></td>";
		str += "			<td><input type='text' id='myEmail' value='tweetswitch@tweetswitch.com' class='login_text_box' size='20' onclick='this.value=\"\";' /></td>";
		str += "			<td><img src='img/btn_register.png' alt='sign up' onclick='TWEETSWITCH.ConfigPanel.addToWaitingList($(\"myEmail\").value, $(\"myName\").value, COMUFY.Config.USERNAME)' /></td>";
		str += "		</tr></table>";
		str += "</div>";
		$$('body')[0].insert(str);
		TWEETSWITCH.ConfigPanel.darkCloack();
	},*/
	dispRegClosed: function(){
		//We register the twitter username first. Always useful.
		TWEETSWITCH.ConfigPanel.addToWaitingList("", "", COMUFY.Config.USERNAME);
		
		//Then we ask him to input email address is he wants to.
		var str = "<div id='registerForm'>";
		str += "<div class='closeForm' onclick='TWEETSWITCH.ConfigPanel.closeRegForm()'></div>";
		str += "<h1>" + TWEETSWITCH.Lang.Generic.RegClosed.regClosed + "</h1>";
		str += "<p>" + TWEETSWITCH.Lang.Generic.RegClosed.registerEmailBelow + "</p>";
		str += "<h3 id='sentSpan'>" + TWEETSWITCH.Lang.Generic.RegClosed.addMeToWaitingList + "</h3>";
		str += "	<div class='formDivider'></div>";
		str += "		<table><tr><th>" + TWEETSWITCH.Lang.Generic.RegClosed.fname + "</th><th>" + TWEETSWITCH.Lang.Generic.RegClosed.email + "</th></tr>";
		str += "		<tr><td><input type='text' id='myName' value='First name' class='login_text_box' size='20' onclick='this.value=\"\";'/></td>";
		str += "			<td><input type='text' id='myEmail' value='tweetswitch@tweetswitch.com' class='login_text_box' size='20' onclick='this.value=\"\";' /></td></tr><tr>";
		str += "			<td><input type='text' id='myTwitter' value='twitter identifier' class='login_text_box' size='20' onclick='this.value=\"\";' /></td>";
		str += "			<td><img src='img/btn_register.png' alt='sign up' onclick='TWEETSWITCH.ConfigPanel.addToWaitingList($(\"myEmail\").value, $(\"myName\").value, $(\"myTwitter\").value)' /></td>";
		str += "		</tr></table>";
		str += "</div>";
		$$('body')[0].insert(str);
		TWEETSWITCH.ConfigPanel.darkCloack();
	},
	
	/**
	 * Displays an error message.
	 * @param {String} error message
	 */
	dispError: function(error){
		//Then we ask him to input email address is he wants to.
		var str = "<div id='errorDialog'>";
		str += "<div class='angryBird'></div>";
		str += "<div class='closeForm' onclick='TWEETSWITCH.ConfigPanel.closeErrorForm()'></div>";
		str += "<h1>" + TWEETSWITCH.Lang.Generic.Error.errorOccured + "</h1>";
		str += "<h3>" + error + "</h3>";
		str += "</div>";
		$$('body')[0].insert(str);
		TWEETSWITCH.ConfigPanel.darkCloack();
	},
	
	/**
	 * Displays a message in a dialog box.
	 * @param {String} message
	 */
	dispMsg: function(title, msg){
		//Then we ask him to input email address is he wants to.
		var str = "<div id='msgDialog'>";
		str += "<div class='closeForm' onclick='TWEETSWITCH.ConfigPanel.closeMsgDialog()'></div>";
		str += "<h1>" + title + "</h1>";
		str += "<h3>" + msg + "</h3>";
		str += "</div>";
		$$('body')[0].insert(str);
		TWEETSWITCH.ConfigPanel.darkCloack();
	},
	
	/**
	 * Displays an error message base on the error number.
	 * @param {String} error message
	 */
	dispErrorNumber: function(error){
		if (isNaN(error)) {
			error = error.cd;
		}
		
		if (error == "TWITTER ERROR NUMBER") {
			TWEETSWITCH.ConfigPanel.dispError(TWEETSWITCH.Lang.Generic.OAuth.errorRedirection);
		}
		
		if (error == "524") {
			TWEETSWITCH.ConfigPanel.dispError(TWEETSWITCH.Lang.Generic.OAuth.tokenInvalid);
		}
		else {
			TWEETSWITCH.ConfigPanel.dispError(COMUFY.Lang.LANGUAGE.ErrorCode.getErrorMessage(error));
		}
		
	},
	
	/**
	 * Displays the terms and conditions
	 * @param{boolean} forceScroll: If true, the user is forced to scroll down
	 * 								If false, he can close with a close button
	 */
	dispTNC: function(forceScroll){
		
		forceScroll = forceScroll || false;
		var tmp1 = TWEETSWITCH.Lang.Generic.TNC.TNCs;
		var tmp2 = TWEETSWITCH.Lang.Generic.TNC.service;
		
		var forceScrollElem1 = "";
		var forceScrollElem2 = "";
		var forceScrollElem3 = "";
		if (!forceScroll) {
			forceScrollElem1 = new Element("div", {
				className: "closeForm"
			});
		}
		else {
			forceScrollElem2 = new Element("div", {
				/**SCROLLING DISABLED**/
				/*className: "TNCAgreeOff",*/
				className: "TNCAgreeOn",
				id: "TNCAgree"
			});
			forceScrollElem3 = new Element("div", {
				className: "TNCNotAgree"
			});
		}
		var regForm = new Element("div", {
			id: 'registerForm'
		}).update(forceScrollElem1).insert(new Element("h1", {
			style: 'padding-bottom:0px'
		}).update(TWEETSWITCH.Lang.Generic.TNC.TNCs)).insert(new Element("div", {
			id: 'TNCForm'
		}).update(TWEETSWITCH.Lang.Generic.TNC.service)).insert(forceScrollElem2).insert(forceScrollElem3);
		
		$$('body')[0].insert(regForm);
		
		if (forceScroll) {
			/**REMOVE TO ENABLE SCROLLING**/
			$('TNCAgree').observe('click', function(){
				COMUFY.Protocol.Com.comsInterface.Twitter.getTwitterURL('TWEETSWITCH.ConfigPanel.redirectTo(res.url)', 'TWEETSWITCH.ConfigPanel.dispErrorNumber(res.cd)');
				TWEETSWITCH.ConfigPanel.closeRegForm();
			});
			/**END REMOVE TO ENABLE SCROLLING**/
			
			$('TNCForm').observe('scroll', function(){
				//IF the user scrolled down
				if ($('TNCForm').scrollHeight == ($('TNCForm').scrollTop + $('TNCForm').getHeight())) {
					$("TNCAgree").className = "TNCAgreeOn";
					$('TNCAgree').observe('click', function(){
						COMUFY.Protocol.Com.comsInterface.Twitter.getTwitterURL('TWEETSWITCH.ConfigPanel.redirectTo(res.authurl)', 'TWEETSWITCH.ConfigPanel.dispErrorNumber(res.cd)');
						TWEETSWITCH.ConfigPanel.closeRegForm();
					});
				}
			});
		}
		if (forceScroll) {
			$$('.TNCNotAgree')[0].observe('click', function(){
				TWEETSWITCH.ConfigPanel.closeRegForm();
			});
		}
		else {
			$$('.closeForm')[0].observe('click', function(){
				TWEETSWITCH.ConfigPanel.closeRegForm();
			});
		}
		
		TWEETSWITCH.ConfigPanel.darkCloack();
		
	},
	/**
	 * Observe elements
	 */
	/*observeElements: function(){
		$("loginDialog").observe('click', function(e){
			//If there is, display the TNCs
			//loginOrTNC();
			TWEETSWITCH.ConfigPanel.dispTNC(true);
		});
	},*/
	
	/**
	 * Redirects the user to a specific URL
	 * @param {String} URL
	 */
	redirectTo: function(URL){
		window.location = URL;
	},
	
	getOldFormat: function(newObjFormat){
		var accs = [];
		var accesspoints = [];
		var groups = [];
		for (var i = 0; i < newObjFormat.accounts.length; i++) {
			var protocol = COMUFY.Protocol.Core.getProtocolIdFromProtocolName(newObjFormat.accounts[i].transport);
			accs[i] = [protocol, newObjFormat.accounts[i].name];
			accesspoints.push({
				"protocol": protocol,
				"acname": newObjFormat.accounts[i].name,
				"alias": newObjFormat.accounts[i].name,
				"index": i
			//"direction":"RM"
			});
		}
		
		for (var i = 0; i < newObjFormat.groups.length; i++) {
			groups.push({
				"name": newObjFormat.groups[i],
				"delivery": [],
				"fixed":"N",
				"contacts":[]
			});
		}
		
		for (var i = 0; i < newObjFormat.preferences.length; i++) {
			for (var j = 0; j < accs.length; j++) {
				for (k = 0; k < groups.length; k++) {
					var protocol = COMUFY.Protocol.Core.getProtocolIdFromProtocolName(newObjFormat.preferences[i].account.transport);
					if (protocol == accs[j][0] &&
					newObjFormat.preferences[i].account.name == accs[j][1] &&
					groups[k].name == newObjFormat.preferences[i].group) {
						groups[k].delivery.push({
							"attempt": newObjFormat.preferences[i].attempt,
							"index": j
						});
					}
				}
			}
		}
		
			
		var oldObjFormat = {
			"cd":newObjFormat.cd,
			"new": 0,
			"user": newObjFormat.user,
			"active": newObjFormat.state,
			"stat": {
				"accesspoints": accesspoints,
				"groups": groups
			}
		};
		return oldObjFormat;
	},
	
	setUser: function(res){
		//First thing: Change the format of the response to match the old format
		res = TWEETSWITCH.ConfigPanel.getOldFormat(res);
		
		TWEETSWITCH.ConfigPanel.loginData = res;
		COMUFY.Config.USERNAME = res.user;
		TWEETSWITCH.ConfigPanel.registerUser(COMUFY.Config.USERNAME);
		//Now check if he is allowed to login.
		TWEETSWITCH.ConfigPanel.loginAllowed(COMUFY.Config.USERNAME, "performLogin(TWEETSWITCH.ConfigPanel.loginData)", 'TWEETSWITCH.ConfigPanel.dispRegClosed()');
	},
	
	/**
	 * Creates the dialog to add a new tab
	 */
	addTabDialog: function(){
		var str = "<div id='whiteBox'>";
		str += "<h1>" + TWEETSWITCH.Lang.Generic.ConfigPanel.whileBoxTitile + "</h1>";
		str += "<div class='whiteBox_content'>";
		str += "<p><label>" + TWEETSWITCH.Lang.Generic.ConfigPanel.whileBoxLabel_1 + "</label><input id='List' name='colType' type='radio' value='List' />" + TWEETSWITCH.Lang.Generic.ConfigPanel.checkBoxText_3 + "<input id='Search' name='colType' type='radio' value='Search' />" + TWEETSWITCH.Lang.Generic.ConfigPanel.checkBoxText_4 + "</p>";
		str += "<p><label for='userName'>" + TWEETSWITCH.Lang.Generic.ConfigPanel.whileBoxLabel_2 + "</label><input id='userName' name='userName' type='text' /></p>";
		str += "<p><button id='OK' name='OK' value='OK'/><span>" + TWEETSWITCH.Lang.Generic.ConfigPanel.btn_confirm + "</span></button><button id='CANCEL' /><span>" + TWEETSWITCH.Lang.Generic.ConfigPanel.btn_cancel + "</span></button></p>";
		str += "</div> <div class='whiteBox_footer'></div></div>";
		
        $$('body')[0].insert(str);	
		
		$("CANCEL").observe('click', function(e){
			$('whiteBox').remove();
			$('bodyWrapper').remove();
		});
		$("OK").observe('click', function(e){
			var selectedType = TWEETSWITCH.ConfigPanel.getSelectedInputForNewTab();
			if (!selectedType) return false;
			
			TWEETSWITCH.ConfigPanel.unselectTabs();
			
			TWEETSWITCH.ConfigPanel.addCustomTab(selectedType, $("userName").value);
			TWEETSWITCH.ConfigPanel.addTabListeners();
			
			$('whiteBox').remove();
			$('bodyWrapper').remove();
            
            TWEETSWITCH.ConfigPanel.conTags();
		});
		
		TWEETSWITCH.ConfigPanel.darkCloack();
	},
	
	/**
	 * Returns true if the tab already exists.
	 * Returns false otherwise
	 */
	tabExists: function(selectedType, val){
		for (var i = 0; i < TWEETSWITCH.ConfigPanel.customTabs.length; i++){
			if ( 
				TWEETSWITCH.ConfigPanel.customTabs[i][0] == selectedType
				&& TWEETSWITCH.ConfigPanel.customTabs[i][1] == val
			){
				return true;
			}
		}
		return false;
	},
	
	addCustomTab: function(selectedType, val){
		//Check if this tab already exists.
		//If exists
		if (TWEETSWITCH.ConfigPanel.tabExists(selectedType, val)){
			alert ("TO LANG FILES: Already exists");	
			return false;
		}
		else {
			TWEETSWITCH.ConfigPanel.customTabs[TWEETSWITCH.ConfigPanel.customTabs.length] = [selectedType,val];	
		}
		
		var insertBeforeElem = $$(".menu ul li")[$$(".menu ul li").length -1];
		insertBeforeElem.insert(
			{before:new Element("li",{className: "customTabLi", id:"custom_"+TWEETSWITCH.ConfigPanel.customTabs.length}).update(
				new Element("div", {className: "navigLinkSelectedLeft"}).update(
					new Element("a", {className: "navigLinkSelectedRight", id:"tweetsTab"}).update(
						"<span class='customTab'>"+selectedType+"</span> "+val
					)
				).insert(
					new Element("div", {id:"closeTab"+TWEETSWITCH.ConfigPanel.customTabs.length, className: "closeTab", 
						onclick:"TWEETSWITCH.ConfigPanel.removeCustomTab('custom_"+TWEETSWITCH.ConfigPanel.customTabs.length+"')"
					})
				)
			)}
		);
	},
	
	removeCustomTab: function(tabDOMID){
		$(tabDOMID).remove();
		TWEETSWITCH.ConfigPanel.selectTab(
			$$("#menu ul li div a")[0]
		);
	},
	
	unselectTabs: function(){
		$$("#menu ul li a").each(function(f){
			//if (e.innerHTML != f.innerHTML) {
				//Make it look unselected
				f.className = "";
				f.parentNode.className = "";
			//}
		});
		$$(".closeTab").each(function(f){
			f.hide()
		});
	},
	
	/**
	 * Finds which radio button was clicked when creating a new tab
	 */
	getSelectedInputForNewTab: function(){
		var val = false;
		$$(".whiteBox_content p input").each(function(e){
			if (e.checked){
				val = e.value;
			}
		});
		return val;
	},
	
	dispPauseCheckbox: function(active){
		var msg = (active == 1)? TWEETSWITCH.Lang.Generic.active : "<u style='color:grey'>"+TWEETSWITCH.Lang.Generic.paused+"</u>";
		var boxChecked = (active == 1);
		
		var tab = new Element('label', {
			className: "skyLabel"
		}).update(new Element('input', {
			type: "checkbox",
			className: "bannerCheckbox",
			id: "pauseCheckbox",
			checked: boxChecked
		})).insert(msg);
		$('menu_msg').insert(tab);
		
		$("pauseCheckbox").observe('click', function(e){
			if (this.checked) {
				//alert("checked")
				var ACTION_REVERT = "$('pauseCheckbox').checked = false";
				$('pauseCheckbox').parentNode.style.color = "white";
				COMUFY.Protocol.Com.comsInterface.ConfigPanel.start("",ACTION_REVERT);
			}
			else {
				//alert("unchecked")
				var ACTION_REVERT = "$('pauseCheckbox').checked = true";
				$('pauseCheckbox').parentNode.style.color = "grey";
				COMUFY.Protocol.Com.comsInterface.ConfigPanel.stop("",ACTION_REVERT);
			}
		});
	},
	
	/**
	 * Replaces navigation tabs by tabs to navigate between groups
	 */
	addGroupTabs: function(){	
		if (document.domain != "tweetswitch.com") {
			var addTabDialog = new Element("li", {onclick:"TWEETSWITCH.ConfigPanel.addTabDialog();", className:"addNewTab"});
		}
		
        $("menu").insert(
			new Element("ul",{id:"tweetsMenu"}).update(
				new Element("li").update(
					new Element("div", {className: "navigLinkSelectedLeft"}).update(
						new Element("a", {className: "navigLinkSelectedRight", id:"tweetsTab"}).update(TWEETSWITCH.Lang.Generic.Tabs.tweets)
					)
				)
			).insert(
				new Element("li").update(
					new Element("div").update( 
						new Element("a", {id:"DMsTab"}).update(TWEETSWITCH.Lang.Generic.Tabs.DMs)
					)
				)
			).insert(
				new Element("li").update(
					new Element("div").update( 
						new Element("a", {id:"MentionsTab"}).update(TWEETSWITCH.Lang.Generic.Tabs.mentions)
					)
				)
			).insert(
            	addTabDialog
		    )
		);
       
	   	if (document.domain != "tweetswitch.com") {
			$("menu").insert(
				new Element("span", {id:"rightMove"})
			);
			$("menu").insert(
				new Element("ul",{id:"menuMore",style:"display:none"})
			);
		}	
		
		TWEETSWITCH.ConfigPanel.addTabListeners();
	},
	
	addTabListeners: function(){
		//List through all the links
		$$("#menu ul li div a").each(function(e){
			//Observe each link
			e.observe("click", function(){
				TWEETSWITCH.ConfigPanel.selectTab(e);
			});
		});
	},
	
	selectTab: function(e){
		TWEETSWITCH.ConfigPanel.unselectTabs();
		
		//If a link is clicked, change its class, and all other links classes
		e.className = "navigLinkSelectedRight";
		e.parentNode.className = "navigLinkSelectedLeft";
		if (e.parentNode.parentNode.className == "customTabLi"){
			var idNb = e.parentNode.parentNode.id.replace("custom_","");
			$("closeTab"+idNb).show();
		}
		TWEETSWITCH.ConfigPanel.dispPanel(e);
	},
	
	dispPanel: function(e){
		//Now, display a different config panel
		switch (e.id){
			case "tweetsTab":
				TWEETSWITCH.ConfigPanel.dispConfigPanel('All Tweets',TWEETSWITCH.Lang.Generic.Tabs.tweetDesc);
				break;
			case "DMsTab":
				TWEETSWITCH.ConfigPanel.dispConfigPanel('DMs',TWEETSWITCH.Lang.Generic.Tabs.DMsDesc);
				break;
			case "MentionsTab":
				TWEETSWITCH.ConfigPanel.dispConfigPanel('Mentions',TWEETSWITCH.Lang.Generic.Tabs.mentionsDesc);
				break;
			default://Custom tabs
				break;
		}
	},
	
	dispConfigPanel: function(group, desc){
		COMUFY.UI.Embed.ConfigPanel.register(group,desc);
		$('COMUFY_config_close').stopObserving().observe('click',function (e){
			TWEETSWITCH.ConfigPanel.logout();
		});
	},
	
	logout: function(){
		Cookies.set("oauth_token", "");
		window.location="/";
	},
	
    /*
     * control the number of tags
     */
    conTags: function(direction) {
        var menuWidth = 0;
        var tagNum =  $$('#tweetsMenu li');     
        var tagVal = "";
        
        $$('#tweetsMenu li').each(function(e) {
            menuWidth += e.getWidth();
            if (menuWidth>500) { 
                if(!e.hasClassName('addNewTab')) {                    
                    tagVal =e.innerHTML;                  
                    $('rightMove').insert({bottom:new Element("li").update(tagVal)});
                    e.remove();
                }
            }
        });
        
        $('rightMove').observe('click', function(){           
            $('menuMore').show();
        });
    } 
};

