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

  function getElement(idname){
    return document.getElementById(idname);
  }
    
      
  function isset(variable){
    if(typeof(variable) == 'undefined')
      return false;
    return true;
  }

  function drawFlyout(fromcontrol,newcontrol,xoffset,yoffset,orientation){
    //record in tcs object
    tcs.flyouts.push(fromcontrol);
    
    //create new element if it doesnt exist
    if(!isset(yoffset))
      var yoffset = -2;
    if(!isset(xoffset))
      var xoffset = 1;
    if(!isset(orientation))
      var orientation = 'left';
      
    var el = document.getElementById(fromcontrol+'flyout');
    if(!el){
      var el = document.createElement('div');
      el.style.position = 'absolute';
      el.style.overflow = 'auto';
      el.style.zIndex = '10';
      el.id = fromcontrol+'flyout';
      document.body.appendChild(el);
    }
    el.style.visibility = 'visible';
    el.innerHTML = newcontrol;
    
    //position el from the fromcontrol
    var from = document.getElementById(fromcontrol);
    var frompos = getAbsolutePosition(from);
    
    el.style.top = (from.offsetHeight+frompos.y+yoffset)+'px';
    if(orientation == 'left')
      el.style.left = (frompos.x+xoffset)+'px';
    else
      el.style.left = (frompos.x+from.offsetWidth-(el.offsetWidth+xoffset))+'px';

  }

  function hideFlyout(fromcontrol,keepcontent){
    var el = document.getElementById(fromcontrol+'flyout');
    if(el){
      //if(!keepcontent)
      //  el.innerHTML = '';
      el.style.visibility = 'hidden';
    }
  }
 
  function hideAllFlyouts(){
    if(tcs.flyouts.length > 0){
      for(var i=0; i<tcs.flyouts.length; i++){
        hideFlyout(tcs.flyouts[i]);
      }
    }
    tcs.flyouts = [];
  }
  
  function turnOffTabs(){
    if(tcs.tabs.length > 0){
      for(var i=0; i<tcs.tabs.length; i++){
        var tab = document.getElementById(tcs.tabs[i]);
	tab.style.backgroundColor = '#ffffff';
	tab.style.color = '#000000';
      }
    }
    tcs.tabs = [];
  }
  
  function turnTabOn(el){
    tcs.tabs.push(el);
    var tab = document.getElementById(el);
    tab.style.backgroundColor = '#'+tcs.colors.bright;
    tab.style.color = '#ffffff';
  }
  
  function checkLoginFields(){
    blockOutControl('loginformoflife','Loading...');
    var fields = {
      user:document.getElementById('loginuser'),
      pass:document.getElementById('loginpass')};
    gatewayRequest('authenticate','&user='+md5(fields.user.value)+'&pass='+md5(fields.pass.value),'handleAuthenticateResponse');
  }
  
  function handleAuthenticateResponse(result){
    if(result.result.authenticated){
      document.location.href = '/';
    }
    else{
      hideBlockOut();
      document.getElementById('loginmsg').innerHTML = '<b>Incorrect username or password.</b>';
    }
  }

  function drawFeedback(el){
    hideAllFlyouts();
    turnOffTabs();
    turnTabOn(el);

    var user = (wazzle) ? '':'<tr><td align="right">Email:</td><td><input style="width:97%" type="text" name="email"></td></tr>';
    var ctrl = '<div id="feedbackformoflife" style="padding:5px; border: 1px solid #'+tcs.colors.bright+'; background-color:#'+tcs.colors.bgrey+';">'+
      '<form method="POST" action="/">'+
      '<table>'+user+
      '<tr><td colspan="2" align="left">Description of problem/feature request/criticism:</td></tr>'+
	    '<tr valign="top"><td colspan="2"><textarea style="width:300px; height:200px;" id="feedback" name="feedback"></textarea></td></tr>'+
	    '<tr><td align="right" colspan="2"><input type="button" name="cancel" onclick="hideAllFlyouts(); turnOffTabs();" value="Cancel">&nbsp;<input type="submit" name="sendfeedback" value="Send Feedback"></td></tr>'+
	    '</table></form></div>';
    drawFlyout(el,ctrl,0,-2,'right');
    document.getElementById('feedback').focus();
  }
  
  function drawLogin(el){
    hideAllFlyouts();
    turnOffTabs();

    turnTabOn(el);
    var ctrl = '<div id="loginformoflife" style="padding:5px; border: 1px solid #'+tcs.colors.bright+'; background-color:#'+tcs.colors.bgrey+';">'+
      '<form method="POST" onsubmit="return false;" action="/login">'+
        '<table><tr><td colspan="2" id="loginmsg"></td></tr><tr id="loginuserrow"><td align="right">Username:</td><td><input id="loginuser" type="text" name="username"></td></tr>'+
	 '<tr id="loginpassrow"><td align="right">Password:</td><td><input id="loginpass" type="password" name="password"></td></tr>'+
	 '<tr><td colspan="2" align="right"><input type="button" name="cancel" onclick="hideAllFlyouts(); turnOffTabs();" value="Cancel">&nbsp;'+
   '<input type="submit" onclick="checkLoginFields();" name="Login" value="Login"></td></tr>'+
   '<tr><td colspan="2"><a href="#" onclick="drawForgotPassword();">Forgot your password? <span style="text-decoration:underline;">Click here</a>.</a></td></tr>'+
	 '</table></form></div>';
    drawFlyout(el,ctrl,-50,-2,'right');
    document.getElementById('loginuser').focus();
  }

  function checkForgotFields(){
    blockOutControl('loginformoflife','Loading...');
    var email = document.getElementById('forgotemail').value.trim();
    var email = (email != '') ? '&email='+md5(email):'';
    gatewayRequest('forgotpassword',email,'forgotCallback');
  }
  
  function forgotCallback(result){
    hideBlockOut();
    if(result.rcode == 1){
      document.getElementById('loginformoflife').innerHTML = '<table><tr><td><b>'+result.rmsg+'</b></td></tr><tr><td align="right"><input type="button" name="cancel" onclick="hideAllFlyouts(); turnOffTabs();" value="Close"></td></tr></table>';
    }
    else{
      document.getElementById('forgotmsg').innerHTML = '<b>'+result.rmsg+'</b>';
    }
  }
  
  function drawForgotPassword(){
    var lf = document.getElementById('loginformoflife');
    lf.innerHTML = '<form method="POST" onsubmit="return false;">'+
        '<table><tr><td colspan="2" id="forgotmsg"></td></tr><tr id="forgotemailrow"><td align="right">Email:</td><td><input id="forgotemail" type="text" name="email"></td></tr>'+
	 '<tr><td colspan="2" align="right"><input type="button" name="cancel" onclick="hideAllFlyouts(); turnOffTabs();" value="Cancel">&nbsp;'+
   '<input type="submit" onclick="checkForgotFields();" name="Go" value="Go"></td></tr>'+
	 '</table></form>';
	 document.getElementById('forgotemail').focus();
  }
  
  String.prototype.trim = function(){ return this.replace( /^\s+¦\s+$/g, "") }
  
  function checkRegFields(){
    var fields = ['user','email','pass','eula'];
    var wrong = false;
    for(var f=0; f<fields.length; f++){
      var c = document.getElementById('register'+fields[f]);
      var r = document.getElementById('register'+fields[f]+'row');
      if(c.value.trim() == '' || (fields[f] == 'eula' && !c.checked)){
        r.style.backgroundColor = '#'+tcs.colors.bright;
	wrong = true;
      }
    }
    if(wrong){
      document.getElementById('regmsg').innerHTML = '<b>The highlighted fields are required.</b>';
    }
    else{
      //make ajax request to check if user and email are unique
      var user = document.getElementById('registeruser');
      var email = document.getElementById('registeremail'); 
      blockOutControl('regformoflife','Loading...');  
      gatewayRequest('checkregistration','&user='+user.value+'&email='+email.value,'displayRegCheck');
    }
  }
 
  var blockouts = {};
  function blockOutControl(control,text){
    if(!blockouts[control]){
      var t = document.createElement('div');
      t.id = control+'-blockout';
      t.setAttribute('id',control+'-blockout');
      t.className = 'blockout';
      t.setAttribute('class','blockout');
      document.body.appendChild(t);
      blockouts[control] = t;
    }

    var b = blockouts[control];
    var c = document.getElementById(control);
    var pos = getAbsolutePosition(c);
    with(b.style){
      left = pos.x+'px';
      top = pos.y+'px';
      width = c.offsetWidth+'px';
      height = c.offsetHeight+'px';
      visibility = 'visible';
    }

    if(text)
      b.innerHTML = '<div style="padding:.5em;">'+text+'</div>';
  }

  function hideBlockOut(control){
    var blist = {};
    
    if(control)
      blist[control] = blockouts[control];
    else 
      blist = blockouts;
   
    for(var b in blist){
      var b = blist[b];
      with(b.style){
        left = '0px'; 
        top = '0px';
        width = '0px';
        height = '0px';
        visibility = 'hidden';
      }
    }
  }
  
  function displayRegCheck(result){
    hideBlockOut();
    var msg = false;
    result = result.result;
    if(result.emailexists){
      msg = 'That email is in use.';
    }
    if(result.userexists){
      msg = 'That username is in use.';
    }
    if(result.userexists && result.emailexists){
      msg = 'That email and username are in use.';
    }
    if(msg){
      document.getElementById('regmsg').innerHTML = '<b>'+msg+'</b>';
    }
    else{
      document.getElementById('regformoflifeform').submit();
    }
  }

  function checkFieldFull(field){
    var c = document.getElementById('register'+field);
    var r = document.getElementById('register'+field+'row');
    if(c.value.trim() != '' || (field == 'eula' && c.checked)){
      r.style.backgroundColor = 'inherit';
    }
  }
  
  function drawRegister(el){
    hideAllFlyouts();
    turnOffTabs();

    turnTabOn(el);
    var ctrl = '<div id="regformoflife" style="padding:0px; border: 1px solid #'+tcs.colors.bright+'; background-color:#'+tcs.colors.bgrey+';">'+
      '<form method="POST" id="regformoflifeform" action="/register">'+
        '<table cellpadding="3" cellspacing="0"><tr><td colspan="2" id="regmsg"></td></tr><tr id="registeruserrow"><td align="right">Username:</td><td><input type="text" id="registeruser" onkeyup="checkFieldFull(\'user\');" name="username"></td></tr>'+
         '<tr id="registeremailrow"><td align="right">Email:</td><td><input type="text" id="registeremail" onkeyup="checkFieldFull(\'email\');" name="email"></td></tr>'+
	 '<tr id="registerpassrow"><td align="right">Password:</td><td><input type="password" id="registerpass" onkeyup="checkFieldFull(\'pass\');"  name="password"></td></tr>'+
	 '<tr id="registereularow"><td align="right" colspan="2"><small>I have read/agree with the <a href="/TOU" style="text-decoration:underline;">terms of use</a>:&nbsp;<input type="checkbox" id="registereula" onmouseup="checkFieldFull(\'eula\');"  name="eula"></td></tr>'+
	 '<tr><td colspan="2" align="right"><input type="button" name="cancel" onclick="hideAllFlyouts(); turnOffTabs();" value="Cancel">&nbsp;<input type="button" name="register" onclick="checkRegFields();" value="Register"></td></tr>'+
	 '</table></form></div>';
    drawFlyout(el,ctrl,-33,-2,'right');
    document.getElementById('registeruser').focus();
  }
    var gateway = 'http://www.thecollectionspace.com/server.php';

    function dmsg(msg){
      var ddata = document.getElementById('ddata');
      if(ddata){
        if(typeof msg == 'object')
          msg = msg.toSource();
        var ctime = new Date();
        ddata.value += ctime.getTime()+': '+msg+'\\n\\n';
        ddata.scrollTop = ddata.scrollHeight;
      }
    }

    function gatewayRequest(method,data,callback){
     ajaxRequest(
       gateway,
       'POST',
       'method='+method+data,
       callback);
   }

   var jsdebug = false;
   function ajaxRequest(url,mode,data,callback){
     var xmlHttp;
     dmsg('Ajax request to '+url+'?'+data+'. Callback: '+callback);

     if(jsdebug)
       alert(data);
     try {xmlHttp = new XMLHttpRequest();}
       catch(e) {try {xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");}
         catch(e) {try {xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");}
           catch(e) {alert('Requires ajax compatibility'); return false;}}}
     xmlHttp.onreadystatechange = function(){
       if(xmlHttp.readyState==4){

         //call callback
         dmsg(xmlHttp.responseText);
         dmsg('Status: '+xmlHttp.status);
         if(jsdebug)
           alert(xmlHttp.responseText);
         var result;
         try{eval('result = '+xmlHttp.responseText);}
           catch(e){result = false;}

         eval(callback+'(result);');
       }
       else{
        dmsg('Waiting for reply. ready state: '+xmlHttp.readyState);
       }
     }
     try{
       dmsg('Attempting to send request');
       xmlHttp.open(mode,url,true);
       xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
       dmsg('Connection open');
       dmsg('Header set');
       xmlHttp.send(data);
       dmsg('Request sent');
     }
     catch(e){
       dmsg('Error on request');
       dmsg(e.toSource());
       return false;
     }
   }


