Event.observe(window, 'load', function(){
  if(Prototype.Browser.IE)
  {
    reloadVisitorGames();
  }
});

function reloadVisitorGames()
{
  if($("visitor_games_preloader") && $("visitor_games"))
  {
    $("visitor_games_preloader", "visitor_games").invoke('toggle');
    new Ajax.Updater({success: 'visitor_games'}, reloadMyGamesUrl, {
      evalScripts: true,
      onComplete: function() {$("visitor_games_preloader", "visitor_games").invoke('toggle');}
    });
  }
}

function triggerPlayed()
{
  if (!playedUrl) return false;

  new Ajax.Request(playedUrl, {
    method: 'get'
  });
}

function onLoaderError(debugText)
{
  var showText = (debugText) ? '<div>'+debugText+'</div>' : gameErrorUrl;
  Modalbox.show(showText, {title: '', closeString: '', onShow: function() {toggleEmbed();},
                           afterHide: function() {toggleEmbed(); },  width: 620, height: 125});
}

var selectionCountShown = false;
function toggleSelectionCount(contName)
{
  selectionCountShown = !selectionCountShown;

  $(contName+'_show_count', contName+'_hide_count').invoke("toggle");

  var node = $(contName).select('[class="gameBox2 floatLeft"]').each(function(node){
    node.down('div.additionalInfo').toggle();
  });
}

function toggleEmbed()
{
  $('wrapper').select('embed', 'object').each(function(embed){
    changeVisibility(embed);
  });
}

function changeVisibility(el)
{
  el.style.visibility = (el.style.visibility != 'hidden') ? 'hidden' : 'visible';
}

// [accid|all:]url[;[accid|all:]url]
function track(name)
{
  if(!window.urchinTracker || g_accounts.length <= 0)
    return;

  var reset_tracking = false;
  for(accid=0; accid < g_accounts.length; accid++)
  {
    real_track(name, g_accounts[accid], reset_tracking);
    reset_tracking = true;
  }
}

function real_track(url, acc, reset)
{
  if(reset)
    _uff = 0; // Reset for other account

  _userv = 2;
  _uacct = acc;
  try
  {
    urchinTracker(url);
  }
  catch (e) {}
}

function sendPass(url)
{
  if(!$('username').value)
  {
    alert(login_username_alert);
    return;
  }

  if(confirm(login_send_pw_prompt))
  {
    new Ajax.Updater('login_password_resend', url,{
      parameters: { username: $F('username') }
    });
  }
}

function getRatio(contWidth, gameWidth)
{
  return contWidth / gameWidth;
}

function sendFlashVersion(url, version)
{
  new Ajax.Request(url, { method: 'post', parameters: { flash_version: version }});
}

function sendJsEnabled(url)
{
  new Ajax.Request(url);
}

var sendComment = true;
function canSendComment()
{
  var okToSend = ($('comment_content').value.replace(/^\s+|\s+$/g, '').length > 0 && sendComment);
  return okToSend;
}

var createEntry = true;
function canCreateEntry()
{
  var okToSend = ($('entry_content').value.replace(/^\s+|\s+$/g, '').length > 0 && createEntry);
  return okToSend;
}

// hover elements
/// create toggle js class
var ToggleGameBoxBgr = Class.create({

  initialize: function(gameId, catMenuId, opacityClass, thumbId) {
    this.gameId = $(gameId);

    if(catMenuId !== null)
      this.catMenuId = catMenuId;

    if(opacityClass == true)
      this.opacityClass = false;
    else
      this.opacityClass = true;

    if(thumbId)
    {
      this.thumbId = thumbId;
      this.toggleTitleThumb = true;
    }
    else
      this.toggleTitleThumb = false;

    this.eventMouseOver = this.hoverState.bindAsEventListener(this);
    this.eventMouseOut   = this.normalState.bindAsEventListener(this)

    this.registerEvents();
  },

  registerEvents: function() {
    if(this.toggleTitleThumb == true)
    {
      Event.observe($(this.thumbId), "mouseover", this.eventMouseOver);
      Event.observe($(this.thumbId), "mouseout", this.eventMouseOut);
    }
    else
    {
      Event.observe(this.gameId, "mouseover", this.eventMouseOver);
      Event.observe(this.gameId, "mouseout", this.eventMouseOut);
    }
  },

  hoverState: function() {
    if (this.opacityClass)
      this.gameId.removeClassName('transparent_png');

    this.gameId.addClassName('whiteBgr');

    if(this.catMenuId)
      $(this.catMenuId).addClassName('whiteBgr');
  },

  normalState: function() {
    this.gameId.removeClassName('whiteBgr');

    if (this.opacityClass)
      this.gameId.addClassName('transparent_png');

    if(this.catMenuId)
      $(this.catMenuId).removeClassName('whiteBgr');
  }

});

