/*
  This is added to every IFrame
*/


/* ###########################
   Prototypes
   ############################ */

// Array.indexOf( value, begin, strict ) - Return index of the first element that matches value
  Array.prototype.indexOf = function( v, b, s ) {
    for( var i = +b || 0, l = this.length; i < l; i++ ) {
      if( this[i]===v || s && this[i]==v ) { return i; }
    }
    return -1;
  };

/* ###########################
   Form Events
   ########################### */

/* Std HTML Events */

  function ejc_BodyOnLoad() {
    if (window.top != window.self) {
      ejc_ResizeIFrame();
      window.top.eJIF_IFrameLoaded();
    }
  }

/* Extended Events */

  function ejc_OnHide() { // Called by the menu when visibiity changes
//    window.alert('ejc_OnHide '+document.title);
    var input;
    var inputs = document.getElementsByTagName('input');
    for (i = 0; i < inputs.length; i++) {
      input = inputs[i];
      if (input.style.backgroundColor == clEditedColour) {
//        window.alert('blurring '+input.id);
        //input.blur();  // doesn't work in ie'
        input.onchange();
        return;
      }
    }
  }


/* ###########################
   Screen Management
   ############################ */

  if (window.top != window.self) { // in an IFRAME
    if (window.addEventListener){
      window.addEventListener("resize", ejc_ResizeIFrame, false);
    } else if (window.attachEvent){
      var r = window.attachEvent("onresize", ejc_ResizeIFrame);
    }
  }

  function ejc_VPHeight() {
    Result = 0;
    if (window.innerHeight != window.undefined) {Result = window.innerHeight;}
    if (document.compatMode=='CSS1Compat') {Result = document.documentElement.clientHeight;}
    if (document.body) {Result = document.body.clientHeight;}
    return Result;
  }

  function ejc_VPWidth() {
    Result = 0;
    if (window.innerWidth!=window.undefined) {Result = window.innerWidth;}
    if (document.compatMode=='CSS1Compat') {Result = document.documentElement.clientWidth;}
    if (document.body) {Result = document.body.clientWidth;}
    return Result;
  }

  function ejc_ResizeIFrame() {
    var FullHeight = ejc_VPHeight();
//    var TrimHeight = 10;
    var TrimHeight = 30;
//    var TrimHeight = 0;

    var div = document.getElementById('ExtendToBottom');
    if (div) {
      var Top = div.offsetTop
      var Height = FullHeight - TrimHeight - Top;
      if (Height > 0) {
        div.style.height = Height+'px';
      }
//      alert('setting height to '+div.style.height);
    }
  }

  function  ejc_FlushChachedPages() {
    window.top.eJIF_SendIFramesMessage('blank', true);
  }

  function ejc_RefreshRequest() {
    window.top.eJIF_SetProcessingDlg(true, 'Refreshing please wait');
    window.location.reload();
  }

  function ejc_LinkOnClick() {
    window.top.eJIF_IFrameLoading();
    return false
  }


  function ejc_GetValueByID(ID) {
    var obj = document.getElementById(ID);
    if (obj != null) {
      return obj.value;
    } else {
      return null;
    }
  }

  function ejc_SetValueByID(ID, Value) {
    var obj = document.getElementById(ID);
    if (obj != null) {
      obj.value = Value;
    } else {
      return (obj != null);
    }
  }

  function ejc_EditingKey(KeyCode) {
    // BS & Delete
    return (KeyCode == 8) || (KeyCode == 46);

  }

  function ejc_CursorKey(KeyCode) {
    // tab, left right arrow, return
    return (KeyCode == 9) || (KeyCode == 39) || (KeyCode == 37) || (KeyCode == 13);
  }


  function ejc_NumericInputOnKeyUp(Event, Input, DecimalPlaces, ProcessFunction) {

    // Old Version only used for products frame
    // should be replace with central input control


    var KeyCode = Event.keyCode;
    var Value = Input.value;
    var OldValue = Value;
    var i;

    if (KeyCode == 13) {
      ProcessFunction(Input);
      return false;
    }

    // if decimal pressed trim digits and remove following dec pts

    if (KeyCode == 190) {
      i = Value.indexOf('.');
      if (i != Value.lastIndexOf('.')) {
        Value = Value.substr(0, i)+'.'+Value.replace('.','').substring(i);
      }
    }

    // Check the decimal places
    if ((i = Value.indexOf('.')) >= 0) {
      if (i+DecimalPlaces+2 < Value.length) {
        Value = Value.substr(0, i+DecimalPlaces+1);
      }
    }

    if (Value != OldValue) {
      Input.value = Value;
      Input.style.backgroundColor = clEditedColour;
    } else {
      if (!ejc_CursorKey(KeyCode)) {
        Input.style.backgroundColor = clEditedColour;
      }
    }


    return true;

    // old code

    if (Event.keyCode == 13) {
      ProcessFunction(Input);
      return false;
    }

    if (Event.keyCode == 9 || Event.keyCode == 16) { // tab and back tab
      return true
    }

    var Value = Input.value;

    if (Event.keyCode == 8) { // backspace
      Input.style.backgroundColor = clEditedColour;
      return true
    }
    // Value checking
    var Value = Input.value;
//    if  (Value == '.' && DecimalPlaces > 0) {Value = '0';} // allow decimal transition
    var LastChar = Value.substring(Value.length-1,Value.length);
    var S = parseFloat(Value);
    if (Value == '') {S = 0;}
    if (Value == '-') {S = 0;} // allow - prefix
    var DP = 0;
    if (Value.indexOf('.') >= 0) {
      DP = Value.length-Value.indexOf('.')-1;
    }

    if (isNaN(S) || (DP > DecimalPlaces) || (DecimalPlaces == 0 && LastChar == '.')) { // trim the last char
      S = Input.value;
      Input.value = S.substring(0,S.length-1);
    } else {
      Input.style.backgroundColor = clEditedColour;
    }
  }

  var clEditedColour      = 'darkorange';
  var clProcessingColour  = 'royalblue';
  var clOKColour          = 'lightgreen';
  var clNeedActionColour  = 'orange';
  var clDefaultBackGround = 'white';

  function ejc_PropertyInputOnChange(Input, OnSucess, BeforeUpdate, CheckedValue, UncheckedValue) {
    // new version handles all datatype based on the input type
    var InputType = Input.type;
    if (BeforeUpdate != null) {
      if (!BeforeUpdate(Input)) {return false;}
    }
    // auto set seleted to and edited background
//    if (OnSucess == null) {
//      OnSucess = eJIF_UpdateFormFromAjax;
//    }
    // code for setting the background vlaues etc!
    if (InputType.indexOf('select') == 0) {
      Input.style.backgroundColor = clEditedColour;
    }
    if (InputType == 'checkbox') {
      if (CheckedValue == null) {CheckedValue = 'Y';}
      if (UncheckedValue == null) {UncheckedValue = 'N';}
      if (Input.checked) {
        Input.value = CheckedValue;
      } else {
        Input.value = UncheckedValue;
      }
    }
    if (Input.style.backgroundColor == clEditedColour || InputType == 'checkbox') {
      AjaxLib_SetProperty(Input, OnSucess);
    }
  }

  function eJIF_NumericInputOnChange(Input, ProcessFunction) {
    if (Input.style.backgroundColor == clEditedColour) {
      ProcessFunction(Input);
    }
  }

  function eJIF_DeleteRecordBtnOnClick(Button, Description, ProcessFunction) {
    if (confirm('Do you want to delete this '+Description)) {
      ProcessFunction(Button);
    }
  }

  function eJIF_SetVisibilityByID(ID, Visible) {
    var el = document.getElementById(ID);
    if (el != null) {
      if (Visible) {
        el.style.display = 'block';
      } else {
        el.style.display = 'none';
      }
    }
  }

  function eJIF_GetVisibilityByID(ID) {
    var el = document.getElementById(ID);
    if (el != null) {
       return el.style.display != 'none';
    }
  }


  function eJIF_SetColourByID(ID, Type, Colour) {
    var el = document.getElementById(ID);
    if (el != null) {
      if (Type == 'background') {
        el.style.backgroundColor = Colour;
      }
    }
  }

  function ShowErrorByID(ID, Error) {
    alert(Error);
  }

  function eJIF_DeleteTableRowByID(RowID) {
    var Row = document.getElementById(RowID);
    if (Row != null) {
      var Table = Row.parentNode;
      if (Table.nodeName != 'TABLE') {
        Table = Table.parentNode;
      }
//      alert(Table.nodeName);
      if (Table != null) {
        Table.deleteRow(Row.rowIndex);
      }
    }
  }

