/*
 * Copyright 2005 Tridium, Inc. All Rights Reserved.
 */
 
/**
 * Tab JavaScript support for Touch Screen access.
 */
var touchscreen = new TouchScreen();
function TouchScreen()
{ 
  this.currentEvent = null;
  this.preloaded = false;
  
  this.debug     = false;
  this.debugStep = 0;
  this.clearTimeout = null;
  this.failure = false;
  
  this.attachKeyboard = function(elem)
  {
    var inputs = elem.getElementsByTagName("input");
    var textareas = elem.getElementsByTagName("textarea");
    var selects = elem.getElementsByTagName("select");
    
    this.addPress(inputs);
    this.addChange(textareas);    
    this.addSelect(selects);
    this.addBezelUse();        
    
    this.fixHeight();
  }
  
  this.addBezelUse = function()
  {
    var body = document;
    if(hx.ie)
      body.attachEvent("onkeydown", this.checkForArrowKeys);
    else  
      body.addEventListener("keydown", this.checkForArrowKeys, false);            
  }
  
  this.addChange = function(inputs)
  {
    for (var i=0; i<inputs.length; i++) 
    {
      if(inputs[i].getAttribute("noKeyboard") != null || inputs[i].getAttribute("keyboard") != null)
        continue;
      else  
        inputs[i].setAttribute("keyboard", true);
      
      if(hx.ie)
        inputs[i].attachEvent("onclick", this.change);
      else  
        inputs[i].addEventListener("click", this.change, false);            
    }
  }
  
  this.addPress = function(inputs)
  {
    for (var i=0; i<inputs.length; i++) 
    {
      if(inputs[i].getAttribute("noKeyboard") != null || inputs[i].getAttribute("keyboard") != null)
        continue;
      else  
        inputs[i].setAttribute("keyboard", true);
          
      if(inputs[i].type == "text" || inputs[i].type == "password")
      {
        if(hx.ie)
          inputs[i].attachEvent("onclick", this.change);
        else  
          inputs[i].addEventListener("click", this.change, false);            
      }      
      else if(inputs[i].type == "radio")
      {
        this.fixRadio(inputs[i]);
        if(hx.ie)
          inputs[i].attachEvent("onclick", this.radioChange);
        else  
          inputs[i].addEventListener("click", this.radioChange, false);            
      }
      else if(inputs[i].type == "checkbox")
      {
        this.fixCheck(inputs[i]);
        if(hx.ie)
          inputs[i].attachEvent("onclick", this.checkBoxChange);
        else  
          inputs[i].addEventListener("click", this.checkBoxChange, false);            
      }
    }    
  } 
  
  this.addSelect = function(selects)
  {
    for (var i=0; i<selects.length; i++) 
    {
      if(selects[i].getAttribute("noKeyboard") != null || selects[i].getAttribute("keyboard") != null || 
        !(selects[i].getAttribute("size") == null || selects[i].getAttribute("size") <= 1))
      {
        continue;
      }
      else  
        selects[i].setAttribute("keyboard", true);
        
      this.fixSelect(selects[i]);
      if(hx.ie)
        selects[i].attachEvent("onchange", this.selectChange);
      else  
        selects[i].addEventListener("change", this.selectChange, false);            
          
    }
  }
    
  this.change = function(e)
  {
    currentEvent=e;
    var elem = touchscreen.elemFromEvent(e)
    if(elem != null && (elem.readOnly || elem.disabled))
      return false;  
    keypad.show(elem);
  }
  
  //go to the parent until you find the scope (copy from smart table)
  this.elemFromEvent = function(event)
  {
    if(hx.ie) 
      return event.srcElement;
    else 
      return event.target;
  }
  
  this.endEvent = function(event)
  {    
    if(event == null)
      return false;
    if (event.stopPropagation)
      event.stopPropagation();        
    else
      event.cancelBubble = true;
    
    event.returnValue = false;
    return false;
  }
  
  this.fixRadio = function(input)
  {
    touchscreen.fixImage(input, "radio");
  }
  
  this.fixCheck = function(input)
  {
    touchscreen.fixImage(input, "check");
  }

  this.fixImage = function(input, imageName)        
  {
    if(input.style.display == 'none')
      return;
    input.style.display='none';
    
    var disabled = input.disabled;
    var extension = "";
    if(disabled)
      extension = "Disabled" + extension;
      
    var image = document.createElement("span");
    if(input.checked)
      image.className=imageName + "On" + extension;
    else
      image.className=imageName + "Off" + extension;
    
    //IE does not support post created labeling
    if(hx.ie)
      image.attachEvent("onclick", touchscreen.ieFix);    
          
    var inLabel = input.parentNode.tagName == "LABEL";
    if(!inLabel)
    {
      var label = document.createElement("label");
      input.parentNode.insertBefore( label, input );    
      input.parentNode.removeChild(input);
      label.appendChild(image);
      label.appendChild(input);
    }
    else
    {
      input.parentNode.insertBefore( image, input );    
    }
  }
  
  this.ieFix = function(e)
  {
    var elem = touchscreen.elemFromEvent(e);
    elem.nextSibling.click();
  }
  
  
  this.radioChange = function(e)
  {
    touchscreen.imageChange(touchscreen.elemFromEvent(e), "radio")
    setTimeout("touchscreen.changeDelay();", 1); 
  }
  
  this.checkBoxChange = function(e)
  {
    setTimeout("touchscreen.changeDelay();", 1); 
    touchscreen.imageChange(touchscreen.elemFromEvent(e), "check")
  }
  
  this.changeDelay = function()
  {
    var elems = document.getElementsByTagName("input");
    for(var i=0; i<elems.length; i++)
    {
      if(elems[i].type == "radio")
        touchscreen.imageChange(elems[i], "radio");
      else if(elems[i].type == "checkbox")
        touchscreen.imageChange(elems[i], "check");
    }
    
    elems = document.getElementsByTagName("select");
    for(var i=0; i<elems.length; i++)
    {
      touchscreen.imageSelectChange(elems[i]);      
    }
  }
  
  this.imageChange = function(input, imageName)
  {
    var checked = input.checked;
    var image = input.previousSibling;
    var disabled = input.disabled;
    var extension = "";
    if(disabled)
      extension = "Disabled" + extension;
    if(input.checked)
      image.className=imageName + "On" + extension;
    else
      image.className=imageName + "Off" + extension;
  }
  
  this.selectChange = function(e)
  {
    var select = touchscreen.elemFromEvent(e);
    touchscreen.imageSelectChange(select);
  }
  
  this.imageSelectChange = function(select)
  {
    
    var image = select.previousSibling;
    var disabled = select.disabled;
    var extension = "";
    if(disabled)
      extension = "Disabled" + extension;
    
    if(select.selectedIndex > -1 && select.selectedIndex < select.options.length)
      image.innerHTML=select.options[select.selectedIndex].text;
    image.className="touchSelect" + extension;
  } 
   
  this.fixSelect = function(select)        
  {
    if(select.style.display == 'none')
    {
      return;
    }
    select.style.display='none';
    
    var disabled = select.disabled;
    var extension = "";
    if(disabled)
      extension = "Disabled" + extension;
      
    var image = document.createElement("span");
    image.className="touchSelect" + extension;
    
    
    if(select.selectedIndex > -1 && select.selectedIndex < select.options.length)
      image.innerHTML=select.options[select.selectedIndex].text;
    
    //IE does not support implicit labeling

    if(hx.ie)
      image.attachEvent("onclick", touchscreen.clickSelectImage);    
    else
      image.addEventListener("click", touchscreen.clickSelectImage, false);            
    
    
          
    select.parentNode.insertBefore( image, select );    
  }     
  
  this.clickSelectImage = function(e)
  {
    var elem = touchscreen.elemFromEvent(e);
    
    if(elem != null && elem.nextSibling.disabled)
      return false;  
      
    selectKeypad.show(elem.nextSibling);
  }
  
  this.fireOnChange = function(elem)
  {
    
    if(hx.ie)
    {
      elem.fireEvent("onchange");
    }
    else
    {
      var changeEvent=document.createEvent("HTMLEvents");
      changeEvent.initEvent("change", true, true);
      elem.dispatchEvent(changeEvent);
    }
  }
  
  this.checkForArrowKeys = function(e)
  {
    var keycode;
    if (window.event) 
      keycode = window.event.keyCode;
    else if (e) 
      keycode = e.which;
    
    if(keycode == 37) //left
    {
      //history.go(-1);
      window.scrollBy(-50,0);      
    }
    else if(keycode == 38) //up
    {       
      window.scrollBy(0,-50);      
    }
    else if (keycode == 39) //right
    {
      window.scrollBy(50,0);
      //history.go(1);
    }
    else if(keycode == 40) //down
    {
      window.scrollBy(0,50);
    }
    else
      return true;
    
    //debug menu with bezel is a clockwise rotation within a second of pressing each button.
    if(keycode == 39)
      touchscreen.debugStep=0;
    else if(keycode == 40 && (touchscreen.debugStep == 0 || touchscreen.debugStep == 1))
      touchscreen.debugStep=1;
    else if(keycode == 37 && (touchscreen.debugStep == 1 || touchscreen.debugStep == 2))
      touchscreen.debugStep=2;
    else if(keycode == 38 && touchscreen.debugStep == 2)
    {
      selectKeypad.show(null, true);
      touchscreen.debugStep=0;      
    }
    else
      touchscreen.debugStep=0;        

    if(touchscreen.clearTimeout != null)
      clearTimeout(touchscreen.clearTimeout);
      
    touchscreen.clearTimeout = setTimeout("touchscreen.clearCode();", 1000);
    
    return false;
  }
  
  this.clearCode = function()
  {
    touchscreen.clearTimeout = null;
    touchscreen.debugStep = 0;    
  }
  
  
  
  this.fixHeight = function()
  {
    if(document.body.offsetHeight >= 460 && document.body.offsetHeight < 500 && 
       document.body.offsetWidth  >= 780 && document.body.offsetWidth < 820  && 
       document.body.scrollHeight >= 460 && document.body.scrollHeight < 500 &&
       document.body.scrollWidth  >= 780 && document.body.scrollWidth < 820)
       
    {
      if(touchscreen.heightFix)
        return;
      document.body.style.height="480px";
      document.body.style.overflow="hidden";
      touchscreen.heightFix=true;
    }
    else if(touchscreen.heightFix == true)
    {
      document.body.style.height="";
      document.body.style.overflow="";
    }
  }
  
  this.heightFix = false;
  
  ////////////////////////////////////////////////////////////////
  // Touchscreen Error Handling
  ////////////////////////////////////////////////////////////////
  
  this.init = function()
  {
    try
    {
      hx.errorInvokeCode = "touchscreen.errorInvokeCode();";
    }
    catch(err)
    {}    
  }
  
  this.timeout = function()
  {
    try
    {
      selectKeypad.show(null, true, "Session disconnected, waiting for reconnect...");
      touchscreen.failure=true;      
    }
    catch(err)
    {}
  }
  
  this.badRequest = function()
  {
    try
    {
      window.onbeforeunload=null;
      window.location='/login';      
    }
    catch(err)
    {}
  }
  
  this.reconnect = function()
  {
    try
    {
      if(touchscreen.failure == true)
      {
        touchscreen.failure=false;
        //close navigation menu
        hx.closeDialog(null, null);
      }      
    }
    catch(err)
    {}
  }
  
  this.errorInvokeCode = function()
  {
    try
    {
      if(hx.err_LostConnection == hx.lastExceptionMessage)
      {
        touchscreen.timeout();
        return true;
      }
      else if(hx.lastExceptionMessage != null && hx.lastExceptionMessage.indexOf('<h1>400:') > -1)
      {
        touchscreen.badRequest();
        return true;
      }
      else if(hx.lastExceptionMessage != null && hx.lastExceptionMessage.indexOf('<h1>404:') > -1)
      {
        touchscreen.timeout();
        return true;
      }
      else if(hx.lastExceptionMessage != null && hx.lastExceptionMessage.indexOf('<h1>405:') > -1)
      {
        
        touchscreen.timeout();
        return true;
      }
      else if(hx.ie && hx.lastExceptionMessage != null && hx.lastExceptionMessage.indexOf('Error: Unspecified error.') > -1);
      {
        if(hx.lastExceptionDetails != null && hx.lastExceptionDetails.indexOf("window.location=") > -1)
        {
          touchscreen.timeout();
          return true;
        }
      }
      
      //just reload
      var stack = hx.lastExceptionDetails;
      if(stack != null && stack.indexOf("&lt;title&gt;" + touchscreen.loginLex +"&lt;/title&gt;") > -1)
      {        
        window.onbeforeunload=null;
        window.location.reload();
        return true;
      }
      else
      {
        return false;
      }
    }
    catch(err)
    {
      //alert("caught:" + err);
    }
  }

  
      
} 

