    var wsUri = "ws://"+ location.host;
    var socket;  
    var imagesContainer;
	var videoWidth = 720;
	var videoHeight = 576;
      
    var cropLeft = 0;
    var cropRight = 0;
    var cropTop = 0;
    var cropBottom = 0;  
	var allPages ;
	var pagesLoaded = false;
	var settingsLoaded = false;
	var lastStateConnected = true;
	var customerVideSource;
	
	$( document ).ready(function() {
		reloadPages();
		InitAllSettings();
		setInterval(function(){
			if(socket.readyState != 1){
				$("#disconnected").show();
				lastStateConnected = false;
				socket.close();
				CreateSocket();
			} else {
				$("#disconnected").hide();
				if(! lastStateConnected){
					location.reload();
				}
				lastStateConnected = true;
			}},5000);

		setInterval(function(){
			var nowX = new Date();
			//$("#DateTime").text(now.toLocaleDateString() + " " + now.toLocaleTimeString());
			var toDisplay = 
				nowX.getFullYear() + '-' + 
				pad((nowX.getMonth()+1),2) + '-' + 
				pad(nowX.getDate(),2) + ' ' + 
				nowX.getHours() + ':' + 
				pad(nowX.getMinutes(),2) + ':' + 
				pad(nowX.getSeconds(),2); 
			$("#DateTime").text(toDisplay);
			},1000);
		if(window["JavaScriptSdkHandlerAsync"]){
			MBirdSdk.UserInterface.CloseButton(MBirdSdk.UIAlignment.Hide, "base64image", 10, 10)
				.then(function(result) {
					// do something with the result
				}).catch(function(error) {
					// handle error
				});	
		}
	});

	// Checkbox TOGGLE
	$(function() {
		//because the parent container is hidden on start we must activate toggle only on show
		$('#CUSTOMERCONTROLS').show(function(){
			$('#ClientCameraSwitch').bootstrapToggle({
				on: 'Started',
				off: 'Paused'
				});
		});
		
		$('#SINGLESIDEBARCONTROL').show(function(){
			$('#SidebarSwitch').bootstrapToggle({
				on: 'Enabled',
				off: 'Disabled'
				});
		});
	});

	function pad(n, width, z) {
		z = z || '0';
		n = n + '';
		return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
	}
	
	function CreateSocket(){
		socket = new WebSocket(wsUri);
		socket.onopen = function (evt) { onOpen(evt) };
		socket.onclose = function (evt) { onClose(evt) };
		socket.onmessage = function (evt) { onMessage(evt) };
		socket.onerror = function (evt) { onError(evt) };
	}

	function generateBarcode(){
        var value = $("#barcodeValue").val();
        var btype = 'code128';
        var renderer = 'canvas';
		var barH = $("#FIDELITY_CANVAS").height();
		var quietZone = false;
        var settings = {
          output:renderer,
          bgColor: '#FFFFFF',
          color: '#000000',
          barWidth: 1,
          barHeight: 130,
          moduleSize: 5,
          posX: 80,
          posY: 10,
          addQuietZone: 1,
		  fontSize: 1,
		  marginHRI: 0,
		  showHRI: false
        };
        if (renderer == 'canvas'){
          clearCanvas();
          $("#barcodeTarget").hide();
          $("#canvasTarget").show().barcode(value, btype, settings);
        } else {
          $("#canvasTarget").hide();
          $("#barcodeTarget").html("").show().barcode(value, btype, settings);
        }
      }

	 function clearCanvas(){
        //var canvas = $('#canvasTarget').get(0);
        //var ctx = canvas.getContext('2d');
        //ctx.lineWidth = 1;
        //ctx.lineCap = 'butt';
        //ctx.fillStyle = '#FFFFFF';
        //ctx.strokeStyle  = '#000000';
        //ctx.clearRect (0, 0, canvas.width, canvas.height);
        //ctx.strokeRect (0, 0, canvas.width, canvas.height);
      }
	  
  function scanFid(){
	$("#barcodeValue").val('');
	generateBarcode();
	$("#fidError").hide(); 	  
    $.ajax({
        type: "POST",
        url: '/scanFid',
        async: true,
        success: function(data) {
        },
    }); 
  }

	  function reloadPages(){
		  $.ajax({
			type: "GET",
			url: '/loadAllPages',
			async: true,
			success: function(data) {
			  console.log('Succes load pages');
			},
			error : function() {
			  console.log('Could not load pages');
			}
		  }); 
	  };

    function init() {
	  
      GetCrewVideoSourceStatus();
      GetVideoStatus();
   
      // Init Container
      imagesContainer = document.getElementById("promo-image");
      CreateSocket();
    };

    function onMessage(evt) {
      var ldata = JSON.parse(evt.data);
      if( ldata.type == "Image")
      {
        addImageToPage(ldata);
      }
      if( ldata.type == "VideoStatus")
      {
        UpdateVideoStatus(ldata.status);
      }
      if( ldata.type == "Pages")
      {
	    pagesLoaded = true;
	    allPages = ldata;
		if( ldata.version == '100'){
		  addPageButtons(ldata);
		} else { 
		  if( ldata.version == '101'){
		  populateCategories();
		  categorySelected();
		  } else {
			if(allPages.pages[0]){
		      loadPage();
			}
		  }
	    }
      }
	  
      if( ldata.type == "showFid")
	  {
	   $("#barcodeValue").val(ldata.fid);
	   generateBarcode();
	  /* if(ldata.error){
		 $("#fidError").show();   
	   } else {
		 $("#fidError").hide();     
	   }  */
      }
      if( ldata.type == "hideFid")
	  {
		$("#barcodeValue").val('');
		generateBarcode();
	  }
	  if(ldata[0]){
		if(ldata[0].route == "/getAllSettings"){
		  LoadSettings( ldata[0].response ); 
		}
	  }
	  
	  // there are times when pages are not loaded so ....
      if ( ! pagesLoaded )  
	  {
	    reloadPages();
	  }
	  if ( ! settingsLoaded ) {
	    InitAllSettings();
	  }
    };
	
	function onClose(evt){
		console.log("Socket disconnected!");
		$("#disconnected").show();
	}
	function onOpen(evt){
		console.log("Socket connected!");
		$("#disconnected").hide();
	}

	function onError(evt){
		console.log("Socket error!");
	}
	
    
    function addImageToPage(imageData) {
	  /*imagesContainer.innerHTML = "";
	  for( aImg in imageData.images){
	    imagesContainer.innerHTML = imagesContainer.innerHTML + "<img id='promo-image' src='"+imageData.images[aImg].src+"'/>";
	  }*/
	  imagesContainer.src=imageData.images[0].src;
    }