//// create pagination class
var TogglePaginationBgr = Class.create({
  initialize: function(link, spacer) {
    this.link = $(link);
    this.spacer = $(spacer);

    this.elements = $(link, spacer);

    this.eventMouseOver = this.hoverState.bindAsEventListener(this);
    this.eventMouseOut   = this.normalState.bindAsEventListener(this)

    this.registerEvents();
  },

  registerEvents: function() {
    Event.observe(this.link, "mouseover", this.eventMouseOver);
    Event.observe(this.link, "mouseout", this.eventMouseOut);

    Event.observe(this.spacer, "mouseover", this.eventMouseOver);
    Event.observe(this.spacer, "mouseout", this.eventMouseOut);
  },

  hoverState: function() {
    this.elements.each(function(s){
      s.removeClassName('blackBgr');
      s.addClassName('whiteBgr');
    });
  },

  normalState: function() {
    this.elements.each(function(s){
      s.removeClassName('whiteBgr');
      s.addClassName('blackBgr');
    });
  }

});

var ToggleImages = Class.create({
  initialize: function(container, nm_image, in_image) {
    this.container = $(container);
    this.images = $(nm_image, in_image);

    this.eventMouseOver = this.hoverState.bindAsEventListener(this);
    this.eventMouseOut   = this.normalState.bindAsEventListener(this)

    this.registerEvents();
  },

  registerEvents: function() {
    Event.observe(this.container, "mouseover", this.eventMouseOver);
    Event.observe(this.container, "mouseout", this.eventMouseOut);
  },

  hoverState: function() {
    this.images.invoke('toggle');
  },

  normalState: function() {
    this.images.invoke('toggle');
  }

});

function blurLink(theObject)
{
  theObject.blur();
}

function Set_Cookie( name, value, expires, path, domain, secure )
{
  var today = new Date();
  today.setTime( today.getTime() );

  var expires_date = new Date( today.getTime() + (expires) );

  document.cookie = name + "=" +escape( value ) +
  ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
  ( ( path ) ? ";path=" + path : "" ) +
  ( ( domain ) ? ";domain=" + domain : "" ) +
  ( ( secure ) ? ";secure" : "" );
}

function jsUpload(upload_field, error)
{
  var re_text = /\.jpg|\.png|\.jpeg|\.gif|\.bmp/i;
  var filename = $(upload_field).value;

  if (filename.search(re_text) == -1)
  {
    $('profileImageStatus').update('<span class="error">' + error + '</span>');
    $(upload_field).form.reset();
    return false;
  }

  $(upload_field).form.submit();
  $(upload_field).disabled = true;

  return true;
}

function gamePopup(gameurl, title, caturl)
{
  var t = title.replace(/\W/g, '_');

  window.open(gameurl, t, 'width=960, height=680, toolbar=0,menubar=0,location=0,scrollbars=1,resizable=1');
  window.location = caturl;
}

function reloadScoreContainer()
{
  if (!scoreUrl) return false;

  new Ajax.Updater({success: 'game_highscores'}, scoreUrl, {
      evalScripts: true,
      onLoading: function() {$("game_scores_loading", "game_highscores").invoke('toggle');},
      onComplete:function() {$("game_scores_loading", "game_highscores").invoke('toggle');}
    });

  if(!lastScoreUrl) return false;
  new Ajax.Updater({success: 'last_highscore'}, lastScoreUrl, {
      evalScripts: true
    });
}

function playFromHtmlSnippet()
{
  $('game_html_snippet', 'game_main').invoke('toggle');
  track('/virtual' + window.location.pathname);
}


