/**
  *  Copy the html file and the javascript file on your webserver

*/


String.prototype.trim = function () {return this.replace(/^\s*/, "").replace(/\s*$/, "")}

// Mail functions


var Mail = {
	// launch takes number of mails to be displayed and
	// the background colr that alternates between the messages
	launch: function(numMail, col) {
		Mail.init();
		Mail.params.mailDispNum = numMail;
		Mail.params.color = col;
		// get the authentication token
		Mail.transactions.getToken();		
	},

	// check for the devId in the html 		
	init: function() {
		if(!Mail.params.devId) Mail.params.devId = document.getElementById("MailContainer").getAttribute("devId");

	},

	// Logout of the OpenAuth, reset the UI

	kill: function() {
		clearTimeout(Mail.core.refresh);
		clearTimeout(Mail.core.listTimeout);
		Mail.core.refresh = null;
		Mail.core.listTimeout = null;
		var authFrame = document.getElementById("AuthFrame");
		authFrame.style.height = "0px";
		authFrame.style.display = "";
		// Logout of OpenAuth and SNS
		authFrame.src = Mail.params.logout + "?devId=" + Mail.params.devId + "&doSNSLogout=1&succUrl=about:blank&a=" + Mail.params.token;
		Mail.params.token = null;
		Mail.core.userName = null;
		Mail.core.showMail = true;
		Mail.ui.reset();
		document.getElementById("LaunchLink").style.display = "";
	}
}

// Initial parameters

Mail.params = {
	devId: null,
	token:null,
	refresh:null,
	color:null,
        locale:"en-us",
	mailDispNum:null,
	baseAuthURI:"https://api.screenname.aol.com",
        baseURL: "http://webmail.aol.com/",
	mailList:"https://api.mail.aol.com/mail/newMailList",
	mailCount:"https://api.mail.aol.com/mail/newMailCount",
	getToken:"https://api.screenname.aol.com/auth/getToken",
	getInfo: "https://api.screenname.aol.com/auth/getInfo",
	logout:"https://api.screenname.aol.com/auth/logout"
}

// Callbacks - these are called based on the Mail.core.requestData parameters
// and called at the Mail.core.acceptData

Mail.callbacks = {
	// get the authentication token from json
	getToken: function(json) {
		//alert("Code = " + json.response.statusCode);
		if(Mail.core.initCall) {
			Mail.core.initCall = false;
			if(json.response.statusCode != 200)
				return;
		}
		document.getElementById("LaunchLink").style.display = "none";
		if(json.response.statusCode == 200) {
			Mail.params.token = json.response.data.token.a;
			document.getElementById("MailContainer").style.display = "";
			Mail.transactions.getInfo();
		} else if (json.response.statusCode == 450 || json.response.statusCode == 401) {
			document.getElementById("AuthFrame").style.display = "none";
			Mail.core.showAuthWindow(json.response.data.redirectURL + "?uiType=mini&devId=" + Mail.params.devId);
		} else if (json.response.statusCode == 330) {
			Mail.kill();
		} else {
			//alert("Error! Status Code = " + json.response.statusCode);
			document.getElementById("ErrorMessage").style.display = "";
		}
	},

	// Get the screenname
	getInfo: function(json) {
		Mail.core.userName = json.response.data.userData.loginId;
		Mail.transactions.getList();
		var userName = document.getElementById("UserName");
		var greeting = userName.firstChild.data;
		userName.removeChild(userName.firstChild);
		var text = greeting.substr(0, greeting.indexOf("("));
		userName.appendChild(document.createTextNode(text + Mail.core.userName));
	},
	// Get the list of mails in Mail.core.messages
	// Can retrieve only 75 mails
	getList: function(json) {
		if(json.response.statusCode == 200) {
			clearTimeout(Mail.core.listTimeout);
			Mail.core.listTimeout = null;
			document.getElementById("ErrorMessage").style.display = "none";
			Mail.core.messageCount = json.response.data.mailList.messageList[0].messageCount;
			//alert("Message count: " + Mail.core.messageCount);
			Mail.core.messages = json.response.data.mailList.messageList[0].messages;
			if(Mail.core.messageCount == 75)
				Mail.transactions.getCount();
			else
				Mail.ui.displayMail();
			Mail.core.refresh = setTimeout("Mail.transactions.getList()", 300000);
		}
		else if (json.response.statusCode == 451 || json.response.statusCode == 500){
			//alert(json.response.statusCode);
			document.getElementById("MailContainer").style.display = "none";
			document.getElementById("ErrorMessage").style.display = "";
		}
	},
	// Get the mail count
	getCount: function(json) {
		Mail.core.messageCount = json.response.data.mailFolderCount.mailFolderData.mailFolderType[0].count;
		//alert("getCount called! Message count: " + Mail.core.messageCount);
		Mail.ui.displayMail();
	}
}