// PAGES Section
	//for version 102
	function loadPage(aPage){
	  $("#list-pages-selector").hide();

	  var currentPage;
	  var lStr = "";
	  var lbtn = "<div onclick=loadPage('%id%') style='margin:auto;border-style:outset; background-color: %color% ; border-radius:5%; height:100px; width:100%; font-family:Museo700;overflow:hidden;color:black;'>";
		  lbtn += "<table height=100% width=100% style='text-align:center;vertical-align:middle'><tr><td>%name%</td></tr><tr><td><img src='%image%'/ style='max-width:100%; max-height:70px'></td></tr></table></div>";
	  for(aId in allPages.pages){
		  if(aPage){
			  if(allPages.pages[aId].id==aPage){
				  currentPage = allPages.pages[aId];
			  }
		  } else {
			  if(allPages.pages[aId].mainPage.toUpperCase() === "TRUE"){
				var lTemp = lbtn.replace("%name%",allPages.pages[aId].name); 
				lTemp = lTemp.replace("%id%",allPages.pages[aId].id);
				lTemp = lTemp.replace("%color%","white");
				lTemp = lTemp.replace("%image%",allPages.pages[aId].image);
				lStr += lTemp;
			// "<input type='button' value='"+allPages.pages[aId].name+"' onclick=loadPage('"+allPages.pages[aId].id+"') />";
			  }
		  }
	  }

	  if(currentPage){
		if(currentPage.displayOnCod=="true"){
			goToPage(aPage);
		}
		for(bId in currentPage.pages){
			var lTemp = lbtn.replace("%name%",currentPage.pages[bId].name); 
			lTemp = lTemp.replace("%id%",currentPage.pages[bId].id);
			lTemp = lTemp.replace("%color%","white");
			lTemp = lTemp.replace("%image%",currentPage.pages[bId].image);
			lStr += lTemp;
			//"<input type='button' value='"+currentPage.pages[bId].name+"' onclick=loadPage('"+currentPage.pages[bId].id+"') />";
		}
	  }
	  
	  if(lStr!=""){
		if(aPage){
			var lTemp = lbtn.replace("%name%","Retour"); 
			lTemp = lTemp.replace("%id%","");
			lTemp = lTemp.replace("%color%","red");
			lTemp = lTemp.replace("%image%","");
			lStr += lTemp;
		}
		document.getElementById("button-pages-selector").innerHTML = lStr;
	  } else { loadPage(); }
	  $("#button-pages-selector").show();
	 
	}
	
	// for version 101
	function populateCategories(){
	  //debugger;
	  $("#button-pages-selector").hide();
	  var lOptions;
	  var lCount = 0;
	  lOptions = "";
	  for( aCat in allPages.pages){
		if(allPages.pages[aCat].type=="Category"){
			lOptions = lOptions + "<option value='"+allPages.pages[aCat].id+"'>"+allPages.pages[aCat].name+"</option>";
		lCount++;
	  }
	  }
	  document.getElementById("category-selector").innerHTML = lOptions;
	  document.getElementById("category-selector").size = lCount;
	  $("#list-pages-selector").show();
	}
	function categorySelected(){
	  var e = document.getElementById("category-selector");
	  var strUser='None';
	  if(e.selectedIndex>=0){
	   strUser = e.options[e.selectedIndex].value;
	  }
	  var aIdx = -1;
	  for( aCat in allPages.pages){
	    if(allPages.pages[aCat].id==strUser) {
		  aIdx=aCat;
		}
	  }
	  var lOptions = "";
	  var lCount = 0;
	  if(aIdx>=0) {
		  for( aPage in allPages.pages[aIdx].pages){
			lOptions = lOptions + "<option value='"+allPages.pages[aIdx].pages[aPage].id+"'>"+allPages.pages[aIdx].pages[aPage].name+"</option>";
		lCount++;
	  }
	  }
	  document.getElementById("page-selector").innerHTML = lOptions;
	  document.getElementById("page-selector").size = lCount;
	}
	
	// for version 100
	function addPageButtons(pageButtons){
	  var lOptions;
	  lOptions = "<option value='-1'>Nothing</option>";
	  for( aPage in pageButtons.pages){
	    lOptions = lOptions + "<option value='"+pageButtons.pages[aPage].id+"'>"+pageButtons.pages[aPage].name+"</option>";
	  }
	  document.getElementById("page-selector").innerHTML = lOptions;
	}
	
	
	function goToPage(strUser){
	  debugger;
	  if(!strUser){
		var e = document.getElementById("page-selector");
		strUser = e.options[e.selectedIndex].value;
	  }
      $.ajax({
        type: "GET",
        url: '/loadWebModule?name=PUSH_PAGES&pageId='+strUser,
		//module=loadpage.exe&pageId='+strUser+'&templateHtml=pageTemplate2.html&width=1024&height=1000&htmlPage=aPage.html',
        async: true,
        success: function(data) {
        },
        error : function() {
          console.log('Could not set page');
        }
      }); 
	
	}