// property and methods

  function ejc_CallMethod(Input, BeforeCall, OnSucess, OnTimeOut, Caption) {
    if (BeforeCall) {
      if (!BeforeCall(Input)) {return false;}
    }
    AjaxLib_CallMethod(Input, null, OnSucess, OnTimeOut, Caption);
  }

  function ejc_CallMethodPrompted(Input, OnSucess, OnTimeOut, Caption) {
    if (window.confirm('Are you sure you want to '+Caption+'?')) {
      AjaxLib_CallMethod(Input, null, OnSucess, OnTimeOut, Caption);
    }
  }

  function eJIF_DatePropertyInputOnChange(Input, OnSucess, BeforeUpdate) {
    if (BeforeUpdate != null) {
      if (!BeforeUpdate(Input)) {return false;}
    }
    Input.style.backgroundColor = clEditedColour;
    AjaxLib_SetProperty(Input, OnSucess);
  }


  // This should be renamed eJIF_PropertyInputOnChange
  function eJIF_TextPropertyInputOnChange(Input, OnSucess, BeforeUpdate) {
    if (BeforeUpdate != null) {
      if (!BeforeUpdate(Input)) {return false;}
    }
    // used for selectors as well
    if (Input.type.indexOf('select') == 0) {
      Input.style.backgroundColor = clEditedColour;
    }
    if (Input.style.backgroundColor == clEditedColour) {
      AjaxLib_SetProperty(Input, OnSucess);
    }
  }

  function eJIF_PropertyInputOnBlur(Input, BeforeUpdate) {
    if (BeforeUpdate != null) {
      if (!BeforeUpdate(Input)) {return false;}
    }
    if (Input.style.backgroundColor == clEditedColour) {
      AjaxLib_SetProperty(Input);
    }
  }


  function eJIF_TextPropertyInputKeyUp(event, Input) {
    if (event.keyCode == 13) {
      if (Input.type != 'textarea') {
        eJIF_TextPropertyInputOnChange(Input);
      }
      return false;
    }
    if (event.keyCode == 9 || event.keyCode == 16) { // tab and back tab
      return true;
    }
    Input.style.backgroundColor = clEditedColour;
  }

  function ejc_NumericPropertyInputKeyDown(Event, Input, DecimalPlaces) {
    // only allow 0..9 - and . if DecimalPlaces > 0
    var Result = false;
    var KeyCode = Event.keyCode;
    Result = (KeyCode >= 48 && KeyCode <= 57) || (KeyCode >= 96 && KeyCode <= 105) || (KeyCode == 189);
    if (!Result && (DecimalPlaces > 0)) {
      Result = (KeyCode == 190) && (Input.value.indexOf('.') < 0);
    }
    Result = Result || ejc_CursorKey(KeyCode) || ejc_EditingKey(KeyCode);
    return Result;
  }

  function ejc_NumericPropertyInputOnChange(Input, OnSucess, BeforeUpdate) {
    if (Input.style.backgroundColor == clEditedColour) {
      if (BeforeUpdate != null) {
        if (!BeforeUpdate(Input)) {return false;}
      }
      AjaxLib_SetProperty(Input, OnSucess);
    }
  }

  function ejc_NumericPropertyInputKeyUp(event, Input, DecimalPlaces, OnSucess, BeforeUpdate) {

    var KeyCode = event.keyCode;
    var Value = Input.value;
    var OldValue = Value;
    var i;

    if (KeyCode == 13) {
      // ejc_NumericPropertyInputOnChange(Input, OnSucess, BeforeUpdate);
      if (Input.onchange) {
        Input.onchange();
      }
      return false;
    }

    if (!ejc_NumericPropertyInputKeyDown(event, Input, DecimalPlaces)) {
      return false;
    }

    // if decimal pressed trim digits and remove following dec pts

    if (KeyCode == 190) {
      i = Value.indexOf('.');
      if (i != Value.lastIndexOf('.')) {
        Value = Value.substr(0, i)+'.'+Value.replace('.','').substring(i);
      }
    }

    // Check the decimal places

    if ((i = Value.indexOf('.')) >= 0) {
      if (i+DecimalPlaces+2 < Value.length) {
        Value = Value.substr(0, i+DecimalPlaces+1);
      }
    }

    if (parseFloat(Value) != parseFloat(OldValue)) {
      Input.value = Value;
      Input.style.backgroundColor = clEditedColour;
    } else {
      if (!ejc_CursorKey(KeyCode)) {
        Input.style.backgroundColor = clEditedColour;
      }
    }

    return true;

    // old code
    var BackspaceDel = (event.keyCode == 8 || event.keyCode == 46);
    if (event.keyCode == 13) {
      eJIF_NumericPropertyInputOnChange(Input, OnSucess, BeforeUpdate);
      return false;
    }


    if (event.keyCode == 16 || event.keyCode == 9) { // tab and back tab, backspace pick up on the onchange
      return true
    }
    var Value = Input.value;
    if  (Value == '.' && DecimalPlaces > 0) {Value = '0';} // allow decimal transition
    var LastChar = Value.substring(Value.length-1,Value.length);
    var PrevValue = Value.substring(0,Value.length-1);
    var S = parseFloat(Value);
    if (Value == '' || Value == '-') {S = 0.0;}

    var DP = 0;
    if (Value.indexOf('.') >= 0) {
      DP = Value.length-Value.indexOf('.')-1;
    }

    if (Value != '' && (isNaN(S) || (DP > DecimalPlaces) || (DecimalPlaces == 0 && LastChar == '.'))) { // trim the last char
      Input.value = PrevValue;
    }
    if (Input.value != PrevValue || BackspaceDel) {Input.style.backgroundColor = clEditedColour;}

  }

  function eJIF_UpdateFormFromAjax(Input, XMLDoc) {
    // get the update values
    if (Input && Input.style.backgroundColor == clProcessingColour) {
      Input.style.backgroundColor = clOKColour;
    }
    var Attr;
    var id;
    var value;
    var Elements = XMLDoc.getElementsByTagName('update');
//    alert('Updating '+Elements.length+' elements');
//    alert(XMLDoc);
    for (var i=0; i<Elements.length; i++) {
      try {
        Attr = Elements[i].attributes;
        var classname = Attr.getNamedItem('class').value;
        var oid = Attr.getNamedItem('oid').value;
        var property = Attr.getNamedItem('property').value;
        var value = Attr.getNamedItem('value').value;
        id = classname+'['+oid+'].'+property;
        ejc_SetValueByID(id, value);
      } catch(Error) {
        // add debug code here
      }
    }
  }

  function ejc_ShowErrorsFromAjax(XMLDoc) {
    // show a dialog and set the inputs background errored
    var Attr;
    var id;
    var error;
    var message = null;
    var Elements = XMLDoc.getElementsByTagName('error');
    for (var i=0; i<Elements.length; i++) {
      try {
        Attr = Elements[i].attributes;
        var classname = Attr.getNamedItem('class').value;
        var oid = Attr.getNamedItem('oid').value;
        var property = Attr.getNamedItem('property').value;
        var error = Attr.getNamedItem('value').value;
        if (message != null) {
          message = '<BR>'+error;
        } else {
          message = error;
        }
        id = classname+'['+oid+'].'+property;
        eJIF_SetColourByID(id, 'background', clNeedActionColour);
      } catch(Error) {
        // add debug code here
      }
    }
    if (message != null) {
      window.top.eJIF_ModalMessage('Error', message, null);
    }
    return (i > 0);
  }


  function eJIF_TotalElements(TagName, Class, Property) {
    var Result = 0.0;
    var Elements = document.getElementsByTagName(TagName);
    for (var I=0; I<Elements.length; I++) {
      var Details = new AjaxLib_TInputDetail(Elements[I]);
      if (Details.Class == Class) {
        if (Details.Property == Property) {
          var fv = parseFloat(Elements[I].value);
          if (!isNaN(fv)) {
            Result += fv;
          }
        }
      }
    }
    return Result;
  }

  function eJIF_Round(Value, DP) {
//    alert(String(Value));
    var Mult = 1;
    for (var I=0; I < DP; I++) {
      Mult = Mult*10;
    }
    Value = Math.round(Value*Mult);
    Value = String(Value);
    // Insert the decimal place
    Value = Value.substr(0,Value.length-DP)+'.'+Value.substr(Value.length-DP,2);
    return Value;
  }

  function eJIF_FormatNumeric(Value, DP) {
    return eJIF_Round(Value, DP);
  }

  function eJIF_GetAbsPostion(element) {
    var r = { x: element.offsetLeft, y: element.offsetTop};
    if (element.offsetParent) {
      var tmp = eJIF_GetAbsPostion(element.offsetParent);
      r.x += tmp.x;
      r.y += tmp.y;
    }
    return r;
  }

  function  eJIF_PleaseWait(Message) {
    window.top.eJIF_ModalMessage('Please wait..', Message);
  }

  function eJIF_Confirm(Message) {
    return window.confirm(Message);
  }

  function ejc_MethodInputKeyUp(event, Input, OnSucess) {
    if (event.keyCode == 13) {
      if (Input.type != 'textarea') {
        ejc_MethodInputOnChange(Input, OnSucess);
      }
      return false;
    }
    if (event.keyCode == 9 || event.keyCode == 16) { // tab and back tab
      return true;
    }
    Input.style.backgroundColor = clEditedColour;
  }

  function ejc_MethodInputOnChange(Input, OnSucess, BeforeUpdate) {
    if (BeforeUpdate != null) {
      if (!BeforeUpdate(Input)) {return false;}
    }
    if (Input.type.indexOf('select') == 0) {
      Input.style.backgroundColor = clEditedColour;
    }
    if (Input.style.backgroundColor == clEditedColour) {
      AjaxLib_CallMethod(Input, null, OnSucess);
    }
  }


/* ###########################
   Cookie Management
   ############################ */

  function ejc_GetCookie(Name) {
    var Result = null;
    var Cookie = document.cookie;
    if (Cookie == null) {
      return Result;
    }
    var NameVals = Cookie.split('; ');
    for (i = 0; i <= NameVals.length; i++) {
      if (NameVals[i] != null) {
        Pair = NameVals[i].split('=');
        if (Pair != null && Pair[0] == Name) {
          Result = Pair[1];
          break;
        }
      }
    }
    if (Result) {Result = unescape(Result);}
    return Result;
  }

  function ejc_SetCookie(Name, Value, DaysLife) {
    var Expires = "";
    if (DaysLife) {
      var ExpDate = new Date();
      ExpDate.setTime(ExpDate.getTime()+(DaysLife*24*60*60*1000));
      Expires = "; expires="+ExpDate.toGMTString();
    }
    Value = escape(Value);
    document.cookie = Name+"="+Value+Expires+"; path=/";
  }

