var imgp=decodeURIComponent(atob(imagepath));
imgp=imgp.split('"').join('');
var prevel = null;
var volume=1; //Για να ρυθμίζει τον ήχο ον/οφ
var snd; // Για να παίζει ήχους.
var sf=false; //StepForward is pressed
var sb=false; //StepBack is pressed
var nextDuration=0;
var keyTimer; //Για setTimeOut και Interval
var timer=null; //Για setTimeOut και Interval
var tm1,tm2,tm3=null; //Για setTimeOut και Interval
var keypresses;
var currentEventID = 0;
var numberOfEvents = data.events.length;
var select=null;
var selectScrollY;
var selectOptionY;


// var data είναι το JSON που έρχεται από την εφαρμογή με τη λίστα των events

function getLeft(elm) {
  var rec = elm.getBoundingClientRect();
  return rec.left + window.pageXOffset;
}

function getTop(elm) {
  var rec = elm.getBoundingClientRect();
 // alert(rec.top +"---"+ window.pageYOffset);
  return rec.top + window.pageYOffset;
} 

function MouseMove(x,y) {
	var pointer = document.getElementById('pointer');
	if (data.events[currentEventID].Params.WithinList=="1") y=parseInt(pointer.style.top,10)+10;
	pointer.style.left = (x-13)+'px';
	pointer.style.top = (y-10)+'px';
	document.getElementById('imageBox').style.left=(x-13+64+10)+'px';
	document.getElementById('imageBox').style.top=(y-10)+'px';
  }

function MouseClickDown() {
	  document.getElementById('pp').src=imgp+"mouse_click.png";
  }
 
function MouseClickUp() {
	  document.getElementById('pp').src=imgp+"mouse.png";
  }
  
function MouseClick(elm) {
	  MouseClickDown();
	  KLMFocus(elm);
	  if(elm){ 
		elm.select();
		prevel=elm;
	  }	  
	  setTimeout(function(){MouseClickUp();}, 1500);	
  }
 
function KLMFocus(elm) {	
	   if(elm){
			var foc=document.getElementById('FocusIndicator');
			foc.style.left=(getLeft(elm)-4)+'px';
			foc.style.top =(getTop(elm)-4)+'px';
			foc.style.borderleft = "4px solid #afcbf7";
			foc.style.bordertop = "4px solid #afcbf7";
			foc.style.height=(elm.offsetHeight-2)+"px";
			foc.style.width=(elm.offsetWidth-2)+"px";
			foc.style.zIndex="1000";
			foc.visibility="visible";
			elm.focus(); 
			setTimeout(function(){elm.focus();elm.focus();elm.focus();elm.focus();elm.focus();elm.focus();elm.focus();elm.focus();}, 500);
			//alert(elm.getAttribute("name"));
	   }
  }

function TextBoxKeyPress(elm,NKeys) {
	elm.value="";
	keypresses=0;
	KLMFocus(elm);
	keyTimer = setInterval(function(){elm.value+="*"; keypresses++; document.getElementById('imageBox').style.visibility='visible';
	document.getElementById('klmImage').src="";
	document.getElementById('klmImage').src=imgp+"K.gif"+"?a="+Math.random();
	if(keypresses>=NKeys) {clearInterval( keyTimer );keyTimer=null;} if(sb || sf) {clearInterval( keyTimer );keyTimer=null;document.getElementById('imageBox').style.visibility='hidden';elm.value="";}},500);
}

function RadioArrowsKeyPress(elms,NKeys) {
	keypresses=0;
	var kTimer = setInterval(function(){elms[keypresses+1].checked=true; keypresses++; document.getElementById('imageBox').style.visibility='visible';
	document.getElementById('klmImage').src="";
	document.getElementById('klmImage').src=imgp+"K.gif"+"?a="+Math.random();
	//AAA//
	if(keypresses>=NKeys) {clearInterval(kTimer);kTimer=null;return;} if(sb || sf) {clearInterval(keyTimer);keyTimer=null;document.getElementById('imageBox').style.visibility='hidden';return;}},500);
}

