/**
 * @author WhiteSpi
 */
var COMUFY={};
COMUFY.Utils = {
	/**
	 * Includes a CSS file
	 * @param {p_file} Path to the CSS file
	 */
	includeCSS: function(p_file) {
		var v_css  = document.createElement('link');
		v_css.rel = 'stylesheet'
		v_css.type = 'text/css';
		v_css.href = p_file;
		document.getElementsByTagName('head')[0].appendChild(v_css);
	}
}

if (document.domain == "tweetswitch.com"){
	var ajaxFE = "http://www.comufy.com/ajaxFE"
}
else {
	var ajaxFE = "http://www.dev.comufy.com/ajaxFE";
}

/**
 * Get URL parameters
 * @param {Object} name
 */
function gup( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

var lang = gup( 'lang' ) || "en";




//function loadLibs(){
$LAB
/**
 * Load prototype
 */
.script(ajaxFE+"/javascripts/lib/prototype.js")
.block()
/**
 * Now load scriptaculoud libraries. We load them manually to be able to block(). If we don't do this, bloody IE will crash randomly
 */
.script(ajaxFE+"/javascripts/lib/scriptaculous/builder.js")
.block()
.script(ajaxFE+"/javascripts/lib/scriptaculous/effects.js")
.block()
.script(ajaxFE+"/javascripts/lib/scriptaculous/dragdrop.js")
.block()
//.script(ajaxFE+"/javascripts/lib/scriptaculous/controls.js")
//.block()
.script(ajaxFE+"/javascripts/lib/json2.js")
.block()


/**
 * Now, load our actual code.
 */
.script("js/jXHR.js")
.script(ajaxFE+"/javascripts/lib/validation.js")
.script(ajaxFE+"/javascripts/main.js")
.block( function(){
	/**
	 * Try to login the user only if he is in the homepage
	 */
	if (location.pathname != "/") return;
	
	var token = getToken();
	if (token != null && token != "") {
		TWEETSWITCH.ConfigPanel.loadingConfigPanel();
	}
})//Main initialises the COMUFY object which other scrips extend
.script(ajaxFE+"/javascripts/contact.js")

.script(ajaxFE+"/javascripts/protocol/protocol.js")
.block()//Initialises COMUFY.Protocol
.script(ajaxFE+"/javascripts/protocol/codes.js")
.script(ajaxFE+"/javascripts/protocol/com.js")
.block()
.script({src:ajaxFE+"/javascripts/protocol/custom/tweetswitch.js", allowDup:true})
//.script(ajaxFE+"/javascripts/protocol/REST.js")
//.script(ajaxFE+"/javascripts/protocol/SOAP.js")

.script(ajaxFE+"/javascripts/messenger.js")
.script({src: ajaxFE + "/javascripts/lang/" + lang + ".js",allowDup: true})
.script(ajaxFE+"/javascripts/configPanel.js")
.script(ajaxFE+"/javascripts/account.js")
.script(ajaxFE+"/javascripts/UI/ui.js")
.block()//Initialises COMUFY.UI
.script({src: ajaxFE+"/javascripts/UI/trash.js",allowDup: true})
.script({src: ajaxFE+"/javascripts/UI/dock.js",allowDup: true})
.script({src: ajaxFE+"/javascripts/UI/configPanel.js",allowDup: true})
.script({src: ajaxFE+"/javascripts/UI/window.js",allowDup: true})
.script({src: ajaxFE+"/javascripts/UI/help.js",allowDup: true})
.script({src: ajaxFE+"/javascripts/UI/account.js",allowDup: true})
.script({src: ajaxFE+"/javascripts/UI/messenger.js",allowDup: true})
.script(ajaxFE+"/javascripts/UI/embed.js")
.block()
.script(ajaxFE+"/javascripts/init.js")
.block(tweetSwitchInit);


COMUFY.Utils.includeCSS(ajaxFE+"/stylesheets/validationStyle.css");
COMUFY.Utils.includeCSS(ajaxFE+"/stylesheets/configuration_panel.css");
COMUFY.Utils.includeCSS(ajaxFE+"/stylesheets/addAccount_window.css");
COMUFY.Utils.includeCSS(ajaxFE+"/stylesheets/instancesIcons.css");
COMUFY.Utils.includeCSS(ajaxFE+"/stylesheets/contacts.css");
COMUFY.Utils.includeCSS(ajaxFE+"/stylesheets/window.css");
COMUFY.Utils.includeCSS(ajaxFE+"/stylesheets/accounts.css");
COMUFY.Utils.includeCSS(ajaxFE+"/stylesheets/embed.css");


//Executes once the DOM has been properly loaded	
function tweetSwitchInit(){
	
	
	COMUFY.Config.DISPCONTACTLIST = false;
	COMUFY.Config.DISPDOCK = false;
	COMUFY.Config.SHOWPID0 = false;
	COMUFY.Config.REQUIRESTOKEN = false;
	COMUFY.Config.DOMAIN = "tweetswitch";
	if (document.domain == "tweetswitch.com") {
		COMUFY.Config.CONFPANEL_DRAGGABLE = false;
		COMUFY.Config.SSLURL = 'https://www.comufy.com/tweetswitch-web/tweetswitch';
		COMUFY.Config.URL = 'https://www.comufy.com/tweetswitch-web/tweetswitch';
		
		//REG CLOSED
		//if (ip != "81.106.104.242" && ip != "78.105.17.88") {
		//	TWEETSWITCH.ConfigPanel.dispRegClosed();
		//	return;
		//}//TWEETSWITCH.ConfigPanel.dispError("TweetSwitch is being upgraded for a few minutes. Please try again later.");
		
	}
	else {//dev
		COMUFY.Config.SSLURL = 'https://www.comufy.com/tweetswitch-web/tweetswitch';
		COMUFY.Config.URL = 'https://www.comufy.com/tweetswitch-web/tweetswitch';
	}
		
	/**
	 * OVERWRITE COMUFY METHODS
	 */
	COMUFY.Config.ERRORMETHOD = TWEETSWITCH.ConfigPanel.dispError;
	COMUFY.UI.Message.newDaemon = function(daemon, pid, name){
		var msg = TWEETSWITCH.Lang.Generic.addDaemonBody;
		msg = msg.replace(/<DAEMON_ACCOUNT>/g,"<b>"+daemon+"</b>");
		msg = msg.replace(/<PROTOCOL>/g,COMUFY.Protocol.Core.getNameFromProtoID(pid));
		TWEETSWITCH.ConfigPanel.dispMsg(TWEETSWITCH.Lang.Generic.addDaemonTitle, msg);
	}
		
	/***********************/
	if (location.pathname != "/" && location.pathname != "/login") return;//If we are not in the index page, return;
	
	if (!window.XMLHttpRequest) {
		// IE6, older browsers
		TWEETSWITCH.ConfigPanel.dispError(TWEETSWITCH.Lang.Generic.Error.browserNotSupported);
		return;
	}

			
	//TWEETSWITCH.ConfigPanel.observeElements();	
	var token = getToken();
	//If the user already has a token
	if (token != null && token != "") {
		TWEETSWITCH.ConfigPanel.oauth_token = token;
		COMUFY.Protocol.Com.comsInterface.ConfigPanel.getUserDetails('TWEETSWITCH.ConfigPanel.setUser(res)', 'TWEETSWITCH.ConfigPanel.dispErrorNumber(res.cd)');
	}
	
	//Redefining the method which asks for relogin on Comufy.
	COMUFY.Protocol.Core.askRelogin = function(){
		TWEETSWITCH.ConfigPanel.dispError("Problem connecting to the backend. Please try again later.");
	}	
};

function getToken(){
	var token = gup( 'oauth_token' );
	if (token != null && token != "") {
		setCookieToken(token);
	}
	
	//else, see if we have a cookie
	else {
		token = Cookies.get("oauth_token");
	}
	
	return token;
}

function setCookieToken(token){
	if (token != "") {
		//alert("back from Twitter");
		var exdate=new Date();
		exdate.setDate(exdate.getDate()+182);//Valid for 6 months
		Cookies.set("oauth_token", token, exdate, "");
	}
}

function performLogin(res){
	if (res.cd == COMUFY.Protocol.Codes._USER_DETAILS_OK
		|| res.cd == COMUFY.Protocol.Codes._LOGIN_OK){
			
		//register user if he's not already registered
		COMUFY.Core.login(res);
		
		$('mainBox').remove();
		$("footer").remove();
		$("fblike").remove();
		
		//disable SMS. (Hackers: don't even try, the backend disables this too).
		COMUFY.Protocol.Core.protocolArray[3].available = false;
		//disable Twitter.
		COMUFY.Protocol.Core.protocolArray[14].available = false
		
		TWEETSWITCH.ConfigPanel.dispConfigPanel('All Tweets',TWEETSWITCH.Lang.Generic.Tabs.tweetDesc);
		
		$('menu_msg').update("");
		
		//Remove email
		$("COMUFY_email_txt").parentNode.remove();
		$$(".COMUFY_im_email")[0].remove();
		//Deal with wizard
		TWEETSWITCH.Wizard.init();
		
		
		TWEETSWITCH.ConfigPanel.addGroupTabs();

		//Clear old menu bar
		$$('#menuTabs li')[1].remove();
		$$('#menuTabs li')[1].className = "emptyTab";
		$$('#menuTabs li')[1].update("");
		
		//Add group tabs
		TWEETSWITCH.ConfigPanel.dispPauseCheckbox(res.active);

		
		//Now insert the human language help
		TWEETSWITCH.ConfigPanel.autoRefreshHumanLanguage();
		TWEETSWITCH.ConfigPanel.insertPrefBoxesHelp();
		//TWEETSWITCH.ConfigPanel.insertTweetBox();
		//TWEETSWITCH.ConfigPanel.dispTwitterWidget();
		
		//Add Google analytics tracking
		COMUFY.UI.Embed.ConfigPanel.addGoogleTracker();
	}
	else{
		TWEETSWITCH.ConfigPanel.dispError(TWEETSWITCH.Lang.Generic.Error.systemCouldNotLogin);
	}
}