// Core functionality 

Mail.core = {
	MailData: [],
	initCall: true,
	messageCount: -1,
	messages:null,
	refresh:null,
	authTimeout:null,
	listTimeout:null,
	deepLink:1, // required for display message level linking
	showMail:true,
	// requestData calls the actual URI by placing <script src=URI> </script> in
	// the <head></head> of your document
	requestData: function(transactionObject) {
		var len = Mail.core.MailData.length;
		transactionObject.timestamp = Date.parse(new Date());
		Mail.core.MailData[len] = {};
		Mail.core.MailData[len].oScript = document.createElement("script");
		Mail.core.MailData[len].oScript.setAttribute("id","MailData-" + len);
		Mail.core.MailData[len].oScript.setAttribute("type","text/javascript");
		Mail.core.MailData[len].objData = transactionObject;
		if(transactionObject.dataURI.indexOf("?") == -1) {
			transactionObject.dataURI+="?r=" + len + "&nocache=" + Date.parse(new Date());
		} else {
			transactionObject.dataURI+="&r=" + len + "&nocache=" + Date.parse(new Date()) ;
		}
		//alert("requestData: " + transactionObject.dataURI);
		Mail.core.MailData[len].oScript.setAttribute("src",transactionObject.dataURI);
		document.getElementsByTagName("head")[0].appendChild(Mail.core.MailData[len].oScript);
	},

	// Accept json, call the respective callbacks
	// if type is getToken - callback - Mail.callbacks.getToken(json) is
	// called
	acceptData: function(json) {
		var requestId = parseInt(json.response.requestId);
		var code = parseInt(json.response.statusCode);
		var type = Mail.core.MailData[requestId].objData.type;
		//alert(type + " w/ code= " + code);
		if(code != 200) {
			if(code == 401 && type != "getToken") { 
				// only getToken expects a 401 - if we get it on any other, kill the session
				Mail.kill();
				return;
			}
		}
		eval("Mail.callbacks." + type + "(json)");
	},

	// Not authenticated - show the AOL OpenAuth window
	showAuthWindow: function(url) {
		var authFrame = document.getElementById("AuthFrame");
		authFrame.style.height = "443px";
		authFrame.src = "about:blank";
		authFrame.src = url + "&language=" + Mail.params.locale + "&nocache=" + Date.parse(new Date());
		setTimeout("document.getElementById('AuthFrame').style.display = ''",200);
		//AIM.core.debug("createAuthWindow: " + url + "&nocache=" + Date.parse(new Date()));
		Mail.core.watchAuthRequest();
		Mail.core.authTimeout = setTimeout("location.replace('#AUTHCANCEL')",120000);
	},

	// Check for the authentication request, 
	// if #AUTHDONE - authentication is successful
	watchAuthRequest: function() {
		var oLoc = location.href;
		if(oLoc.indexOf("#AUTHDONE") > -1) {
			clearTimeout(Mail.core.authTimeout);
			location.replace("#mail");
			document.getElementById("AuthFrame").style.display = "none";
			Mail.transactions.getToken();
		} else if (oLoc.indexOf("#AUTHCANCEL") > -1) {
			clearTimeout(Mail.core.authTimeout);
			location.replace("#mail");
			//setTimeout(Mail.transactions.getToken,100);
			document.getElementById("AuthFrame").style.display = "none";
			document.getElementById("LaunchLink").style.display = "";
		} else {
			clearTimeout(oTimeout);
			var oTimeout = setTimeout(Mail.core.watchAuthRequest,500);
		}
	}

}

// The mail transactions 