function ListArrowsKeyPress(elm,NKeys) {
	keypresses=0;
	var kTimer = setInterval(function(){elm.selectedIndex=keypresses++; document.getElementById('imageBox').style.visibility='visible';
	document.getElementById('klmImage').src="";
	document.getElementById('klmImage').src=imgp+"K.gif"+"?a="+Math.random();
	
	if(keypresses>=NKeys) {clearInterval(kTimer);kTimer=null;return;} if(sb || sf) {clearInterval(keyTimer);keyTimer=null;document.getElementById('imageBox').style.visibility='hidden';return;}},500);
}

function PlayClickMouse() {
	var elm=(document.getElementsByName(data.events[currentEventID].Params.Element).length==0?null:document.getElementsByName(data.events[currentEventID].Params.Element)[0]);
	MouseClick(elm);
}

function PlayClickMouseDown() {
	  MouseClickDown();
}

function PlayClickMouseUp() {
	  MouseClickUp();
}

function ExpandSelect(elname, maxOptionsVisible){
		select=(document.getElementsByName(elname).length==0?null:document.getElementsByName(elname)[0]);
		//alert(data.events[currentEventID].Params.Element);
	   if (typeof maxOptionsVisible == "undefined") {
                maxOptionsVisible = 20;
        }
        if (typeof window["ExpandSelect_tempID"] == "undefined") {
                window["ExpandSelect_tempID"] = 0;
        }
        window["ExpandSelect_tempID"]++;

        var rects = select.getClientRects();

        // ie: cannot populate options using innerHTML.
        function PopulateOptions(select, select2)
        {
                select2.options.length = 0; // clear out existing items
                for (var i = 0; i < select.options.length; i++) {
                        var d = select.options[i];
						//d.style.fontSize="16px";
                        select2.options.add(new Option(d.text, i))
                }
        }

        var select2 = document.createElement("SELECT");
        //select2.innerHTML = select.innerHTML;
        PopulateOptions(select, select2);
        select2.style.cssText = "visibility: hidden;";
        if (select.style.width) {
                select2.style.width = select.style.width;
        }
        if (select.style.height) {
                select2.style.height = select.style.height;
        }
        select2.id = "ExpandSelect_" + window.ExpandSelect_tempID;

        select.parentNode.insertBefore(select2, select.nextSibling);
        select = select.parentNode.removeChild(select);

        if (select.length > maxOptionsVisible) {
                select.size = maxOptionsVisible;
        } else {
                select.size = select.length;
        }

        if ("pageXOffset" in window) {
                var scrollLeft = window.pageXOffset;
                var scrollTop = window.pageYOffset;
        } else {
                // ie <= 8
                // Function taken from here: http://help.dottoro.com/ljafodvj.php
                function GetZoomFactor()
                {
                        var factor = 1;
                        if (document.body.getBoundingClientRect) {
                                var rect = document.body.getBoundingClientRect ();
                                var physicalW = rect.right - rect.left;
                                var logicalW = document.body.offsetWidth;
                                factor = Math.round ((physicalW / logicalW) * 100) / 100;
                        }
                        return factor;
                }
                var zoomFactor = GetZoomFactor();
                var scrollLeft = Math.round(document.documentElement.scrollLeft / zoomFactor);
                var scrollTop = Math.round(document.documentElement.scrollTop / zoomFactor);
        }

        select.style.position = "absolute";
        select.style.left = (rects[0].left + scrollLeft) + "px";
        select.style.top = (rects[0].top + scrollTop) + "px";
        //select.style.zIndex = "1000000";

        var keydownFunc = function(e){
                e = e ? e : window.event;
                // Need to implement hiding select on "Escape" and "Enter".
                if (e.altKey || e.ctrlKey || e.shiftKey || e.metaKey) {
                        return 1;
                }
                // Escape, Enter.
                if (27 == e.keyCode || 13 == e.keyCode) {
                        select.blur();
                        return 0;
                }
                return 1;
        };

        if (select.addEventListener) {
                select.addEventListener("keydown", keydownFunc, false);
        } else {
                select.attachEvent("onkeydown", keydownFunc);
        }

        var tempID = window["ExpandSelect_tempID"];

        var clickFunc = function(e){
                e = e ? e : window.event;
                if (e.target) {
                        if (e.target.tagName == "OPTION") {
                                select.blur();
                        }
                } else {
                        // IE case.
                        if (e.srcElement.tagName == "SELECT" || e.srcElement.tagName == "OPTION") {
                                select.blur();
                        }
                }
        };

        if (select.addEventListener) {
                select.addEventListener("click", clickFunc, false);
        } else {
                select.attachEvent("onclick", clickFunc);
        }

        var blurFunc = function(){
                if (select.removeEventListener) {
                        select.removeEventListener("blur", arguments.callee, false);
                        select.removeEventListener("click", clickFunc, false);
                        select.removeEventListener("keydown", keydownFunc, false);
                } else {
                        select.detachEvent("onblur", arguments.callee);
                        select.detachEvent("onclick", clickFunc);
                        select.detachEvent("onkeydown", keydownFunc);
                }
                select.size = 1;
                select.style.position = "static";
                select = select.parentNode.removeChild(select);
                var select2 = document.getElementById("ExpandSelect_"+tempID);
                select2.parentNode.insertBefore(select, select2);
                select2.parentNode.removeChild(select2);

        };

        if (select.addEventListener) {
                select.addEventListener("blur", blurFunc, false);
        } else {
                select.attachEvent("onblur", blurFunc);
        }

        document.body.appendChild(select);
        select.focus();
		
		selectOptionY=parseInt(select.clientHeight, 10)/2;
		selectScrollY=(parseInt(select.scrollHeight, 10)-parseInt(select.clientHeight, 10))/2;
		
		//alert("Height:"+select.height+" style.height:"+select.style.height+" offsetheight:"+select.offsetHeight+" clientheight:"+select.clientheight+" scrollheight:" + select.scrollHeight);
}