// END PAGES Section	
	
	
	function hidePage(){
      $.ajax({
        type: "GET",
        url: '/showWebPage?page=',
        async: true,
        success: function(data) {
        },
        error : function() {
          console.log('Could not set page');
        }
      }); 
	  
	}
	
    window.addEventListener("load", init, false);
    //window.addEventListener("load", ShowCropImage);
    window.addEventListener('resize', ShowCropImage);

	function InitAllSettings(){
      $.ajax({
        type: "GET",
        url: '/getAllSettings',
        async: true,
        crossDomain: true,
        success: function(data) {
          LoadSettings(data)
        },
        error : function() {
		  settingsLoaded = false;
        }
      });
	};
	
	function isElementHidden (element) {
		return window.getComputedStyle(element, null).getPropertyValue('display') === 'none';
	}
	
	function LoadSettings(data){
		//console.log(data);
		var lStr;
		var aJson=JSON.parse(data);
		var modules = aJson.activeModules.split(",");
		for(res in modules){
		  $("#"+modules[res]).show();
		}
	    for(aId in aJson.video){
			if(aJson.video[aId].name.toUpperCase()=='CREW'){
				var elem = document.getElementById("CREWFEED");
				if(elem){
					if( !isElementHidden(elem)){
						$("#crew-stream-img").attr("src",aJson.video[aId].url);
					}
				}
				cropLeft = aJson.video[aId].cropLeft; 
				cropRight = aJson.video[aId].cropRight;
				cropTop = aJson.video[aId].cropTop;
				cropBottom = aJson.video[aId].cropBottom; 

				ShowCropImage();				
			}
			if(aJson.video[aId].name.toUpperCase()=='CUSTOMER'){
				customerVideSource = aJson.video[aId].url;
				$("#customer-stream-img").attr("src",customerVideSource);
			}
			if(aJson.video[aId].name.toUpperCase()=='CUSTOMER2'){
				$("#customer2-stream-img").attr("src",aJson.video[aId].url);
			}
		}

	   // sidebars populate	with images
	   if(aJson.pushbanners){
		   for(sb in aJson.pushbanners){
			 if(aJson.pushbanners[sb].id != ""){
				 $("#"+aJson.pushbanners[sb].id).show();
			 //Materialize carousel
			  lStr = "";
			  for(im in aJson.pushbanners[sb].library){
				lStr += "<a class='carousel-item' ontouchmove=StartTouch() ontouchstart=StartTouch()"; 
				lStr += " ontouchend=EndTouch('"+aJson.pushbanners[sb].id+"','" + escape(aJson.pushbanners[sb].library[im].SIDEBARImage) +"')";
				lStr += " ondblclick=PushBanner('"+aJson.pushbanners[sb].id+"','" + escape(aJson.pushbanners[sb].library[im].SIDEBARImage) +"') >";
				lStr += "<img src='"+aJson.pushbanners[sb].library[im].SIDEBARName + "' /></a>"; 
				var singleSidebar = document.getElementById("cod_sidebar_1_img");
				if(singleSidebar){
					singleSidebar.style.backgroundImage = "url('"+aJson.pushbanners[sb].library[im].SIDEBARName+"')" ;
					$('#SidebarSwitch').attr('onchange',"SetSingleSlide(this,'"+aJson.pushbanners[sb].id+"','" + escape(aJson.pushbanners[sb].library[im].SIDEBARImage)+"')");
					$('#SINGLESIDEBARCONTROL').show();
				} else {
					$('#SINGLESIDEBARCONTROL').hide();
				}
			  }
			  var elList = document.getElementsByName(aJson.pushbanners[sb].id+"_SLIDES");
			  var i ;
			  for(i = 0; i < elList.length; i++){
				elList[i].innerHTML=lStr;
			  }
			}
			$('.carousel').removeClass('initialized');
			$('.carousel').carousel({noWrap: true, indicators: true});
			};
		}
		if($("#barcodeValue")){	
			$("#barcodeValue").val(aJson.LastFIDScan);
			generateBarcode();
		}
		
		if($("#InfoText")[0]){
			lStr = "<table style='width:100%; text-align:center;' ><tr>";
			var aLen = Math.floor(100 / aJson.InfoText.length) + "%";
			for(id in aJson.InfoText){
				lStr += "<td width='"+aLen+"'>"+aJson.InfoText[id].txt+"</td>";
			}
			lStr += "</tr></table>";
			//$("#InfoText").text(aJson.InfoText);
			$("#InfoText")[0].innerHTML = lStr;
		}
		
		if(aJson.master == true){
			$("#localContentManager").show()
		} else {
			$("#localContentManager").hide()
		}
		
		$("#carDetectorState").attr("src","car-off.png");
		if(aJson.CarDetector){
			if(aJson.CarDetector.Active){
				$("#carDetectorState").attr("src","car-black.png");
			}
			if(aJson.CarDetector.CarIsPresent){
				$("#carDetectorState").attr("src","car-green.png");
			}
		}
		debugger;
		if(aJson.avatars && aJson.avatars.count > 0){
			var avList = document.getElementById("AVATARSELECTOR");
			lStr = '';
			for(av in aJson.avatars){
				lStr += "<a onclick=SetAvatar('"+aJson.avatars[av].filename+"') >";
				lStr += "<img class='avatar-item ";
				if(aJson.avatars[av].active==true){
					lStr += "avatar-active";
				}
				lStr += "' src='" + aJson.avatars[av].location + "' /></a>"; 
			}
			avList.innerHTML = lStr;
		}
		
		settingsLoaded = true;

	};

	
	//#################################
	// FUNCTIONS FOR VIDEO DISPLAY
	//#################################
	
    function ShowCropImage() {
      var ImageWidth = $("#CREWFEED").width();
      var ImageHeight = $("#CREWFEED").height();
      var FrameCropLeft = (ImageWidth / videoWidth) * cropLeft;
      var FrameCropRight = (ImageWidth / videoWidth) * cropRight;
      var FrameCropTop = (ImageHeight / videoHeight) * cropTop;
      var FrameCropBottom = (ImageHeight / videoHeight) * cropBottom;

      $("#frame-crop").css('left', FrameCropLeft);  
      $("#frame-crop").css('right', FrameCropRight);
      $("#frame-crop").css('top', FrameCropTop);
      $("#frame-crop").css('bottom', FrameCropBottom);
    }

    function CropImage (CropSettings, Stream) {
      // Now used only for crew stream video
      cropLeft = CropSettings.cropLeft; 
      cropRight = CropSettings.cropRight;
      cropTop = CropSettings.cropTop;
      cropBottom = CropSettings.cropBottom; 

      ShowCropImage();
    };

    // Check if Video streaming is set to off on COD  
    function GetVideoStatus() {
      $('.request-progress').show(); 
      $.ajax({
        type: "GET",
        url: '/getVideoStatus',
        //url: '/getVideoStatus',
        async: true,
        crossDomain: true,
        success: function(data) {
          $('.request-progress').hide(); 
          UpdateVideoStatus(data)
        },
        error : function() {
          $('.crew-video-stream-status').removeClass('label-success');
          $('.crew-video-stream-status').addClass('label-danger');
          $('.crew-video-source-status-text').html('Source check Error');
          $('.crew-stream-alert').show();
          $('.request-progress').hide(); 
        }
      }); 
    };

    function UpdateVideoStatus (status) {
      if (status == 'VideoStatusON') {
        $(".btn-play-stream").hide();
        $(".btn-stop-stream").show();
        $(".crew-video-stream-status").removeClass('label-danger');
        $(".crew-video-stream-status").addClass('label-success');
        $(".crew-video-source-status-text").html('Stream ONLINE');
      } else if (status == 'VideoStatusOFF') {
        $(".btn-stop-stream").hide(); 
        $(".btn-play-stream").show();
        $(".crew-video-stream-status").removeClass('label-success');
        $(".crew-video-stream-status").addClass('label-danger');  
        $(".crew-video-source-status-text").html('Stream OFFLINE'); 
      }
    };

    // CREW VIDEO STREAM SOURCE STATUS
    function GetCrewVideoSourceStatus() {
      $('.crew-stream-alert').hide();
      $('.request-progress').show();
      $.ajax({
        type: "GET",
        url: '/getCrewStreamStatus',
        async: true,
        crossDomain: true,
        success: function(data) {
          $('.request-progress').hide();
          SetCrewVideoSourceStatus(data)
        },
        error : function() {
          $('.crew-video-source-status').removeClass('label-success');
          $('.crew-video-source-status').addClass('label-danger');
          $('.crew-stream-alert').show();
          $('.request-progress').hide();
        }
      });
    }; 

    function SetCrewVideoSourceStatus(data) {
      if (data.search('CrewVideoSourceOFF') == -1 ) {
        $('.crew-video-source-status').removeClass('label-danger');
        $('.crew-video-source-status').addClass('label-success');
      } else {
        $('.crew-video-source-status').removeClass('label-success');
        $('.crew-video-source-status').addClass('label-danger');
      };
    }; 

    function SetVideoStatus(AStatus) {
      $('.crew-stream-alert').hide();
      $.ajax({
        type: "GET",
        url: '/setVideoStatus?status=' + AStatus,
        async: true,
        crossDomain: true,
        success: function(data) {
          UpdateVideoStatus(data)
        },
        error : function() {
          $('.crew-video-stream-status').removeClass('label-success');
          $('.crew-video-stream-status').addClass('label-danger');
          $('.crew-stream-alert').show();
        }
      }); 
    };
	
	function SwitchClientCamera(aChk){
		if(aChk.checked){
			$('#customer-stream-img').attr('src',customerVideSource);
		} else {
			$('#customer-stream-img').attr('src','OfflineImage.jpg');
		}
	}
	
	//#################################
	// FUNCTIONS FOR NAVIGATION CAROUSEL 
	//#################################
	var lastTouchTime;
	
	function PushBanner(aBannerId,aImage){
	  debugger;
	  //$(".carousel[name='"+aBannerId+"']").
      $.ajax({
        type: "POST",
        url: '/setBannerImage',
		data: { name : aBannerId, img : aImage },
        success: function(data) {
        },
        error : function() {
        }
      }); 
	}
	
	function SetSingleSlide(aEvt,aBannerId,aImage){
	  debugger;
      $.ajax({
        type: "POST",
        url: '/setSingleSlide',
		data: { name : aBannerId, img : aImage, checked : aEvt.checked },
        success: function(data) {
        },
        error : function() {
        }
      }); 
	}

	function StartTouch(){
		lastTouchTime = (new Date()).getTime();
	}
	
	function EndTouch(aBannerId,aImage){
	  var timeNow = (new Date()).getTime();	
	  if( timeNow > lastTouchTime + 100 ){
		  $.ajax({
			type: "POST",
			url: '/setBannerImage',
			data: { name : aBannerId, img : aImage },
			success: function(data) {
			},
			error : function() {
			}
		  }); 
	  }
	}
	
	//#################################
	// END FUNCTIONS FOR NAVIGATION CAROUSEL 
	//#################################
	
	function SwitchCarDetectorStatus(){
      $.ajax({
        type: "POST",
        url: '/changeCarDetectorStatus',
		data: { status : true },
        success: function(data) {
        },
        error : function() {
        }
      }); 
	}
	
	function SetAvatar(file){
      $.ajax({
        type: "POST",
        url: '/setAvatar',
		data: { "filename" : file },
        success: function(data) {
			location.reload();
        },
        error : function() {
        }
      }); 
	}