function showParticipationPopup(url)
{
  Modalbox.show(url,
     {
       title: '',
       closeString: '',
       onShow: function() { toggleEmbed();  },
       afterHide: function() {toggleEmbed(); },
       width: 620,
       height: 551
     });
  return false;
}

function goToUrl(url, seconds)
{
  if(!seconds) seconds = 1000;
  setTimeout('window.location = "'+url+'"', seconds);
}

function goToLobby()
{
  if(!lobbyUrl) return false;

  goToUrl(lobbyUrl);
}

function validateRequired(requiredFormFields, noErrors)
{
  var validates = true;

  if(rquiredFormFields && requiredFormFields.size() > 0)
  {
    requiredFormFields.each(function(field){
      var currentValidates = true;
      switch($(field).type)
      {
        case 'checkbox':
          if(!$(field).checked) {	currentValidates = false; }
          break;
        default:
          if($(field).value.empty()) { currentValidates = false; }
          break;
      }

      if(!currentValidates)
      {
        $(field+'_error').update(formErrors.get(field));
        if(!noErrors) $(field+'_error').show();
        validates = false;
      }
      else
      {
        $(field+'_error').hide();
      }
    });
  }

  return validates;
}

function validateSendDeveloperGame()
{
  var validates = true;

  validates = validateRequired(new Array('name', 'email', 'game_title', 'captcha'));

  if(validates)
  {
    validates = (validateRequired(new Array('game_link'), true) || validateRequired(new Array('game_file'), true));
    if(!validates)
    {
      var visible = ($('game_link').style.display != 'none') ? 'game_link' : 'game_file';
      $(visible+'_error').update(formErrors.get('game_link'));
      $(visible+'_error').show();
    }
    else
    {
      $('game_link_error', 'game_file_error').invoke('hide');
      validates = ($('game_file').value.search(/\.exe/i) == -1);
      if(!validates)
      {
        $('game_file_error').update(formErrors.get('game_file'));
        $('game_file_error').show();
      }
    }
  }

  return validates;
}

function copy2clipboard()
{
  Copied = game_snippet.createTextRange();
  Copied.execCommand("RemoveFormat");
  Copied.execCommand("Copy");
}

function goToAbi(node)
{
  $('invitation_form').action = node.form.action;
  $('invitation_form').submit();

  return false;
}

function toggleContactsList(node)
{
  $('contacts_list').getElementsBySelector('[type="checkbox"]').each(function(chbox){
    chbox.checked = node.checked;
  });
}

function playMpGame(address, port, roomId, userId)
{
  if (!mpGameUrl) return false;

  window.location = mpGameUrl + "?gsloc=" + address + "&gsport=" + port + "&roomId=" + roomId +
                    "&userId=" + userId;
}

var gotdi = 0;
var GameRotator = Class.create({
  initialize: function(el, timer, rawGotds) {
    this.el = $(el+'_'+gotdi);
    this.paused = 0;
    this.timer = timer ? timer : 3;
    this.gotds = rawGotds;

    this.reverseGotds = this.gotds;

    this.eventMouseOver = this.pause.bindAsEventListener(this);
    this.eventMouseOut = this.unpause.bindAsEventListener(this)
    this.eventMouseClick = this.pause.bindAsEventListener(this);
    this.registerEvents();

    this.execute();
  },

  registerEvents: function() {
    Event.observe($('gotdHolder'), "mouseover", this.eventMouseOver);
    Event.observe($('gotdHolder'), "mouseout", this.eventMouseOut);
    Event.observe($('gotdHolder'), "click", this.eventMouseClick);
  },

  execute: function() {
    this._executor = new PeriodicalExecuter(function(pe) {
        this.rotateRule();
      }.bind(this), this.timer);
  },

  rotateRule: function() {
    var j = gotdi++;

      if (j == this.gotds.length)
      {
        gotdi = 0;
        j = gotdi++;
      }

    this.retrieveGotd(this.reverseGotds[j]);
  },

  retrieveGotd: function(id) {
    var hiddens = this.gotds.without(id);

    hiddens.each(function(s) {
      $('switch_'+ s).setStyle({
        backgroundColor: '#000',
        color: '#fff'
      });
      $(s).fade();
    });

    $(id).appear();

    $('switch_'+id).setStyle({
      backgroundColor: '#fff',
      color: '#000'
    });


  },

  pause: function() {
    this.paused = 1;
    this._executor.stop();
  },

  unpause: function() {
    this.paused = 0;
    this.execute();
  }
});


