/*
 * applet.php
 * Date Created: Dec 04, 2007
 * Date Modified: Dec 28, 2007
 * Requires: prototype.js 1.6.0
 * Requires: prototype_ss.js for 1.6.0
 * Requires: effects_ss.js for 1.6.0
 * Requires: EventSelectors.js
 * Author: Grady Kuhnline
 */

var Applet = Class.create({
	//constructor
	initialize: function(s) {
		// initialize settings
		this.s = {
			moduleName: 'Applet',
			url: 'lmi://www.oneilind.com:10000/',
			ver: '1.0.3',
			json: {

			meta: { // general info about the page
				"memberName": "name",
				"newp": "pwd",
				url: 'lmi://www.oneilind.com:10000/',
				ver: '1.0.3'
				},
				data: {}
			},
			guest : '',
			guestField : ($('guestName') ? $('guestName') : null)
			/* put extensions to settings here */
		};
		for(var key in s) this.s[key] = s[key];

		// initialize nodes
		this.n = {
			applet: null
			/* put extensions to nodes here */
		};

		// initialize collections
		this.c = {
			timeouts: [],
			throbbers: []
		};
	},
	/* Public Methods */
	addLink:  function(el) {
		Event.observe(el, 'click', this.call.bindAsEventListener(this, el));
	},
	addTest:  function(el) {
		Event.observe(el, 'click', this.test.bindAsEventListener(this, el));
	},
	addForm:  function(el) {
		Event.observe(el, 'submit', this.signIn.bindAsEventListener(this, el));
	},
	addMyAccountForm:  function(el) {
		Event.observe(el, 'submit', this.reSignIn.bindAsEventListener(this, el));
	},
	setCookie: function(name, value, daysToExpire) {
	    var expire = '';
	    var path = '/';
	    var domain = '';
		domain = '; domain=.www.oneilind.com';
		if (daysToExpire != undefined) {
				var d = new Date();
				d.setTime(d.getTime() + (60*60*24*30));
				expire = '; expires=' + d.toGMTString();
				path = '; path=/';
		}
		return (document.cookie = escape(name) + '=' + escape(value || '') + expire + path + domain);
	},
  	getCookie: function(name) {
		var cookie = document.cookie.match(new RegExp('(^|;)\\s*' + escape(name) + '=([^;\\s]*)'));
		return (cookie ? unescape(cookie[2]) : null);
	},

	/* Event Methods */
	/**
	 * @param string roomName
	 * @return void
	 */
	call: function(e, href) {
		this.el = href;
		var owner = (this.el.hasClassName('owner') ? true : false);
		var pattern = /#(call|conf)\?roomName=(.*)&?/;
		var matches = href.href.match(pattern);
		var callType = matches[1];
		var roomName = matches[2].toLowerCase();

		var label = roomName+',foobar,';

		if(callType == 'conf')
		{
			if(this.getCookie('vidyohistory') == null)
			{

				this.setCookie('vidyohistory', label, 1);
				this.setCookie('history_update', '1', 1);
			}
			else
			{
				var history = this.getCookie('vidyohistory');
				if(history.match(roomName) == null)
				{
					label = history+label;
					this.setCookie('vidyohistory', label, 1);
					this.setCookie('history_update', '1', 1);
				}
			}
		}

		if(e) Event.stop(e);
		var msg = this.s.url + callType + '=' + roomName;
		if(this.s.guest != "") msg += '&guest=' + encodeURIComponent(this.s.guest);
		if(owner) msg += '&owner=1';
		this.sendMsg(msg, href );
	},

	/**
	 * @param string memberName
	 * @return void
	 */
	signIn: function(e, form) {

		var data = Form.serialize(form, true);

		if(!this.s.guestField || this.s.guestField.value == "")
			this.sendMsg( this.s.url + 'signin=&userID=' + data.username + '&password=' + data.userpassword + '&ver=' + this.s.ver, form);
	},

	reSignIn: function(e, form) {
		var data = Form.serialize(form, true);

		if(data.newp==data.verifyp) {
			var updateurl="ajax/index.php";
			this.s.json.meta.memberName=data.memberName;
			this.s.json.meta.newp=data.newp;
			var param ="action=myaccount&data="+Object.toJSON(this.s.json);
			this.addRequest(updateurl, param, form, this);
		}
	},

	addRequest: function(url, params, form, applet) {
		var myAjaxRequest =new Ajax.Request(url, {
			method: 'post',
			parameters: params,
			asynchronous: false,
			onSuccess: function(t) {
				var results=t.responseText.evalJSON();
				//alert("Success="+results.data.success);
				if(results.data.success=='1') {
					//alert("Hello");
					//alert( results.meta.url+'signin=&userID='+results.data.memberName+'&password='+results.data.newp + '&ver=' + results.meta.ver+ form);
					//this.sendMsg( results.meta.url+'signin=&userID='+results.data.memberName+'&password='+results.data.newp + '&ver=' + results.meta.ver, form);
					//alert( results.meta.url + 'signin=&userID=' + results.meta.memberName + '&password=' + results.meta.newp + '&ver=' + results.meta.ver);
					applet.sendMsg( results.meta.url + 'signin=&userID=' + results.meta.memberName + '&password=' + results.meta.newp + '&ver=' + results.meta.ver, form);
				}
			}
		});
	},

	/**
	 * @param string url
	 * @return string
	 */
	sendMsg: function(url, el) {
		if (!this.n.applet) {
			// All other browsers
			if (navigator.plugins && navigator.mimeTypes && navigator.mimeTypes.length) {
				this.n.applet = document.getElementById('vidyoAppletEmbed');
			}
			// IE
			else {
				this.n.applet = document.getElementById('vidyoAppletObject');
			}
		}
		if (!this.n.applet) {
			if (this.c.timeouts[el]) {
				window.clearTimeout(this.c.timeouts[el]);
				this.c.timeouts[el] = null;
			}
			if (!this.c.throbbers[el])
				this.c.throbbers[el] = new Effect.Throb(el, '<div>Please Wait...</div>');
			this.c.timeouts[el] = window.setTimeout(this.sendMsg.bind(this, url, el), 100);
			return;
		}
		if (Element.isThrobbed(el)) {
			this.c.throbbers[el].cancel();
			this.c.throbbers[el] = null;
		}
		var result = this.n.applet.sendMsg(url);

		if (result === 1)
		{
			if (el.tagName.toLowerCase() != 'form') {
				//alert('VidyoDesktop is not running. \n\nPress ok to refresh and try again');
				window.location.reload();
			}
			return;
		}
		else if (result === 2)
		{
			if (el.tagName.toLowerCase() != 'form') {
				//alert('VidyoDesktop is not running. \n\nPress ok to refresh and try again');
				window.location.reload();
			}
			return;
		}
		else if (result === 0 && typeof(el.fire) == 'function')
		{
//			alert('Test Message. Applet returned success!\n\nComment this out on line 120 of applet.php');
			el.fire('ss:callsuccess');
		}
		return result;
	}

	/* Private Methods */
});