function PlayListBoxScrollDrag() {
	  //alert(selectOptionY);
	 // alert(selectScrollY);
	  var pointer = document.getElementById('pointer');
	  var el=(document.getElementsByName(data.events[currentEventID].Params.Element)[0]);
	  var finalScrollTop=selectScrollY-10; 
	  el.scrollTop=0;
	   var t=setInterval(function(){
		   el.scrollTop = el.scrollTop + 10;
		   if (el.scrollTop>=finalScrollTop)
		   {
			   clearInterval(t);
			   t=null;
		   }
	   },50);
	   var finalY=selectOptionY;

	   setTimeout(function(){
			pointer.style.top = parseInt(el.style.top,10)+(finalY-10)+'px';
			document.getElementById('imageBox').style.top=parseInt(el.style.top,10)+(finalY-10)+'px';			
	   },50);
}

function PlayListBoxClickMouse() {
		 var elm=(document.getElementsByName(data.events[currentEventID].Params.Element).length==0?null:document.getElementsByName(data.events[currentEventID].Params.Element)[0]);
		 //alert(data.events[currentEventID].Params.Element+"---"+document.getElementsByName(data.events[currentEventID].Params.Element).length);
		 if (elm==null) return;
		 MouseClickDown();
		 KLMFocus(elm);
		 elm.selectedIndex = "0"; 
		 KLMFocus(elm);
		 setTimeout(function(){MouseClickUp();KLMFocus(elm);}, 800);	
		 prevel=elm;
		 KLMFocus(elm);
	     setTimeout(ExpandSelect,1000, data.events[currentEventID].Params.Element);
		 KLMFocus(elm);
}

function PlayListBoxOptionClickMouse() {
	MouseClickDown();
	var elm=(document.getElementsByName(data.events[currentEventID].Params.Element).length==0?null:document.getElementsByName(data.events[currentEventID].Params.Element)[0]);
	if (elm==null) return;
	elm.options[Math.ceil(elm.options.length/2)-1].selected = 'selected';
	elm.selectedIndex = Math.ceil(elm.options.length/2)-1;	
	setTimeout(function(){select.blur();}, 1200);	
	setTimeout(function(){MouseClickUp();}, 1500);	
	prevel=elm;
 }
 
function PlayRadioCheckClickMouse() {
	var elm1=null;
	if (document.getElementsByName(data.events[currentEventID].Params.Element).length==1){ 
		elm1=document.getElementsByName(data.events[currentEventID].Params.Element)[0];
	}
	MouseClick(elm1);
	KLMFocus(elm1);
	//gia radio button xtipa to meseo
	var c=document.getElementsByName(data.events[currentEventID].Params.Element).length;
	KLMFocus(elm1);
	if (c>1){
			elm1=document.getElementsByName(data.events[currentEventID].Params.Element)[Math.ceil(c/2)-1];
	KLMFocus(elm1);
		}
		else{
			elm1=document.getElementsByName(data.events[currentEventID].Params.Element)[0];			
	KLMFocus(elm1);
	} 
	elm1.checked=true;
	KLMFocus(elm1);
 }
 