Mail.transactions = {
	// Attempts to get an OpenAuth token to access mail services. If the user is not authenticated
	//  then this will call a login screen.
	 
	getToken: function() {
		// receiveMessage - fix for FF3 login issue
		var receiveMessage = function(event) {
			if (event.origin == "https://api.screenname.aol.com") {
				if (event.data == "#AUTHDONE")
					location.replace("#AUTHDONE");
			}
		}

		try {
			window.addEventListener("message", receiveMessage, false);
		}
		catch (e)
		{ }
		
		var tObj = {
			dataURI: Mail.params.getToken + "?devId=" + Mail.params.devId + "&f=json&c=Mail%2Ecore%2EacceptData",
			type:"getToken"
		}
		Mail.core.requestData(tObj);
	},

	// Gets the userName.
	getInfo: function() {
		var tObj = {
		dataURI: Mail.params.getInfo + "?devId=" + Mail.params.devId + "&f=json&a=" + Mail.params.token + "&c=Mail%2Ecore%2EacceptData",
			 type:"getInfo"
		}
		Mail.core.requestData(tObj);
	},

	// Retrieves a list of the user's new mail. Max number of items is 75.
	getList: function() {
		if(Mail.core.refresh) {
			clearTimeout(Mail.core.refresh);
			Mail.core.refresh = null;
		}
		var tObj = {
			dataURI: Mail.params.mailList+ "?f=json&items=75&a=" + 
				Mail.params.token + "&devId=" + Mail.params.devId + "&c=Mail%2Ecore%2EacceptData",
			type:"getList"
		}
		Mail.core.requestData(tObj);
		Mail.core.listTimeout = setTimeout('document.getElementById("ErrorMessage").style.display = "";',5000);
	},

	// Called only if user has more than 75 new emails
	getCount: function() {
		var tObj = {
			dataURI: Mail.params.mailCount + "?f=json&a=" + 
				Mail.params.token + "&devId=" + Mail.params.devId + "&c=Mail%2Ecore%2EacceptData",
			type:"getCount"
		}
		Mail.core.requestData(tObj);
	}
}


/**
  * Display the UI 
*/