var AppletObject;
EventSelectors.register({
	'a.applet': function(el, index) {
		// initialize the applet once, AFTER the page has loaded
		if (typeof(AppletObject) !== 'object')
		{
			AppletObject = new Applet();
		}

		// give all of the links to the applet.
		AppletObject.addLink(el);
	},
	'div.loginContent form.loginForm': function(el, index) {
		// initialize the applet once, AFTER the page has loaded
		if (typeof(AppletObject) !== 'object')
		{
			AppletObject = new Applet();
		}

		// give all of the links to the applet.
		AppletObject.addForm(el);
	},
	'form.myAccountForm': function(el, index) {
		// initialize the applet once, AFTER the page has loaded
		if (typeof(AppletObject) !== 'object')
		{
			AppletObject = new Applet();
		}

		// give all of the links to the applet.
		AppletObject.addMyAccountForm(el);

		}

});
EventSelectors.register({
	'a.roomLaunch': function(el) {
		// initialize the applet once, AFTER the page has loaded
		if (typeof(AppletObject) !== 'object')
		{
			AppletObject = new Applet();
		}
		// launch room
		AppletObject.call(false, el);
	},
	'a.action-btn:click' : function(el) {
		window.setTimeout(function(){window.location.reload()}, 2000);
	}
}, true);

/**
 * @param JSONString status
 * @return true
 */
