function Weblink_UserInterface(elm){
	var that = this;
	var current = {};
	this.WU;
	var Search;
	var BugReport;
	var Images = {
			getLoading : function(){
				if(/flashlogic|omegalink/.test(location.href)) return '/weblink/images/status/device-detect-start-unbranded.jpg';
				return '/weblink/images/status/device-detect-start.gif';	
			},
			getNoCable : function(){
				if(/flashlogic|omegalink/.test(location.href)) return '/weblink/images/status/device-detect-error-cable-unbranded.jpg';
				return '/weblink/images/status/device-detect-error-cable.gif';
			},
			getNoModule : function(){
				if(/flashlogic|omegalink/.test(location.href)) return '/weblink/images/status/device-detect-error-module-unbranded.jpg';
				return '/weblink/images/status/device-detect-error-module.jpg';
			},
			getNoBlade : function(){
				return '/weblink/images/status/device-detected-remote-no-blade-dse.gif';
			}
	}
	if(elm && $(elm).size()!=0){
		var container = elm;
	} else {
		throw 'Not a valid container';
	}
	
	this.setWU = function(wu){
		that.WU = wu;
	};
	
	function pluginBusy(){
		ErrorMessage('The plugin is currently busy, please wait for the current task to complete.');
	}
	
	this.init = function(){
			
			function whenDetected(){
				//$('.status').html('whenDetected');
				
				//$('.status').html('whenDetected2');
				var dev = that.WU.getDevice(1);
				//$('.status').html('whenDetected3');
				if(dev){
					var SI = new Weblink_ServerInterface();
					SI.$.one('dataLoaded',
							function(evt,data){
								current['device'] = dev;
								dev.setInfos(data);
								//$('.status').html('whenDetected3.5');
								current.firmware = dev.firmware;
								var SI = new Weblink_ServerInterface();
								SI.$.one('dataLoaded',that.displayModuleInfo);
								//$('.status').html('whenDetected4');
								if (typeof(data['Error']) != 'undefined')
								{
									$('#weblink_updater>div.header').html('<h1>Serial number is not found</h1>');
									$('#weblink_updater>div.header').after('<div class="module-info" align="center">There is no device associated to this serial number [ '+dev.get('Serial')+' ]. Please, contact technical support to resolve this issue.</div>');
									$('#weblink_updater>div.module-info').after('<div class="buttons" align="center"><img class="buttons retry" src="/weblink/images/buttons/retry.en.gif" complete="complete"/></div>');									
									$('#weblink_updater div.buttons img.retry').one('click',function(){WU = "undefined"; location.reload();});									
								}
								else
									SI.getModuleInfo(dev,false);
								//$('.status').html('whenDetected5');
							});
					
					SI.getModuleInfo(dev,true);
				}
				
				var starter = that.WU.getDevice(Weblink_Types.REMOTE_STARTER);
				
				if(starter){
					current['starter']=starter;
				}
				
				if(starter && !dev){
					if(starter.get('BootLoader')==23) that.initStarterOnly();
					else whenDetectError(null,new BladeNotDetectedException());
				}
			}
			this.callTechSupport = function(step){
				/*if(step==1){
					$('.image-status').after("<div class='image-callSupport'><img src='/weblink/images/buttons/chatsupport.gif' complete='complete'/>");
				}
				if(step==3){
					$('div.right-column > div.text-status').after("<div class='image-callSupport' style='margin-top: 30px;'><img src='/weblink/images/buttons/chatsupport.gif' complete='complete'/>");
				}
				$('.image-callSupport > img').bind('click',function(){
					tracking.storeInfo();
				});	*/
			};
			function whenDetectError(evt,exception){

				if(exception instanceof CableNotDetectedException){
					$('.text-status').text('No cable detected, please verify the connection and retry.');
					$('.image-status img').attr('src',Images.getNoCable());
				}
				else if(exception instanceof BladeNotDetectedException){
					$('.text-status').text('No Blade has been detected, please verify the connection and retry.');
					$('.image-status img').attr('src',Images.getNoBlade());
				}
				else if(exception instanceof DeviceNotDetectedException){
					$('.text-status').text('No device detected, please verify the connection and retry.');
					$('.image-status img').attr('src',Images.getNoModule());
				} else {
					$('.text-status').text('No device/cable detected, please verify the connection and retry.');
					$('.image-status img').attr('src',Images.getNoModule());
				}
				tracking.getMonitor().addProcessAction(exception.message,Weblink_Monitor_Priorities.HIGH|Weblink_Monitor_Priorities.ERROR)
			}
			
			function whenDetectStart(){
					
			}

			function whenDetectNew(){
				var jq = $('#weblink_updater div.footer-version');
				var content = '<div class="new-version">A new version of the Weblink Plugin is available. <span>It is highly recommended that you update to the latest version of the plugin. <a href="#" onclick="return false;">Click here to download it.</a></span><br><span>Please <font color="#FF0000">RESTART</font> your browser after installation</span></div>';
				if(jq.length!=0)jq.after(content);
				else $('#weblink_updater div.header').before(content);
				$('#weblink_updater div.new-version a').click(getLatestVersion);
			}
			function whenReady(){
				var version = that.WU.getPluginInterfaceVersion(true);
				$('#weblink_updater div.header').before('<div class="footer-version">You are using Weblink Updater version '+version['version']+' r'+version['revision']+'</div>');
				
				if(typeof(tracking) != "undefined"){
					try{
						BugReport = new Weblink_UserInterface_BugReport();
					} catch(e){
						alert(e);
					}
				}
				
				if(in_array(version,[3,4,4.1])){
					$('div.version-switch img.wu4').remove();
				}
				
				
				//Initialize Busy Check
				that.WU.$.one('pluginBusy',pluginBusy);
				
				that.WU.$.one('deviceDetectError',whenDetectError);
				that.WU.$.one('deviceDetectStart',whenDetectStart);
				that.WU.$.one('deviceDetectComplete',
						whenDetected
						);
				try{
					that.WU.callDetectDevice();
				} catch(e){
					//alertX(e);
				}
			}
			
			function pluginDetectError(){
				
				//Only propose weblink 5 if vendor is idatalink else propose version 4
				if(in_array(5,Weblink_Versions) && Weblink_Vendor == "idatalink"){
					$('.text-status').text('Weblink Plugin Required. Click the link below to download the latest plugin.');
					$('.image-status img').attr('src','/weblink/images/status/plugin-detect-error5.gif');
					$('.image-status img').css('cursor','pointer');
					$('.text-status,.image-status img').click(
							function(){
								location.href="/downloads/weblink-drivers-latest/";
								}
							);
				} else if(Weblink_Vendor == "idatalink"){
					$('.text-status').text('Weblink Plugin Required. Click the link below to download the latest plugin.');
					$('.image-status img').attr('src','/weblink/images/status/plugin-detect-error.gif');
					$('.image-status img').css('cursor','pointer');
					$('.text-status,.image-status img').click(
							function(){
								location.href="/downloads/weblink-drivers/";
								}
							);
				} else {
					/*
					 * For other vendors, use ajax to grab weblink page
					 * REFACTOR ASAP...
					 */
					
					$('.text-status').text('Weblink Plugin Required. Click the link below to download the latest plugin.');
					$('.image-status img').attr('src','/weblink/images/status/plugin-detect-error.gif');
					$('.image-status img').css('cursor','pointer');
					$('.text-status,.image-status img').click(
							function(){
						        var actionID = 'weblink';
						        $.ajax({
						            url:'/common/index/'+actionID,
						            type:'GET',
						            dataType:'html',
						            success : function(data) {
						        		if (!$("#results_box").length)
						        		{
						        			$("#update_box").attr('id', 'results_box');
						        		};
						                $("#results_box").html(data);
						            },
						            error : function(xhr) {
						            	ErrorMessage(xhr);
						            }
						        }
							);
							});
				}
			}
			function getLatestVersion(){
				if(in_array(5,Weblink_Versions) && Weblink_Vendor == "idatalink"){
						location.href="/downloads/weblink-drivers-latest/";
					} else if(Weblink_Vendor == "idatalink"){
						location.href="/downloads/weblink-drivers/";
					} else {
						var actionID = 'weblink';
				        $.ajax({
				            url:'/common/index/'+actionID,
				            type:'GET',
				            dataType:'html',
				            success : function(data) {
				        		if (!$("#results_box").length)
				        		{
				        			$("#update_box").attr('id', 'results_box');
				        		};
				                $("#results_box").html(data);
				            },
				            error : function(xhr) {
				            	ErrorMessage(xhr);
				            }
					        }
						);
					}
			}
			function pluginRequirementsMissing(){
				$('.text-status').text('Browser/OS is not compatible with the Weblink Plugin');
				$('.image-status').load('/weblink/index/missing-requirements/');
				$('.text-status,.image-status img').click(
						getLatestVersion
						);
			}
			
			function pluginDetectStart(){
				$('#weblink_updater div.header').html('<div class="text-status"></div><div class="image-status"><img src="'+Images.getLoading()+'"/></div>');
			}
			
			that.WU.$.one('pluginDetectStart',pluginDetectStart);
			that.WU.$.one('pluginRequirementsMissing',pluginRequirementsMissing);
			that.WU.$.one('pluginDetectError',pluginDetectError);
			that.WU.$.one(
					'pluginNew',
					whenDetectNew);
			that.WU.$.one(
					'pluginReady',
					whenReady);
			var wujq = $('#weblink_updater > div.tabs');
			wujq.append('<img class="step1" src="/weblink/images/tabs/step1.on.en.gif"');
			wujq.append('<img class="step2" src="/weblink/images/tabs/step2.off.en.gif"/>');
			wujq.append('<img class="step3" src="/weblink/images/tabs/step3.off.en.gif"/>');
			wujq.append('<div class="version-switch"></div>');
			wujq.append('<div class="clear-fix"></div>');
			if(Weblink_Vendor == 'idatalink'){
				if(in_array(5,Weblink_Versions)){
					wujq.children('div.version-switch').append('<img class="wu4" src="/weblink/images/buttons/flashwithupdater4.jpg"/>');
					wujq.find('div.version-switch > img').click(function(){location.href = '/update/index/chosen-updater/4'});
				} else {
					wujq.children('div.version-switch').append('<img class="wu5" src="/weblink/images/buttons/flashwithupdater5.jpg"/>');
					wujq.find('div.version-switch > img').click(function(){location.href = '/update/index/chosen-updater/5'});
				}
			
				
			}
	};
	
	this.displayModuleInfo = function (evt,infos){
		$('.image-status').slideUp(function(){$(this).remove();});
		switch(current.device.getType()){
		case Weblink_Types.MODULE : $('.text-status').text('Module detected, click next to flash your module'); break;
		case Weblink_Types.BLADE_MODULE : $('.text-status').text('Blade Module detected, click next to flash your module'); break;
		}
		//$('.status').html('displayModuleInfo');
		if($('#weblink_updater div.header div.module-info').size()==0) $('#weblink_updater div.header').append('<div class="module-info"></div>');
		$('#weblink_updater div.header div.module-info').html(infos);
		$('#weblink_updater div.header img.retry').one('click',function(){WU = undefined; location.reload();});		
		$('#weblink_updater div.header img.next').one('click',
				function(){
					$('div.text-status').slideUp(
							function(){
								$(this).remove();
								});
					that.initSearch();
					$(this).parent().eq(0).remove();
					if(typeof(tracking) != "undefined"){
						tracking.addInfo("Click next button on Step 1");
					}
				});
		//add firmware tracking info into db
		if(typeof(tracking) != 'undefined'){
			tracking.addDeviceInfo(current.device.get('Serial'));
		}
	};
	this.initSearch = function(){
		
		Search = new Weblink_UserInterface_Search(current);
		Search.init();
		Search.$.bind('firmwareSelected',that.initFlash);
		that.setCurrentStep(2);
	};
	this.initStarterConf = function(){
		if(that.WU.isBusy()) return;
		StarterEdit = new Weblink_UserInterface_StarterConfEdit(current,WU.isAllowed);
		StarterEdit.init();
		WU.$.one('starterEepromUpdated',StarterEdit.getOptions);
		WU.$.one('updateConfigurationError',StarterEdit.kill);
		WU.updateDeviceConfiguration(current.starter);
		StarterEdit.$.bind('starterFeaturesEdited',function(){WU.updateDeviceConfiguration(current.starter);})
	};
	this.initStarterOnly = function(){
		$('.text-status').text('Blade compatible remote starter detected. Press unlock to unlock your starter\'s RS232 port.')
		$('.image-status').slideUp(function(){$(this).remove();});
		function Unlock(){
			StarterOnly.setUpUnlock();
			that.WU.$.unbind('unlockProgress');
			that.WU.$.one('unlockStarts',StarterOnly.progressStarts);
			that.WU.$.bind('unlockProgress',function(evt,bytes,perc){StarterOnly.progress(perc);});
			that.WU.$.one('unlockError',function(evt,exception){
				that.WU.$.unbind('unlockProgress');
				that.WU.$.unbind('unlockComplete');
				that.WU.$.unbind('unlockStarts');
				StarterOnly.progressError(exception.message);
				if(typeof(tracking) != "undefined"){
					tracking.addInfo("Error: "+exception.message);
					that.callTechSupport(3);
				}
			});
			that.WU.$.one('unlockComplete',function(){
				StarterOnly.progressComplete();
				if(typeof(tracking) != "undefined"){
					var currentTime = new Date();
					var second = currentTime.getSeconds();
					var minute = currentTime.getMinutes();
					var hour = currentTime.getHours();
					that.process['FlashComplete']= hour+":"+minute+":"+second;
					tracking.addFirmwareTracking(current);
				}
			});
			WU.unlock(current.starter);
			
		}
		StarterOnly = new Weblink_UserInterface_StarterOnly(current,WU.isAllowed);
		StarterOnly.init();
		StarterOnly.$.one('unlockCalled',Unlock);
	};
	this.initFlash = function(){
		ModuleFlash = new Weblink_UserInterface_ModuleFlash(current,WU.isAllowed);
		ModuleFlash.$.unbind('flashCalled');
		ModuleFlash.$.unbind('starterFlashCalled');
		ModuleFlash.$.unbind('editFirmwareSelection');
		ModuleFlash.$.unbind('featuresEdited');
		ModuleFlash.$.unbind('editStarterConfiguration');
		ModuleFlash.$.bind('flashCalled',function(){
			if(WU.isBusy()) return;
			that.flashStart(current.device,current.firmware);
			});
		ModuleFlash.$.bind('editFirmwareSelection',function(){
			if(that.WU.isBusy()) return;
			Search.show();
			ModuleFlash.hide();
			});
		if(current.starter && WU.isAllowed('flash',{'device':current.starter}) && current.starter.get('Latest')){
			current.starter.setInfos('Latest', new Weblink_Firmware(current.starter.get('Latest')));
			ModuleFlash.$.bind('starterFlashCalled',function(){
				if(WU.isBusy()) return;
				that.flashStart(current.starter,current.starter.get('Latest'));
				});
		}
		
		ModuleFlash.$.bind('editStarterConfiguration',that.initStarterConf);
		if(WU.isAllowed('readConfiguration')){
			ModuleFlash.$.bind('featuresEdited',
					function(){
						if(WU.isBusy()) return;
						WU.updateDeviceConfiguration(current.device);
						});
			WU.$.one('deviceEepromUpdated',ModuleFlash.init);
			WU.$.one('deviceEepromUpdated',ModuleFlash.updateFeatures);
			WU.$.one('deviceEepromUpdateFailed',ModuleFlash.init);
			WU.updateDeviceConfiguration(current.device);
		} else {
			ModuleFlash.init();
			ModuleFlash.updateFeatures(false);
			
		}
		that.setCurrentStep(3);
	};
	this.flashStart = function(device,firmware){
		that.WU.$.unbind('flashProgress');
		that.WU.$.one('flashStarts',ModuleFlash.progressStarts);
		that.WU.$.bind('flashProgress',function(evt,bytes,perc){ModuleFlash.progress(perc)});
		that.WU.$.one('flashError',function(evt,exception){
			that.WU.$.unbind('flashProgress');
			that.WU.$.unbind('flashComplete');
			that.WU.$.unbind('flashStarts');
			that.WU.$.unbind('flashError');
			ModuleFlash.progressError(exception.message);
			
			//TODO REFACTOR THIS
			if(typeof(tracking) != "undefined"){
				var currentTime = new Date();
				var second = currentTime.getSeconds();
				var minute = currentTime.getMinutes();
				var hour = currentTime.getHours();
				if(typeof(exception)!="object"){
					tracking.addInfo("Error: "+exception+"(" + hour + ":" + minute + ":" + second+")");
				} else {
					tracking.addInfo("Error: "+exception.message+"(" + hour + ":" + minute + ":" + second+")");
				}
				that.callTechSupport(3);
			}
		});
		that.WU.$.one('flashComplete',function(){
			ModuleFlash.progressComplete();
			if(typeof(tracking) != "undefined"){
				tracking.addFirmwareTracking(current);
			}
		});
		that.WU.updateFirmware(device,firmware);
	};
	
	this.setCurrentStep = function(step){
		var steps = [1,2,3];
		var on = false;
		for(x in steps){
			var _step = steps[x];
			if(step == _step){
				$('#weblink_updater > div.tabs .step'+_step).attr('src',$('#weblink_updater div.tabs .step'+_step).attr('src').replace(/\.(on|off|done)\./,'.on.'));
				on = true;
			} else if(!on){
				$('#weblink_updater > div.tabs .step'+_step).attr('src',$('#weblink_updater div.tabs .step'+_step).attr('src').replace(/\.(on|off)\./,'.done.'));
			} else {
				$('#weblink_updater > div.tabs .step'+_step).attr('src',$('#weblink_updater div.tabs .step'+_step).attr('src').replace(/\.(on|off|done)\./,'.off.'));
			}
			//$('#weblink_updater > div.tabs .step2').attr('src',$('#weblink_updater div.tabs .step2').attr('src').replace('off','on'));
		}
		
	};
	
}