function PlayPointMouse() {
	MouseMove(data.events[currentEventID].Params.X,data.events[currentEventID].Params.Y);
 }

function PlayShowImage() {
	document.getElementById('imageBox').style.visibility='visible';
	document.getElementById('klmImage').src="";
	document.getElementById('klmImage').src=imgp+data.events[currentEventID].Params.File+"?a="+Math.random();
 }

function PlayShowMessage() {
   //alert(data.events[currentEventID].Params.Message);
   //if(data.events[currentEventID].Params.Message=="First.") {alert("First"); playSound("http://localhost:8084/sounds/Settings.mp3");};
   document.getElementById("messageBox").innerHTML+=data.events[currentEventID].Params.Message;
   document.getElementById("messageBox").scrollTop = document.getElementById("messageBox").scrollHeight;
 }
 
function StartMouse() {
   var pointer = document.getElementById('pointer');
   pointer.src="";
   if (data.events[currentEventID].Params.X!=1)
   {
		pointer.style.left = (data.events[currentEventID].Params.X-13)+'px';
		pointer.style.top = (data.events[currentEventID].Params.Y-10)+'px';
		document.getElementById('imageBox').style.left=(data.events[currentEventID].Params.X-13+64+10)+'px';
		document.getElementById('imageBox').style.top=(data.events[currentEventID].Params.Y-10)+'px';
		var elm=document.getElementsByName(data.events[currentEventID].Params.Element)[0];
		KLMFocus(elm);
		elm.select();
	}
	else
	{
		pointer.style.left = (1)+'px';
		pointer.style.top = (1)+'px';
	}
	setTimeout(function() {document.getElementById('pp').src=imgp+"mouse.png";
	pointer.style.visibility='visible';}, 1000);	
 }
 
function PlayTab() {
	    tm1=setTimeout(PlayShowImage(),4000);
		var elm=(document.getElementsByName(data.events[currentEventID].Params.Element).length==0?null:document.getElementsByName(data.events[currentEventID].Params.Element)[0]);
		KLMFocus(elm);		
		if(elm)
		{
			if (elm.tagName.toLowerCase()!="select" && elm.type.toLowerCase()!="submit") elm.select();
			document.getElementById('imageBox').style.left=(data.events[currentEventID].Params.X-13+64+10)+'px';
			document.getElementById('imageBox').style.top=(data.events[currentEventID].Params.Y-10)+'px';
			prevel=elm;
		}
 }
 
function PlaySpace() {
		setTimeout(function(){document.getElementById('imageBox').style.visibility='visible';
		document.getElementById('klmImage').src="";
		document.getElementById('klmImage').src=imgp+"space.gif"+"?a="+Math.random();},1500);		
		var elm=document.getElementsByName(data.events[currentEventID].Params.Element)[0];
		if(elm)
		{	
			KLMFocus(elm);
			if(document.getElementsByName(data.events[currentEventID].Params.Element).length>1) //radios
			{
				elm.select();
				elm.checked=true;				
			}
			else if (elm.tagName.toLowerCase()!="select" && elm.type.toLowerCase()!="submit") //checkbox
			{				
				elm.select();
				elm.checked=!elm.checked;
			}
			document.getElementById('imageBox').style.left=(data.events[currentEventID].Params.X-13+64+10)+'px';
			document.getElementById('imageBox').style.top=(data.events[currentEventID].Params.Y-10)+'px';
			prevel=elm;
		}
}
 