function setStatus(status) {
	if (typeof(AppletObject) !== 'object')
	{
		AppletObject = new Applet();
	}

	status = status + ''; // force it to be a string

	status = status.evalJSON();
	if (!status.type)
		return false;

	$('overlay').style.display = "none";
    $('lightbox').style.display = "none";

	switch (status.type) {
		case 'installed':
			if(true) {
				logout();
			}
		break;
		case 're-installed':
			$('overlay').style.display = "none";
			$('lightbox').style.display = "none";
			if ($('lbContent')) Element.remove($('lbContent'));
		break;
		case 'not-installed':
			showLightboxNotification("Installation did not complete", "<div class='clearfix aligncenter'><a class='lbAction button' rel='deactivate' style='float: none'>OK</a></div>");
			$$('.lbAction').each(function(el) {
				if(el.rel == "deactivate")
					el.observe('click', function() { logout();});
			});
			// should take them to the login page again.
		break;
		case 'installFailed':
			showLightboxNotification("Installation failed", "<div class='clearfix aligncenter'><a class='lbAction button' rel='deactivate' style='float: none'>OK</a></div>");
			$$('.lbAction').each(function(el) {
				if(el.rel == "deactivate")
					el.observe('click', function() { logout();});
			});
			// should take them to the login page again.
		break;
        case 'installDownload':
        	showLightboxNotification("Please wait&hellip;", "Downloading Vidyo Conferencing&trade; software&hellip;");
        	break;
        case 'installDownloaded':
        	showLightboxNotification("Download completed.", "Please proceed to Vidyo Conferencing&trade; installation wizard.<br/><div class='clearfix aligncenter'><a class='lbAction button' onclick='setCloseWindow(true);' rel='deactivate' style='float: none'>OK</a></div>");
        	break;
		case 'status':
			switch (status.value) {
				case 'busy':
						showLightboxNotification("Please wait&hellip;", "Searching for Vidyo Conferencing&trade; software.");
//					AppletObject.onClientBusy();
					break;
				case 'failed':
						showLightboxNotification("Please try again later", "The requested operation could not be performed.");
//					AppletObject.onSendMessageFailed();
					break;
			}
		break;
	}
	return true;
}

function showLightboxNotification(header, message) {
	if ($('lbContent')) Element.remove($('lbContent'));
    else addLightboxMarkup();

	$('overlay').style.display = "block";
    $('lightbox').style.display = "block";

    var info = "<div id='lbContent'><div class='popupHeader'><a title='Close' class='lbAction closeIcon' onclick='setCloseWindow(true);' rel='deactivate'>Close</a></div><div class='popupContent'><h3>" + header + "</h3><br/><p>" + message + "</p></div><div class='popupFooter'></div></div>";

	new Insertion.Before($('lbLoadMessage'), info);

	$('lightbox').className = "done";

	lightbox.prototype.actions();
}

var closeWindow = false;

function setCloseWindow(value) {
	closeWindow = value;
}

function displayLoop() {
	if (!closeWindow)
    	setTimeout(displayLoop);
}

function setLoginFocus() {
	if ($('username') && !$('username').disabled) $('username').focus();

}

function logout() {
	window.location = "http://www.oneilind.com/portal/index.php?action=logout";
}

var applet_code = '';
if ($('roomLocked')) {
} else {
if (navigator.plugins && navigator.mimeTypes && navigator.mimeTypes.length) {
	applet_code += '<embed id="vidyoAppletEmbed" width="0" height="0"';
	applet_code += '	type="application/x-java-applet;version=1.4"';
	applet_code += '	code="ClientLauncherApplet.class"';
	applet_code += '    server="www.oneilind.com:10000"';
	applet_code += '	archive="/portal/tools/SignedClientLauncherApplet.jar"';
	applet_code += '	pluginspage="http://www.java.com/en/download/manual.jsp"';
	applet_code += '	scriptable="false"';
	applet_code += '	download="false"';	applet_code += '	mayscript="false"';
	applet_code += ' />';
}
// IE
else {
	applet_code += '<object id="vidyoAppletObject" classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93" width="0" height="0" type="application/x-java-applet;version=1.4">';
	applet_code += '	<param name="type" value="application/x-java-applet;version=1.4">';
	applet_code += '	<param name="code" value="ClientLauncherApplet.class">';
	applet_code += '        <param name="server" value="www.oneilind.com:10000">';
	applet_code += '	<param name="archive" value="/portal/tools/SignedClientLauncherApplet.jar">';
	applet_code += '	<param name="scriptable" value="false">';
	applet_code += '	<param name="download" value="false">';	applet_code += '	<param name="mayscript" value="false"></object>';
}
document.write(applet_code);
}

//For help links to open in a new window
$$('.pdfHelp a').each(function(el) {
		el.observe('click', function(e) {
				window.open(this.href);
				e.stop();
			}.bindAsEventListener(el))
	});
