var MODE_SIGN_IN    = "sign_in";
var MODE_QUICK_PLAY = "quick_play";
var MAX_CHILDREN = 6;

/* http://www.quirksmode.org/js/cookies.html */
function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function authenticate(email, password) {    
  $$("form#Login p.notice")[0].update("");

  new Ajax.Request("/sessions.json", {
    method: "post",
    parameters: {
      email: email,
      password: password
    },
    onSuccess: function() {
      insertGameHTML({
        mode:       MODE_SIGN_IN,
        email:      email,
        password:   password,
        sessionId:  readCookie('_deeqs_session')
      });
      set_account_bar(MODE_SIGN_IN, {username:email});
    },
    onFailure: function() {
      $$("form#Login p.notice")[0].update("Sorry, that username or password is incorrect.");
    }
  })
}

function insertGameHTML(options) {
  var TIMESTAMP = 1223996131;
  
  $('Central').update('<div id="FlashGame"><div id="FlashContent"><div class="require-flash-notice">To play the Unite the Deeqs game, you\'ll need Flash version 9.0.28 or later.<br />You can download the latest version by following the instructions at <a href="http://www.adobe.com/go/getflashplayer">Adobe.com</a>.</div></div></div>');

  var opt = {
    flashvars:{
      assetsPath:"game/"
    },
    params:{
      allowScriptAccess:"always"
    },
    attributes:{
      bgcolor:"#FFFFFF"
    }
  };

  if (options.mode == MODE_SIGN_IN) {
    opt.flashvars.email     = options.email;
    opt.flashvars.password  = options.password;
    opt.flashvars.sessionId = options.sessionId;
    opt.flashvars.signIn    = true;
  } else {
    opt.flashvars.signIn    = false;
  }

  swfobject.embedSWF("/game/Shell.swf" + "?" + TIMESTAMP, "FlashContent", "900", "500", "9.0.28", null, opt.flashvars, opt.params, opt.attributes);
}

function sign_in(event) {
	urchinTracker('/homepage-buttons/play/');
  authenticate($F('username'), $F('password')); 
  event.stop();
}
function quick_play(event) {
	urchinTracker('/homepage-buttons/quick-play/');
  insertGameHTML({ mode: MODE_QUICK_PLAY });
  set_account_bar(MODE_QUICK_PLAY);
  event.stop();
}
function sign_up(event) {
	urchinTracker('/homepage-buttons/sign-up/');
  new Ajax.Request("/sign-up", {
    method: "get",
    onSuccess: function(transport) {
      var w = overlay.create();
      w.update(transport.responseText);
      hijack_links(w);
      focus_first_form_element(w);
    }
  });
  if (event) event.stop();
}

function forgot_password(event) {
	urchinTracker('/homepage-buttons/forgot-your-password');
  new Ajax.Request("/password-reset", {
    method: "get",
    onSuccess: function(transport) {
      var w = overlay.create();
      w.update(transport.responseText);
      hijack_links(w);
      focus_first_form_element(w);
    }
  });
  event.stop();
}

function hijack_links(w, overlay) {
  /* loop through every link we loaded and re-wire it to be opened within the overlay */
  w.select('a[@href], button[@href]').each(function(link) {
    link.observe('click', function(event) {
      event.stop();
      
      if (event.target.readAttribute('href') == "#") return;
      
      if (event.target.readAttribute('href')) {
        var url = event.target.readAttribute('href');
        new Ajax.Updater(w, url, {
         method: 'GET', 
         onComplete: function(transport) { 
           w.update(transport.responseText); 
           hijack_links(w);
           focus_first_form_element(w);
         }
        });
        return;
      } else if ((event.target.type == "submit" || event.target.tagName.toLowerCase() == "button") && event.target.form) {        
        var form = event.target.form;
        var url = form.action;
        submitFormViaAjax(url, form, w, overlay);
        return;
        
      } else {
        //
      }
    })
  })
}

function submitFormViaAjax(url, form, w, overlay) {
  new Ajax.Request(url, {
   method: 'POST', 
   postBody: form.serialize(),
   onComplete: function(transport) { 
     (overlay || w).update(transport.responseText); 
     hijack_links((overlay || w));
     focus_first_form_element((overlay || w));
   }
  });  
}

function addNewChild() {
  var next_child = ($$('.add-child').length);
  hideAddNewChildButtonIfNecessary();
  new Ajax.Updater($('children'), '/child/' + next_child, {method:"get", insertion:'bottom', evalScripts:true, onComplete:function(event){
    hijack_links($('child_' + next_child +'_buttons'), overlay.create());
  }});
}

function hideAddNewChildButtonIfNecessary() {
  var next_child = ($$('.add-child').length);
  if (next_child + 1 >= MAX_CHILDREN) $$('.btn-add-child').each(Element.hide);  
}

/* Account Bar */
function set_account_bar(mode, options) {
  var content;

  if (mode == MODE_QUICK_PLAY) 
  {

    content = '<p>Now Playing in <strong>Quick Play Mode</strong> &#8212; saving is disabled.' +
              ' <a id="SignUpInvite" href="/">Sign Up</a> for more features' +
              ' and to save your games!</p>';
        
  } 
  else if (mode == MODE_SIGN_IN) 
  {

    content = '<p>'+options.username+' | <a href="/sign-out">Sign Out</a></p>';
    
  }
  
  if (content) $('AccountBar').select('.content')[0].update(content);  
}




/* focus on the first form element */
function focus_first_form_element(container) {
  if (!container) container = $$('body')[0];
  container.select('form')[0].elements[0].focus();  
}


//function glow(el, opts) {
//    if (opts && opts.fixIEBackgroundBug) {
//        try {
//          document.execCommand("BackgroundImageCache", false, true);
//        } catch(err) {}
//    }
//    var min = 0;
//    var max = 1;
//    var step = 1/15;
//    var alpha = 1;
//    var ticks = 0;

//    var target = el;
//    var currA = fadeOut;

//    function fadeIn()  {
//      alpha = alpha + step;
//      if (alpha > max) currA = fadeOut;
//    };
//    
//    function fadeOut() { 
//      alpha = alpha - step;
//      if (alpha < min) currA = fadeIn;
//    };
//        
//    function animate() {
//      ticks++;
//      currA();
//      target.setOpacity(alpha);
//    };

//    new PeriodicalExecuter(animate, 1/30);    
//};
