/**
* Vidyo JavaScript wrapper for XHR REST methods. Usage:
*
* Initialize with name of the flex callback function and the contents to
* be placed in the authorization header. 
*
* 	Vidyo.initialize({callback:'flexCallback', auth: 'Basic xFgSgvsa'});
*
* 	Vidyo.send({url:'http://server/path', method:'PUT', data:'param=value'});
*
* The Flex callback is invoked with any server responses and also with JavaScript
* debug traces. An object will be passed to the Flex callback with the following
* parameters:
*
*    action:       'trace' or 'responseComplete'
*    statusCode:   The HTTP status code
*    data:         The HTTP data from the server or null
*    msg:          The message to trace, for the 'trace' action.
*/
var Vidyo = (function() {

	var _callback = null;
	var _appId = null;
	var _auth = null;
	var _xhr = null;
	var _flex = null;
	var _isIE = true;
	var _lastResponse = null;
    var _imgError = false;
    var _baseUrl = '/portal2';
	var _responsePending = 0;
	var _responseDelivered = true;
	var vdSocketPort = 63457;

	return {
	//-------------------------------------------------------------------------
	//	Public methods
	//-------------------------------------------------------------------------
		initialize: function(params) {
			if (params.callback) _callback = params.callback;
			if (params.auth) _auth = params.auth;
			if (params.appId) {
				_appId = params.appId;
				_flex = document.getElementById(params.appId);
			}
			var browser=navigator.appName;
			if (browser == 'Netscape') {
				_isIE = false;
			}
			if (params.baseUrl) {
				_baseUrl = params.baseUrl;
			}
			
			//this.trace('initialization complete');
			initXhr();
			if (_xhr) this.trace('XHR object initialized');
			return true;
		},
		
		setFocusFlash: function() {
			if (_flex) {
				_flex.focus();
				return 'focus set';
			}
			else {
				_flex = document.getElementById(_appId);
				if (_flex) {
					_flex.focus();
					return 'focus set';
				}
				else {
					return 'focus NOT set';
				}
			}
		},
		
		setAuth: function(auth) {
			_auth = auth;
			//this.trace('setAuth: ' + _auth);
			return true;
		},
		
		send: function(params) {
			var url = params.url;
			var method = params.method;
			var data = params.data;
			
			//this.trace('initXhdr');
			if (this._responsePending != 0)
				_xhr.abort();

			initXhr();
			
			//this will get executed only when we have focus on the portal 
			
			
			
			if (!_xhr) {
				//this.trace('failed to initXhdr');
				return false;
			}
			
			this._lastResponse = null;

			if ((method == 'GET' || method == 'get') && data) {
				url = url + '?' + data;
			}
			//this.trace('send: url=' + url + ' method=' + method);

			try {
				_xhr.open(method, url, true);
				//this.trace('request opened');
	
				if (_auth) {
					var authHeader = 'Basic ' + _auth;
					//this.trace('Authorization: ' + authHeader);
					_xhr.setRequestHeader('Authorization', authHeader);
				}
				else {
					//this.trace('no auth header');
				}
				if (data && method != 'GET') {
					//this.trace('set content-type header');
					_xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
				}
				else {
					//this.trace('no post data');
				}
				
				// Variable "this" is not in scope inside the readstate handler function. Capture
				// it in the that variable to capture it in the function closure.
				var that = this;
				this._responsePending = 1;
				this._responseDelivered = true;
				
				_xhr.onreadystatechange = function () {
					if (_xhr.readyState != 4) {
						// no data yet
						//that.trace('readyState = ' + _xhr.readyState);
						return;
					}
					//that.trace('result complete');
					that._lastResponse = new Object();
					that._lastResponse.statusCode = _xhr.status;
					that._lastResponse.data = _xhr.responseText;
					that._lastResponse.action = 'responseComplete';
					that._responsePending = 0;
					
					if (_callback && _flex) {
						try {
							_flex[_callback](that._lastResponse);
						}
						catch(flexErr) {that._responseDelivered = false;} // can't call flex, just hold onto response
					}
				}
				
				//that.trace('calling send');
				_xhr.send(data);
				
				//that.trace('data sent');
				return true;
			}
			catch(err) {
				//this.trace('JavaScript exception ' + err.name + ': ' + err.message);
				if (_callback && _flex) {
					this._lastResponse = new Object();
					this._lastResponse.statusCode = 500;
					this._lastResponse.data = null;
					this._lastResponse.action = 'responseComplete';
					try {
						_flex[_callback](this._lastResponse);
					}
					catch (flexErr) {;} // can't call flex, just hold the response
				}
				return false;
			}
		},
		
		getOS: function() {
			var OSName="Unknown OS";
			if (navigator.appVersion.indexOf("Win")!=-1) OSName="Windows";
			if (navigator.appVersion.indexOf("Mac")!=-1) OSName="MacOS";
			if (navigator.appVersion.indexOf("X11")!=-1) OSName="UNIX";
			if (navigator.appVersion.indexOf("Linux")!=-1) OSName="Linux";	
			return OSName;	
		},
		
		isChromeBrowser: function() {
			if (navigator && navigator.userAgent && navigator.userAgent.indexOf('Chrome') != -1) {
				return true;
			}
			else {
				return false;
			}	
		},
		
		linkVidyoDesktop: function(srcLink) {
			//this.trace('linkVidyoDesktop invoked');
			this._imgError = false;
			var elem = document.getElementById('vdLink');
			if (elem) {
				elem.src = srcLink;
				//this.trace('img src link set to ' + srcLink);
				return srcLink;
			}
			else {
				//this.trace('failed to get image element');
				return 'ERROR: failed to get source link element';
			}
		},

		getImageError: function() {
			return this._imgError;
		},
		
		getLastResponse: function() {
			if(this._responseDelivered){
				return null;
			}
			else
			{
			   return this._lastResponse;
			}
			
		},
		
		getTheme: function() {
			try {
				var value = this.readCookie('VidyoPortal2Theme');
				if (value == null) return '';
				return value;
			}
			catch(err) {
				return 'exception';
			}	
		},
		
		readCookie: function(name) {
			var nameEQ = name + "=";
			var ca = document.cookie.split(';');
			for(var i=0;i < ca.length;i++) {
				var c = ca[i];
				while (c.charAt(0)==' ') c = c.substring(1,c.length);
				if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
			}
			return null;
		},
		
		hideVidyoDesktopImage: function() {
			var elem = document.getElementById('vdLink');
			if (elem) {
				elem.style.visibility = 'hidden';
			}
		},

		getVidyoDesktopLink: function() {
			//this.trace('getVidyoDesktopLink invoked');
			var url = '';
			var elem = document.getElementById('vdLink');
			if (elem) {
				//this.trace('getVidyoDesktopLink located image element');
				url = elem.src; 
			}
			//this.trace('getVidyoDesktopLink returning url ' + url);
			return url;
		},
		
		reloadPage: function() {
			//window.location.href = window.location.href;
			window.location.reload(true);
		},
		
		gotoInstallPage: function() {
			window.location.href = _baseUrl + '/download.html';
		},
		
		gotoPage: function(srcLink) {
			try {
				window.location.href = srcLink;
				return true;
			}
			catch(err) {
				return false;
			}
		},
		
		getPortalAddress: function() {
			//return '172.16.2.71';
			return window.location.host;
		},
		
		getPageLocation: function() {
			return window.location;
		},
		
		doInvite: function(params) {
			// alert(url);
			if (!(params && params.message)) {
				return 'missing url';
			}
			var link = document.getElementById('inviteLink');
			if (link) {
				link.href = params.message;
				if (_isIE) {
					link.click();
				}
				else {
					//link.onclick();
					window.location.href = params.message; 
				}
				return params.message;
			}
			else {
				return 'no link';
			}
		},
		
		encodeUri: function(uri) {
			return encodeURIComponent(uri);
		},
		
		vidyoNotRunning: function() {
			//this.trace('VidyoDesktop NOT running');
			this._imgError = true;
			/*
			if (_callback && _flex) {
				var params = new Object();
				params.action = 'vidyoDesktopNotRunning';
				try { _flex[_callback](params); }
				catch(err) {;} // nothing to do, imgError flag is set
			}
			*/
		},

		trace: function(msg) {
			if (_callback && _flex) {
				var params = new Object();
				params.message = msg;
				params.action = 'trace';
				_flex[_callback](params);
			}
		},
		
		//------------------------------------------------------------------------------------
		// Needed for VidyoRoom only.
		//------------------------------------------------------------------------------------
		setMicVolume: function(value) {
			try {
				var cmdLine = 'setmic ' + value;
				var app = 'C:\\Program Files\\Vidyo\\Vidyo Desktop\\audio.exe';
				//alert(app + ' ' + cmdLine);
				window.external.SWBBrowserExecute(app, cmdLine);
				return true;
			}
			catch(err) {
				return false;
			}
		},

		shutdownIp: function() {
			try {
				var cmdLine = '-ip';
				var app = 'C:\\Program Files\\Vidyo\\Vidyo Desktop\\shutdown.exe';
				//alert(app + ' ' + cmdLine);
				window.external.SWBBrowserExecute(app, cmdLine);
				return true;
			}
			catch(err) {
				return false;
			}
		},

		setSpeakerVolume: function(value) {
			try {
				var cmdLine = 'setvol ' + value;
				var app = 'C:\\Program Files\\Vidyo\\Vidyo Desktop\\audio.exe';
				//alert(app + ' ' + cmdLine);
				window.external.SWBBrowserExecute(app, cmdLine);
				return true;
			}
			catch(err) {
				return false;
			}
		},
		
		resetCamera: function() {
			try {
				var cmdLine = '--interface 127.0.0.1 http://127.0.0.1:'+vdSocketPort+'/dummy?camera=Reset';
				var app = 'C:\\Program Files\\Vidyo\\Vidyo Desktop\\curl.exe';
				//alert(app + ' ' + cmdLine);
				window.external.SWBBrowserExecute(app, cmdLine);
				return true;
			}
			catch(err) {
				return false;
			}
		},

		backlightOn: function() {
			try {
				var cmdLine = '--interface 127.0.0.1 http://127.0.0.1:'+vdSocketPort+'/dummy?camera=BlOn';
				var app = 'C:\\Program Files\\Vidyo\\Vidyo Desktop\\curl.exe';
				//alert(app + ' ' + cmdLine);
				window.external.SWBBrowserExecute(app, cmdLine);
				return true;
			}
			catch(err) {
				return false;
			}
		},

		backlightOff: function() {
			try {
				var cmdLine = '--interface 127.0.0.1 http://127.0.0.1:'+vdSocketPort+'/dummy?camera=BlOff';
				var app = 'C:\\Program Files\\Vidyo\\Vidyo Desktop\\curl.exe';
				//alert(app + ' ' + cmdLine);
				window.external.SWBBrowserExecute(app, cmdLine);
				return true;
			}
			catch(err) {
				return false;
			}
		}
		
	};

	//-------------------------------------------------------------------------
	//	Private methods
	//-------------------------------------------------------------------------
	function initXhr() {
		var XMLHttpFactories = [
			function () {return new XMLHttpRequest()},
			function () {return new ActiveXObject("Msxml2.XMLHTTP")},
			function () {return new ActiveXObject("Msxml3.XMLHTTP")},
			function () {return new ActiveXObject("Microsoft.XMLHTTP")}
		];
		for (var i=0;i<XMLHttpFactories.length;i++) {
			try {_xhr = XMLHttpFactories[i](); }
			catch (e) {	continue; }
			break;
		}
	}
	
}());