var SwitchGameRotator = Class.create({
  initialize: function(el, rawGotds) {
    this.el = el;
    this.gotds = rawGotds;

    this.execute();
  },

  execute: function() {
    var x = 0;
    for (x = 0; x < this.gotds.length; x++) {

      if(x == 0) {
        new Insertion.Bottom(this.el, '<div class="floatLeft"><a href="#" class="floatLeft" onclick="switchActiveGame(\''+ this.gotds[x] +'\');" id="switch_gotd_'+ x +'" style="margin-right:1px; text-align:center; width:20px; display:block; background:#fff; color:#000; padding-right:1px">'+ (x + 1) +'</a></div>');
      }
      else {
        new Insertion.Bottom(this.el, '<div class="floatLeft"><a href="#" class="floatLeft" onclick="switchActiveGame(\''+ this.gotds[x] +'\');" id="switch_gotd_'+ x +'" style="margin-right:1px; text-align:center; width:20px; display:block; background:#000; padding-right:1px">'+ (x + 1) +'</a></div>');
      }
    }
  }
});

function switchActiveGame(id)
{
  $(id).show();

  $('switch_'+id).setStyle({
    backgroundColor: '#fff',
    color: '#000'
  });

  var hiddens = rawGotds.without(id);

  hiddens.each(function(s) {
    $('switch_'+ s).setStyle({
      backgroundColor: '#000',
      color: '#fff'
    });

    $(s).hide();
  });

}

var preGameAdv = Class.create({
  initialize: function(el, duration, width) {
    this.el = $(el);
    this.duration = duration;
    this.width = width;
    this.timer = 0.25;
    this.steps = duration / this.timer;
    this.currentWidth = 0;

    this.execute();
  },

  execute: function() {
    this._executor = new PeriodicalExecuter(function(pe) {
      this._showAdv();
    }.bind(this), this.timer);
  },

  _togglePreGameAdv: function() {
	$('bannerPreGameToggleT').hide();  
    $('bannerPreGameToggle').show();
  },

  _showAdv: function() {
    this.currentWidth += (this.width / this.steps);
    if(this.currentWidth > this.width)
      this.currentWidth = this.width;

    if(this.currentWidth > (this.width / 2))
      this._togglePreGameAdv();
    
    this.el.setStyle({ width: this.currentWidth+'px' });

    if(this.currentWidth >= this.width)
    {
      this._executor.stop();
//      this._togglePreGameAdv();
    }
  }
});

var forumIframeUrl = null;
var forumHomepageUrl = null;
function loginSuccessRedirect()
{
  if (!forumIframeUrl || !forumHomepageUrl)
  {
    setTimeout('window.location.reload();', 1000);
    return;
  }

  if(window.location.href.search(forumIframeUrl) == 0)
  {
    setTimeout('window.location = "'+forumHomepageUrl+'"', 1000);
  }
  else
  {
    setTimeout('window.location.reload();', 1000);
  }
}

function subdomainGo(a)
{
  var subd = a.href;

  if(g_accounts)
    track(subd);
  var newWindow = window.open(subd, '_blank');
}

function bookmarkIt(msg)
{
  var url = window.document.URL;
  var title = window.document.title;
  
  if (!document.all && window.sidebar && !window.opera) 
  { 
	  window.sidebar.addPanel(title, url, '');
  }
  else if (document.all)
  {	  
	  window.external.AddFavorite(url, title);
  }
  else
  {
	  Modalbox.show(msg, {title: '', closeString: '', onShow: function() {toggleEmbed();  }, afterHide: function() {toggleEmbed();  } , height: 136, width: 338}); return false;
  }
  
//else if(window.opera && window.print)
//{ // opera
//	var elem = document.createElement('a');
//	elem.setAttribute('href',url);
//	elem.setAttribute('title',title);
//	elem.setAttribute('rel','sidebar');
//	elem.click();
//}
  
}
