var gScopa = {

  table: null,

  onload: function() {
    this.patchLinks();
    this.setupTable();
  },


  newGame: function(link) {
    if(gGame.data && gGame.data.gameId && !confirm(_['msg.abandon'])) return false;
    return this.play(link);
  },

  play: function(teaserContainer) {
    try {
      gGame.reset();
      gGame.refresh('new', teaserContainer || null);
    } finally {
      return true;
    }
  },

  tableReady: false,
  setupTable: function() {

    //gScopa.flare();
    this.table = $("table");
    this.table.style.visibility = "visible";

    if(!(gGame.playing || location.search)) {
      window.setTimeout(function() { gScopa.showCards(); }, 200);
    } else {
      //document.documentElement.scrollTop = 400;
     // document.body.scrollTop = 400;
      gGame.update();
    }
    this.tableReady = true;
  },

  patchLinks: function() {
    var aa = document.getElementsByTagName("a");
    var a, c;
    for(var j = aa.length; j-- > 0;) {
      a = aa[j];
      c = a.className;
      if(/\bclose\b/.test(c)) {
        a.onclick = function() { gScopa.closeBox(this); return false; }
      }
    }
  },

  cards: null,
  preload: function() {

    this.cards = CardsDeck.create("table", null, function() { gScopa.onload() });
    this.cards.preload("img/bg.jpg", "img/logo-flare.jpg");

    var w, h;
    if(self.innerHeight) {
      w = self.innerWidth;
      h = self.innerHeight;
    } else if(document.documentElement && document.documentElement.clientHeight) {
      w = document.documentElement.clientWidth;
      h = document.documentElement.clientHeight;
    }
    else if(document.body) {
      w = document.body.clientWidth;
      h = document.body.clientHeight;
    }

    var dw = Math.max(700 - w, 0);
    var dh = Math.max(400 - h, 0);
    window.resizeBy(dw, dh);
    if(dw || dh) window.moveTo(0, 0);
  },

  showCard: function(n, x, y) {
   this.cards.show(n, x, y);
  },
  hideCard: function(n) {
    this.cards.hide(n);
  },

  cardW: 0,
  cardH: 0,


  showCount: 0,
  showAccel: 10,
  showCards: function() {
    var t = this.table;
    var w = t.offsetWidth - 8;
    var h = t.offsetHeight - 8;
    var a = Math.PI * this.showCount / 800;
    this.showAccel = Math.max(Math.cos(a) * 10, 2);
    this.showCount += this.showAccel;
    var cn = Math.ceil(this.showCount / 10);
    if(cn > 40) cn = 40;


    var c = this.cards[cn];

    var d = c.getDimensions();

    var cw = d.width;
    var ch = d.height;
    a = Math.PI + (Math.PI * 38 / 40) * this.showCount / 200;
    var halfW = w / 2;
    var halfCW = cw / 2;
    var halfH = h / 2;
    var halfCH = ch / 2;

    var x = Math.floor(halfW - halfCW + Math.cos(a) * (halfW - halfCH)); // + halfCW);
    var y = Math.floor(halfH - halfCH + Math.sin(a) * (halfH - halfCH)) // + halfCH);
    if(c.style.visibility == "hidden") {
      this.showCard(cn, x, y);
    }

    if(cn < 40) {
      this.showCard(0, x, y);
      var st =  Math.ceil(this.showCount);
      //document.documentElement.scrollTop = st;
      //document.body.scrollTop = st;
    } else {
      this.hideCard(0);
      this.showCard(cn, x, y);
    }

    if(this.showCount < 399) {
      window.setTimeout(function() { gScopa.showCards(); }, 20);
    } else {
      IAFlashes.startFlash("play-button");
    }
  },

  debugOn: false,
  debug: function(msg) {
    if(!this.debugOn) return;
    var d = document.getElementById("debug");
    d.style.display = "block";
    d.innerHTML += msg + "<br />";
  },


  grabBox: function(node) {
     box = $(node);
     while(box && !Element.hasClassName(box,"box")) box = box.parentNode;
     return box;
  },
  openBox: function(node, content) {

    var box = this.grabBox(node);
    if(!box) return;
    cb = new Selector(".box-content").findElements(box).first();
    if(cb) {
      if(content) {
        cb.innerHTML = content;
      } else {
        content = cb.innerHTML;
      }
      if(content.indexOf('"error"') > -1) Element.addClassName(box, "error");
      else Element.removeClassName(box, "error");
    }
    new Effect.Appear(this.grabBox(node), { queue: { scope: "box-" + node.id } });
  },
  closeBox: function(node) {
    new Effect.Fade(this.grabBox(node), { queue: { scope: "box-" + node.id } });
  },
  toggleBox: function(node) {
    var box = this.grabBox(node);
    if(box.style.display != "block") this.openBox(box);
    else this.closeBox(box);
  },
  openHelp: function() {
    var width = Math.min(1000, window.screen.width);
    var height = Math.min(620, window.screen.height);
    var w = window.open("help.html", "scopa_help", "width=" + width + ", height=" + height + ", top=0, left=0, toolbar=0, scrollbars=1, resizable=1");
    w.focus();
    return false;
  },

  todo: function() {
    alert("Middle layer only partially working");
    return false;
  },
  flareTimeout: null,
  flare: function() {

    $("header").style.display = "block";
    new Effect.Fade("header");
    if(gScopa.flareTimeout) window.clearTimeout(gScopa.flareTimeout);
    gScopa.flareTimeout = window.setTimeout(gScopa.flare, 10000);
  },


  hype: function(msg, size) {
    var hype = $("hype");
    if(hype.visible()) {
      window.setTimeout(
        function() {
          this.hype(msg, size);
        }.bind(this), 100);
      return;
    }
    hype.style.fontSize = size || "";

    hype.descendants().each(function(h) {
      h.innerHTML = msg;
    });
    Element.show(hype);

    with(hype.style) { width = height = top = left = ""; }
    var q = { scope: 'hype', position: 'end' };

    new Effect.Appear(hype, {
      duration: 1,
      queue: q,
      afterFinish: function() {
        window.setTimeout(function() { new Effect.Fade(hype, {
        queue: q,
        afterFinish: function() {  Element.hide('hype'); } } ); }, 200);
      }
    });
  },



  // commands

  logout: function() {
    if(!confirm(_['msg.logout'])) return;
    this.login(true);
    if(ChatBox){ChatBox.cansend(false);}
  },
  login: function(isLogout) {
    if(this.loginOperation){return;}
    gScopa.loginOperation = true;
    parameters = (isLogout ? 'out=1' : Form.serialize("userform")) + "&c=user&a=login";
    $('login-indicator').show();

    new Ajax.Updater('loginbox', location.pathname, {
      onComplete: function()
      {
        gScopa.loginOperation = false;
        if(ChatBox){ChatBox.cansend(true);}
        if(gGame){gGame.updatePlayersData();}
      },
      parameters: parameters,
      evalScripts: true
    });
  },

  forgot: function() {
    Effect.BlindUp("userform", { duration: .5, afterFinish: function() {
        $$('#forgot input[type="text"]').value = "email@domain.com";
        Effect.BlindDown("forgot", { duration: .5, afterFinish: function() { Form.focusFirstElement("forgot"); } });
      }
    });
  },

  sendCredentials: function(email) {
    Effect.BlindUp("forgot", { duration: .5, afterFinish: function() {
        Effect.BlindDown("userform", { duration: .5 });
      }
    });
    if(email) {
      new Ajax.Updater('invitation', location.pathname, {
        parameters: Hash.toQueryString({ c :'user', a: 'recall', email: email }),
        evalScripts: true
      });
    }
  },

  invite: function(form) {
    var sender, addresses;
    if(form) {
      sender = form.elements.sender && form.elements.sender.value || "";
      addresses = form.elements.addresses &&  form.elements.addresses.value || "";
    }
    $('invitation').innerHTML='';

    new Ajax.Updater('invitation', location.pathname, {
        parameters: Hash.toQueryString({
          c:'user',
          a: 'invite',
          sender: sender,
          addresses: addresses,
          submit: form ? 1 : 0
        }),
        evalScripts: true
    });
  }

}

/* menu functions */
var menu_data = new Array();
function show_menu(id)
{
	if(!menu_data[id])
	{
		menu_data[id]=new Array();
	}
	if(menu_data[id]['timer'])
	{
		clearTimeout(menu_data[id]['timer']);
		menu_data[id]['timer'] = null;
	}
	menu_data.each(
		function(val, key)
		{
			if(val['timer']){hide_menu_timeout(key);}
		}
	);
	if(menu_data[id]['effect'])
	{
		menu_data[id]['effect'].cancel();
	}
	$(id).setStyle({opacity: 1});
	$(id).show();
}

function hide_menu(id)
{
	if(id){
		if(menu_data[id]['timer']=null) {
			//do nothing
		} else {
			menu_data[id]['timer'] = setTimeout("hide_menu_timeout('"+id+"')", 100);
		}
	}
}

function hide_menu_timeout(id)
{
	menu_data[id]['effect'] = new Effect.Fade(id);
	clearTimeout(menu_data[id]['timer']);
	menu_data[id]['timer'] = null;
}
/* menu functions */

gScopa.preload();

