// Info.js
//
// 03.07.09 Ver & \1
var IE,Ver,Cookies,
MemId,  // /- set by Boot call
LoginN, // |
Email,  // |
GName,  // |
Name,   // |
RRTime = 15000, // timeout time on a Req/Rec (Ajax) call
DatReq, // Data exchange request
eBtnsA=[],// Array of EE std Buttons
El,     // global element for input check fns
moomenu = { // Menu
  initialize: function(nav) {
    nav.getElements('li').each(function(el) {
      if (el.getElement('ul')) {  // has descendant ul element
        el.addEvents({
          'mouseenter':this.enter.bind(this,el),
          'mouseleave':this.leave.bind(this,el)
        })
      }
    }, this)
  },
  enter:function(el){
    $clear(el.sfTi);
    var ud
    if ((ud = el.getElement('ul'))) {  // first descendant ul element
      if (!el.hasClass('sfHover')) {
        el.addClass('sfHover');
        var w = ud.getStyle('width'), h = ud.getStyle('height');
        ['opacity','width','height'].each(function (prop) {ud.setStyle(prop,0)})
        ud.get('morph').start({opacity:1,width:w,height:h});
      }
    }
  },
  leave:function(el){
    el.sfTi = (function(){
    el.removeClass('sfHover');
    }).delay(500);
  }
},
Site = {
  Start:function() {
    IE = Browser.Engine.name == 'trident'
    var t
    if ((t=$('nav')))
      moomenu.initialize(t)
    $('HdrCtr').removeClass('hide') // make hdr centre td (Book flash & MI) visible
    Ver = (Ver=$(document.head).getElement('meta')).get('name') == 'EEver' ? Ver.get('content') : ''
    // Test for Cookies
    CreateCookie('T', 1, 1)
    if ((Cookies = (document.cookie.contains('T=') ? 1:0)))
      EraseCookie('T')
    // Server Data exchange request
    DatReq = new Request({
      onSuccess: function(d) {Rec(d)} // ignore failure
    });
    if (self.Init)
      Init()
    else
      Boot()
  }
}

function Boot(m) {
  Req('i', ''+screen.width + screen.height + '\x01' + ((new Date()).getTimezoneOffset()) + '\x01' + escape(document.referrer) + '\x01' + Ver  + '\x01' + Cookies, m? location.href : 'http://www.tariinfo.com/srv/Boot.htm', BootRec)
}

function BootRec() {
  SetMI()
  if (self.Done)
    Done()
}

// Set Member Info
function SetMI() {
  var t, dfsA = DatReq.dfsA
  // Have in Dat
  // MemId | LoginN | Email | GName | Name
  //   0       1        2       3      4
  MemId  = +dfsA[0]
  LoginN = +dfsA[1]
  Email  =  dfsA[2]
  GName  =  dfsA[3]
  Name   =  dfsA[4]
  DatReq.e = 5 // next dfsA
  ShowMI()
}

function ShowMI() {
  switch (LoginN) {
    case 0: t = "Subscribe to <a href='/pub/TNews.htm' title='Subscribe to TARI News - It is Free.'><b>TARI News</b></a> to stay informed about TARI"; break
    default:t = "Hello <b>" + GName + "</b>. <span class='f10'>(<a href='#' onclick='return ZapCookie()' title='Zap Cookie'>Click here</a> if you are not " + Name +'.)</span>'; break
  }
  $('MI').set('html', t)
}

function ZapCookie() {
  EraseCookie('L')
  LoginN = MemId = 0
  ShowMI()
  if (self.ZapCookieCB)
    ZapCookieCB()
  return false
}

// Req/Rec
// -------
// op  = 1 char op code
// dat = the data if any being sent
// up  = url to post to, default = module .php
// fn  = call back fn, default = Done
function Req(op,dat,up,fn) {
  if (!DatReq.op) {
    DatReq.op=op
    DatReq.cbfn = (fn ? fn : Done)
    var d = 'Dat=' + op + (dat ? dat : ''), u = (up ? up : location.href).replace(/\/pub\//, '/srv/').replace(/\.htm/, '.php')
    DatReq.send({url:u,data:d})
    DisableButtons()
    DatReq.RRTO=NoRec.delay(RRTime)
  }
}

function Rec(d) {
  $clear(DatReq.RRTO)
  if (DatReq.op) {
    DatReq.dfsA = d.split('\x01')
    var r = +DatReq.dfsA.pop(),
    sesId =  DatReq.dfsA.pop()
    CreateCookie('L', sesId, 365*24)
    if (r < 0) { // Error
      switch (r) {
        case -1: // NOT_LOGGEDIN
          ZapCookie()
          break
        case -2: // NOP_LOCK op not able to be performed because of lock
          Error("Sorry, the operation you attempted could not be performed because Site Maintemace is in progress.\nPlease try again in a while.")
          break
        default: // Any other error
          Error('Sorry, an error (code number ' + r + ') has occurred, and been reported to Auchinlea for correction. Please try again later.')
      }
    }else{ // r >= 0
      DatReq.e = 0
      DatReq.r = r
      DatReq.cbfn()
      RRcleanup()
    }
  }
}

function RRcleanup() {
  $clear(DatReq.RRTO)
  DatReq.op = 0
  if (self.After)
    After()
}
// Disable all e buttons
function DisableButtons() {
  eBtnsA.each(function(e){e.addClass('btnGrey')})
}

// Enable e buttons
function EnableButtons() {
  eBtnsA.each(function(e){e.removeClass('btnGrey')})
}

function NoRec() {
  //Error('Sorry there has been no response from the server for 15 seconds, which probably indicates an error, possibly a //communication failure.\nPlease try again.')
}

function Error(m) {
  RRcleanup()
  alert(m)
}

function CreateCookie(name,value,hours) {
  var date = new Date()
  date.setTime(date.getTime()+hours*60*60*1000)
  document.cookie = name + "=" + value + "; expires="+date.toGMTString() + "; path=/"
}

function EraseCookie(name) {
  CreateCookie(name,"",-24)
}

// Input checking functions
// Returns true on fails with input el of 1st one to fail in El
function ChkRet(e, r) {
  if (r && !El) El=e
  return r
}

function NoGo(msg) {
  El.focus()
  El=0
  alert(msg+'.')
  return false
}

// check length of text field. Returns true if fails with input el in El
function ChTxt(e, l) {
  return ChkRet(e, e.value.length < l)
}

function ChEmail(e) {
  return ChkRet(e,!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(e.value))
}

// Form onkeydown fn to process Tab or Enter
function tekd(evt, goFn, nxt) {
  var k = IE ? evt.keyCode : evt.which
  if (k==9 || k == 13) {
    // process or Enter
    if (goFn)
      goFn()
    else
      nxt.focus()
    return false
  }
  return true
}

window.addEvent('domready', Site.Start)