function PlayTextKeyPress() {
	  if (data.events[currentEventID].Params.Arrows){
		 RadioArrowsKeyPress(document.getElementsByName(data.events[currentEventID].Params.Element),data.events[currentEventID].Params.NumofKeys);
	  }
	  else {
		if (data.events[currentEventID].Params.ListArrows){
			ListArrowsKeyPress(document.getElementsByName(data.events[currentEventID].Params.Element)[0],data.events[currentEventID].Params.NumofKeys);
		} 
		else {
			if (data.events[currentEventID].Params.ListChars){
				var elm=document.getElementsByName(data.events[currentEventID].Params.Element)[0];
				TextBoxKeyPress(elm,data.events[currentEventID].Params.NumofKeys);
				setTimeout(function(){elm.selectedIndex=Math.ceil(elm.options.length/2)-1;},500);
			} 
			else {
				TextBoxKeyPress(document.getElementsByName(data.events[currentEventID].Params.Element)[0],data.events[currentEventID].Params.NumofKeys);
			}
		}
	  }
 }
 
function PlayStepInfo() {
	    var X=(data.events[currentEventID].Params.X-13<0?1:data.events[currentEventID].Params.X-13);
	    var Y=(data.events[currentEventID].Params.Y-10<0?1:data.events[currentEventID].Params.Y-10);

		if (data.events[currentEventID].Params.CurrentElement=="Start" || data.events[currentEventID].Params.CurrentElement=="Finish") return;
		var pointer = document.getElementById('pointer');
		pointer.src="";
		pointer.style.left = X+'px';
		pointer.style.top = Y+'px'; 	 	
	
		document.getElementById('imageBox').style.left=(X+64+10)+'px';
		document.getElementById('imageBox').style.top=Y+'px';
		var elm=document.getElementsByName(data.events[currentEventID].Params.CurrentElement)[0];
		//to stepID 3 einai to proto element pou ksekina. Giayto to kano focus
		if(data.events[currentEventID].Params.Focused=="True" || data.events[currentEventID].StepID==3) {
			if (elm.tagName.toLowerCase()!="select" && elm.type.toLowerCase()!="submit") elm.select();
			KLMFocus(elm);
		}
		setTimeout(function() {document.getElementById('pp').src=imgp+"mouse.png";
		pointer.style.visibility='visible'; if(data.events[currentEventID].Params.Focused=="True" || data.events[currentEventID].StepID==3) {KLMFocus(elm);}}, 500);  
 }

function playEvent() {
   //document.getElementById("PlayerHeader").innerHTML=data.events[currentEventID].Header;
   if ((!sf && !sb) && !timer) return;
   var eventType = data.events[currentEventID].Type;
   switch (eventType) {
    case "Descriptive":
        PlayShowMessage(); 
        break;
    case "Image":
        PlayShowImage();
        break;
    case "Point":
        PlayPointMouse();
		break;
    case "RadioCheckClick":
        PlayRadioCheckClickMouse();
		break;
    case "Click":
        PlayClickMouse();
		break;
    case "MouseDown":
        PlayClickMouseDown();
		break;
    case "MouseUp":
        PlayClickMouseUp();
		break;
	case "ScrollDrag":
        PlayListBoxScrollDrag();
		break;
	case "ListBoxClick":
        PlayListBoxClickMouse();
		break;
	case "ListBoxOptionClick":
        PlayListBoxOptionClickMouse();
		break;
    case "SpacePress":
        PlaySpace();
		break;
	case "TabPress":
        PlayTab();
		break;
	case "KeyPress":
        PlayTextKeyPress();
		break;
	case "StepInfo":
		document.getElementById("messageBox").innerHTML="";
        if(sf){
			PlayStepInfo() 
		} else {
			if(sb) {
				PlayStepInfo();
			} else {
				var elm=document.getElementsByName(data.events[currentEventID].Params.CurrentElement)[0];
				//to stepID 3 einai to proto element pou ksekina. Giayto to kano focus
				if(data.events[currentEventID].Params.Focused=="True" || data.events[currentEventID].StepID==3) {
					KLMFocus(elm);
					if (elm.tagName.toLowerCase()!="select" && elm.type.toLowerCase()!="submit") elm.select();
				}
			}
		}
		break;
	case "Initial":
        StartMouse();
	}
 }

function playSound(soundPath){
		//alert(volume);
		snd = new Audio(soundPath); // buffers automatically when created
		snd.volume=volume;
        snd.play();
}
 