Mail.ui = {
	// Sets up mail module display
	displayMail: function() {
		if(AIM.params.sessionId == null)
			AIM.widgets.IMMe.launch();

		var mailCount = document.getElementById("MailCount");
		if(mailCount.firstChild)
			mailCount.removeChild(mailCount.firstChild);
		var mailBody = document.getElementById("MailBody");
		mailBody.style.display = "none";
		while(mailBody.hasChildNodes())
			mailBody.removeChild(mailBody.lastChild);
		if(Mail.core.messageCount > 0) {
			mailCount.appendChild(document.createTextNode(" (" + Mail.core.messageCount + ")"));
			for (var i = 0; i < Mail.core.messages.length && i < Mail.params.mailDispNum; i++) {
				var row = document.createElement("tr");
				if(i%2 == 1)
					row.style.backgroundColor = Mail.params.color;
				var sender = document.createElement("td");
				sender.width = "40%";
				var sendText = Mail.core.messages[i].sender;
				var compText = sendText.toLowerCase();
				if(compText.indexOf("@aol.com") > -1 || compText.indexOf("@aim.com") > -1 ||
					compText.indexOf(".aol.com") > -1) {
					var text = document.createElement("span");
					text.title = sendText;
					sendText = sendText.substr(0,sendText.indexOf("@"));
					text.appendChild(document.createTextNode(sendText));
					sender.appendChild(text);

					// Presence Info Code Update begins	
					var pres = document.createElement("a");
					pres.onclick = new Function("click", "AIM.ui.createIMWindow('"+sendText.toLowerCase()+"');return false;"); 
					var imgText = document.createElement("img");
					
					// Oscar API to get presence icon k - universal key, t - TargetUsername (ScreenName)
				    imgText.src="http://api.oscar.aol.com/presence/icon?k=ma1igiqyNMxPr4in&t="+sendText.toLowerCase(); 
					imgText.border="0";				
					pres.appendChild(imgText);
					text.appendChild(pres);;
					//Presence Info Code Update ends
				}
				else 
					if(sendText.length > 15) {
						var text = document.createElement("span");
						text.title = sendText;
						text.appendChild(document.createTextNode(sendText.substr(0,15) + "..."));
						sender.appendChild(text);
					}
					else
						sender.appendChild(document.createTextNode(sendText));
				var subject = document.createElement("td");
				var subText = Mail.core.messages[i].subject.trim();
				// If you have enabled deeplinking,
				// concatenate the uid to the message display
				if(Mail.core.deepLink) {
					var msgLink = Mail.core.messages[i].messageLink;
					var addr = Mail.params.baseURL + Mail.params.locale + "/" + msgLink.substr(msgLink.indexOf("Display"));
				}
				else
					var addr = document.getElementById("InboxLink").href;
				if(subText.length == 0)
					subText = "(NoSubject)";
				if(subText.length > 20) {
					var link = Mail.ui.createLink(subText.substr(0,17) + "...", addr);
					link.title = subText;
				}
				else
					var link = Mail.ui.createLink(subText, addr);
				link.target= "_blank";
				subject.appendChild(link);
				if(Mail.core.messages[i].read == 1) {
					sender.style.fontWeight = "normal";
					subject.style.fontWeight = "normal";
				}
				var sentOn = document.createElement("td");
				sentOn.style.textAlign = "right";
				sentOn.style.fontWeight = "normal";
				var sentText = Mail.ui.formatSentOn(i);
				sentOn.appendChild(document.createTextNode(sentText));
				row.appendChild(sender);
				row.appendChild(subject);
				row.appendChild(sentOn);
				mailBody.appendChild(row);
			}
		}

		if(Mail.core.showMail)
			setTimeout(Mail.ui.showMail,50);
		else
			setTimeout(Mail.ui.hideMail,50);
	},
	formatSentOn: function(msgPos) {
		var today = new Date();
		var year = today.getFullYear();
		var month = "" + (today.getMonth() + 1);
		var date = "" + today.getDate();
		if (month.length == 1)
			month = "0" + month;
		if (date.length == 1)
			date = "0" + date;
		var sendDate = Mail.core.messages[msgPos].sentOn;
		if (date == sendDate.substr(8,2) && month == sendDate.substr(5,2) && year == sendDate.substr(0,4)) {
			var msgHour = parseInt(sendDate.substr(11,2));
			var msgMin = sendDate.substr(14,2);
			return Mail.ui.formatTime(msgHour,msgMin);
		} else {
			var msgMonth = sendDate.substr(5,2);
			var msgDate = sendDate.substr(8,2);
			return Mail.ui.formatDate(msgMonth,msgDate);
		}
	},
	formatTime: function(hour,min) {
		if (Mail.params.locale == "en-us" || Mail.params.locale == "en-ca" || Mail.params.locale == "en-in" ||
			Mail.params.locale == "en-gb" || Mail.params.locale == "es-us") {
			if (hour/12 < 1) {
				if (hour == 0)
					hour = 12;
				return hour + ":" + min + "am";
			} else {
				if (hour != 12)
					hour %= 12;
				return hour + ":" + min + "pm";
			}
		} else {
			return hour + ":" + min;
		}
	},
	formatDate: function(mon,date) {
		if (mon.indexOf("0") == 0)
				mon = mon.substr(1);
		if (Mail.params.locale == "en-us" || Mail.params.locale == "es-us" || Mail.params.locale == "zh-cn")
			return mon + "/" + date;
		else if (Mail.params.locale == "de-de")
			return date + "." + mon;
		else
			return date + "/" + mon;
	},
	createLink: function(dispText, address) {
		var link = document.createElement("a");
		link.onclick = function() {window.openerContext=null;};
		link.href = address;
		link.target = "_blank";
		link.appendChild(document.createTextNode(dispText));
		return link;
	},
	toggleMail: function() {
		if(Mail.core.showMail) {
			Mail.ui.hideMail();
			Mail.core.showMail = false;
		}
		else {
			Mail.ui.showMail();
			Mail.core.showMail = true;
		}
		document.getElementById("HideLink").blur();
	},
	hideMail: function() {
		document.getElementById("MailTop").style.display = "none";
		document.getElementById("MailBody").style.display = "none";
		document.getElementById("NoMail").style.display = "none";
		document.getElementById("HideMail").style.display = "none";
		document.getElementById("ShowMail").style.display = "";
		
	},
	showMail: function() {
		if(Mail.core.messageCount > 0) {
			document.getElementById("NoMail").style.display = "none";
			document.getElementById("MailTop").style.display = "";
			document.getElementById("MailBody").style.display = "";
		}
		else {
			document.getElementById("MailTop").style.display = "none";
			document.getElementById("MailBody").style.display = "none";
			document.getElementById("NoMail").style.display = "";
		}
		document.getElementById("HideMail").style.display = "";
		document.getElementById("ShowMail").style.display = "none";
	},
	reset: function() {
		var userName = document.getElementById("UserName");
		var greeting = userName.firstChild.data;
		userName.removeChild(userName.firstChild);
		var text = greeting.substr(0, greeting.indexOf(" ") + 1);
		userName.appendChild(document.createTextNode(text + "(screenname)"));
		document.getElementById("MailTop").style.display = "none";
		document.getElementById("MailContainer").style.display = "none";
		document.getElementById("NoMail").style.display = "none";
		var mailBody = document.getElementById("MailBody");
		while(mailBody.hasChildNodes())
			mailBody.removeChild(mailBody.lastChild);
		mailBody.style.display = "";
		document.getElementById("HideMail").style.display = "none";
		document.getElementById("ShowMail").style.display = "none";
		var mailCount = document.getElementById("MailCount");
		if(mailCount.firstChild)
			mailCount.removeChild(mailCount.firstChild);
		document.getElementById("ErrorMessage").style.display = "none";
	}
}