function play(){
		if ((!sf && !sb) && !timer) return;
		document.getElementById('imageBox').style.visibility='hidden';
		//Αν έχει πατηθεί το νεχτ ψάξε μέχρι να φτάσεις στο επόμενο stepId που θα έχει και stepinfo event
		if (sf)
		{
			var stepid=data.events[currentEventID].StepID;
			while (data.events[currentEventID].StepID==stepid)
			{		
				if (currentEventID==numberOfEvents) {sf=false;return;}
				currentEventID++;
			}		
			playEvent();
			sf=false;
			currentEventID++;
			if (currentEventID==numberOfEvents){
				 currentEventID=0;
				 document.getElementById("playpause").className = "fa fa-play";
				 timer=null;
			}
			timer=1;
			nextDuration=100;
			document.getElementById("playpause").className = "fa fa-pause";
			playnext();
		}
		else
		if (sb)
		{
			var stepid=data.events[currentEventID].StepID;
			if (data.events[currentEventID].Type=="StepInfo") 
				if (currentEventID==0) {sb=false;return;}
				else
					currentEventID--;
			while (data.events[currentEventID].Type!="StepInfo") 
			{		
				if (currentEventID==0) break;
				currentEventID--;
			}			
			playEvent();
			sb=false;
			timer=1;
			nextDuration=400;
			document.getElementById("playpause").className = "fa fa-pause";
			playnext();
		}
		else
		{
			nextDuration=0;
			while (data.events[currentEventID].Type!="Descriptive")
			{
			      nextDuration=(nextDuration<data.events[currentEventID].Duration?data.events[currentEventID].Duration:nextDuration);
				  playEvent();
				  currentEventID++;
			}
			//if (document.activeElement.getAttribute("name")=="lastname") alert(document.activeElement.getAttribute("name"));
			nextDuration=(nextDuration<data.events[currentEventID].Duration?data.events[currentEventID].Duration:nextDuration);
			//alert(nextDuration);
			playSound("http://localhost:8084/sounds/"+encodeURI(data.events[currentEventID].Params.SoundFile+".mp3"));		
			playEvent();
			currentEventID++;
			if (currentEventID==numberOfEvents){
				 currentEventID=0;
				 document.getElementById("playpause").className = "fa fa-play";
				 document.getElementById("contentContainer").style.visibility="hidden";
				 timer=null;
			}
			else
			{
				playnext();
			}
		}
		
}

function playnext(){
       if(timer) tm2=setTimeout(play,nextDuration);
}

function setTimer(t){
    if (timer) {
	   t.className = "fa fa-play";
	   SoundStop(); 
	   timer=null;	
	   fst=false;	   
	}
    else {
	   t.className = "fa fa-pause";
	   timer=1;
	   tm3=setTimeout(play,500);
    }
	return false;
}

function StepForward(){
	sf=true;
	SoundStop();
	ClearTimeOuts();
	play();
	return false;
}

function StepBack(){
	sb=true;
	SoundStop();
	ClearTimeOuts();
	play();
	return false;
}

function soundToggle(t){
	if(t.className=="fa fa-volume-up fa_custom fa-2x"){
		volume=0;
		if(snd) {
			snd.volume = 0;
		}
		t.className ="fa fa-volume-off fa_custom fa-2x";
		//alert(volume);
	}
	else {
		t.className ="fa fa-volume-up fa_custom fa-2x";		
			snd.volume = 1;
			volume=1;
	}
    
	return false;
}

function ClearTimeOuts(){
	timer=null;
	if (tm1) {clearTimeout(tm1);tm1=null}
	if (tm2) {clearTimeout(tm2);tm2=null}
	if (tm3) {clearTimeout(tm3);tm3=null}
}

function SoundStop(){
	if(snd){
		snd.pause();
		snd.currentTime = 0;
	}	
}

function Stop(){
	SoundStop();
	ClearTimeOuts();
	currentEventID=0;
	document.getElementById("playpause").className = "fa fa-play";	
	document.getElementById("contentContainer").style.visibility="hidden";
	document.getElementById("pointer").style.visibility="hidden";
}

function restart(){
	Stop();
	prevel = null;
	sf=false; //StepForward is pressed
	sb=false; //StepBack is pressed
	nextDuration=500;
	keyTimer=null;
	keypresses=0;
		document.getElementById("contentContainer").style.visibility="visible";
	setTimer(document.getElementById("playpause"));
	document.getElementById("playpause").className = "fa fa-pause";
	return false;
}





