if(typeof(GameVars) === 'undefined') GameVars = {};
GameVars.vars = GameVars.vars || {};
GameVars.getGameWindowWidth = function() { return GameVars.vars.game_window_width; };
GameVars.getGameWindowHeight = function() { return GameVars.vars.game_window_height; };
GameVars.isLoggedIn = function() {return GameVars.vars.is_logged_in;};
GameVars.isValidPlayer = function() {return GameVars.vars.is_valid_player;};
GameVars.isOncePlay = function() {return getCookie('is_once_played');};
GameVars.getZveripediaUrl = function() { return GameVars.absPath('/zveripedia/index.php'); };
GameVars.getFeedbackUrl = function()  { return GameVars.absPath('/feedback'); };
GameVars.absPath = function(url) { return url.match(/^(https?:|\/)/) ? url : GameVars.getBasePath() + url; };
GameVars.getBasePath = 
function() {
  if(!GameVars.vars.base_path || !GameVars.vars.base_path.length)
  {
    if(window.document.baseURI)
      GameVars.vars.base_path = window.document.baseURI;
    else
      GameVars.vars.base_path = 'http://zveriki.com/';
  }  
  return GameVars.vars.base_path;
};

GameVars.ajax = function(options) 
{
  options.type = options.type || 'POST';
  options.data = options.data || {};
  options.dataType = options.dataType || 'json';
  options.url = GameVars.absPath(options.url);
  options.error = options.error || function() {baseErrorAjaxSend();};
  if(typeof(options.async) == 'undefined')
    options.async = false;
  (function(beforeSend) {options.beforeSend = function() {if(typeof(ajaxLoader) != 'undefined') ajaxLoader.show(); if(typeof(beforeSend) == 'function') beforeSend(); }})(options.beforeSend);
  (function(complete) {options.complete = function() {if(typeof(ajaxLoader) != 'undefined') ajaxLoader.hide(); if(typeof(complete) == 'function') complete(); }})(options.complete);
  return options;
}
                                
function openPlayGamePopup()
{
  openPopup(GameVars.getBasePath() + 'member_play_game/game', GameVars.getGameWindowWidth(), GameVars.getGameWindowHeight(), 'play_game');
}

function openTrialGamePopup()
{
  //openPopup(GameVars.getBasePath() + 'trial_game/play', GameVars.getGameWindowWidth(), GameVars.getGameWindowHeight(), 'play_game'); 
}

var Friends = 
{
  lock: false,
  removeClick: function(id)
  {                                   
    if(Friends.lock)
      return;
    var text = 'Вы уверены что хотите удалить пользователя из вашего списка друзей?';
    GameModalWindow.confirmCallback(text, function() {Friends.sendRequestDelete(id);}); 
  },

  sendRequestDelete: function(id)  
  {
    if(Friends.lock)
      return;
    Friends.lock = true;
    ajaxLoader.show();
    jQuery.ajax({
      type: 'POST',
      data: {'id':id},
      cache: false,
      dataType: 'json',
      url: 'my/ajax_remove_from_friends',
      success: function(data) 
      {
        Friends.lock = false;
        ajaxLoader.hide();
        if(data.errors)
        {
          GameModalWindow.message(data.errors);
          return;
        }
        if(data.message)
          GameModalWindow.message(data.message, false, function() {location.reload();});
      },
      error: function() { 
        Friends.lock = false;
        baseErrorAjaxSend();
      }
    });
  }
}

var MemberBlackList = {
  lock: false,

  clickAdd: function(id) 
  {
    MemberBlackList.confirmAction('Добавить пользователя в черный список?', function() {MemberBlackList.send(id, 'my/ajax_add_to_ignored');});
  },
  
  clickRemove: function(id) 
  {
    MemberBlackList.confirmAction('Удалить пользователя из черного списка?', function() {MemberBlackList.send(id, 'my/ajax_remove_from_ignored');});
  },

  confirmAction: function(question, callback)
  {
    if(MemberBlackList.lock)
      return;
    GameModalWindow.confirmCallback(question, callback); 
  },

  send: function(id, url)  
  {
    if(MemberBlackList.lock)
      return;
    MemberBlackList.lock = true;
    ajaxLoader.show();
    jQuery.ajax({
      type: 'POST',
      data: {id: id},
      cache: false,
      dataType: 'json',
      url: url,
      success: function(data) 
      {
        MemberBlackList.lock = false;
        ajaxLoader.hide();
        if(data.errors)
        {
          GameModalWindow.message(data.errors);
          return;
        }
        if(data.message)
          GameModalWindow.message(data.message, false, function() {location.reload();});
      },
      error: function() 
      { 
        MemberBlackList.lock = false;
        baseErrorAjaxSend();
      }
    });
  }
}

function openPopup(url, windowWidth, windowHeight, name, view_location)
{
  var centerWidth = (window.screen.width - windowWidth) / 2;
  var centerHeight = (window.screen.height - windowHeight) / 2;

  if(view_location !== 1)
    view_location = 0;

  newWindow = window.open(url, name,
                          'resizable=0' +
                          ',toolbar=0' + 
                          ',location=' + view_location +  
                          ',width=' + windowWidth +
                          ',height=' + windowHeight +
                          ',left=' + centerWidth +
                          ',top=' + centerHeight);
  if(newWindow)
    newWindow.focus();
}

function openInParentWindow(url, close_current)
{
  if(!window.opener)
  {
    window.location = url;
  }
  else
  {
    window.opener.location = url;
    window.opener.focus();
    if(close_current)
      window.close();
  }
}

function base_estimate(opinion_type, id, sign, success_callback, show_loader)
{
  if(sign>0)
    var vote_url = 'vote/ajax_positive/'+opinion_type+'/';
  else if(sign<0)
    var vote_url = 'vote/ajax_negative/'+opinion_type+'/';
  else
  {
    GameModalWindow.message(i18n['error_try_again_later']);
    return false;
  }
  this.send_estimations = this.send_estimations || {};
  var request_id = opinion_type + '_' + id;
  if(this.send_estimations[request_id])
    return;
  this.send_estimations[request_id] = 1;

  if(show_loader)
    ajaxLoader.show();

  var link = this;
  jQuery.ajax({
  type: 'POST',
  dataType: 'json',
  data: {id: id},
  url: GameVars.absPath(vote_url),
  success: function(data) {
    link.send_estimations[request_id] = 0;
    if(data.error)
    {
      GameModalWindow.message(data.error);
      return;
    }
    if(!success_callback)
      GameModalWindow.message(data.message);
    else
      success_callback(data.message);
  },
  error: function() {
    GameModalWindow.message(i18n['error_try_again_later'], '');
    link.send_estimations[request_id] = 0;
  },
  complete: function() {
    if(show_loader)
      ajaxLoader.hide();
  }
  });
}

function video_estimate(id, sign)
{
  return base_estimate('video_opinion', id, sign);
}

function photo_estimate(id, sign)
{
  return base_estimate('photo_opinion', id, sign);
}

function adequacy_vote(id, sign)
{
  return base_estimate('adequacy_opinion', id, sign);
}

function pet_vote(id, sign)     
{
  return base_estimate('pet_opinion', id, sign);
}

function message_vote(id, sign)
{
  return base_estimate('message_opinion', id, sign);
}

function baseErrorAjaxSend()
{
  if(typeof(ajaxLoader)=='object')
    ajaxLoader.hide();
  GameModalWindow.message(i18n['base_error_ajax_send'], '');
}

function getCookie(name) {
	var cookie = " " + document.cookie;
	var search = " " + name + "=";
	var setStr = null;
	var offset = 0;
	var end = 0;
	if (cookie.length > 0) {
		offset = cookie.indexOf(search);
		if (offset != -1) {
			offset += search.length;
			end = cookie.indexOf(";", offset)
			if (end == -1) {
				end = cookie.length;
			}
			setStr = unescape(cookie.substring(offset, end));
		}
	}
	return(setStr);       
}

function ClickPlayOrTrial(link)
{
  return ClickPlayPets(link);
  /*(GameVars.isOncePlay())
    return ClickPlayPets(link);
  openTrialGamePopup();
  return false;*/
}

function ClickPlayPets(link)
{
  var href;
  href = getGameLinkRedirect(true);
  if(!href)
  {
    return false;
  }
  link.href = href;
  link.target = '';
  return true;
}

function getGameLinkRedirect(validate_player)
{                      
  if(validate_player && !GameVars.isValidPlayer())
    return 'member_play_game';

  if(SWPlaerStat.allowGame())
  {
    openPlayGamePopup();
    return false;
  }
  return GameVars.getHelpShockwaveInstallUrl();
}

GameVars.getHelpShockwaveInstallUrl = function()
{
  var href = 'other';
  if(jQuery.browser.mozilla)
    href = 'mozilla';
  else if(jQuery.browser.safari)
    href = 'safari';
  else if(jQuery.browser.opera)
    href = 'opera';
  return 'game/help_' + href; 
}

function getShockwaveVersion()
{
  navigator.plugins.refresh();
  var
    plugins = navigator.plugins, 
    l = plugins.length,
    desc;
  for (i=0; i < l; i++)
  {
    desc = plugins[i].description;
    if(desc.indexOf("Shockwave") != -1 && desc.indexOf("Director") != -1)
      return parseInt(desc.substring(desc.indexOf("version ") + 8));
  }
  return false;
}

function clickPrivateMessage(link)
{    
  if(jQuery.browser.msie)
    var view_location = 1;
  else
    var view_location = 0;

  href = link.href;
  href_arr = href.split('/');
  id = href_arr[href_arr.length-1];
  if(id=='')
    id = href_arr[href_arr.length-2];
  openPopup(link.href, 616, 680, id , view_location);
  return false;
}

SWPlaerStat = {
  id: 0,
  level: false,

  valid_version: 11,
  is_init: false,
  send_construct_info: false,

  cookie_id: 'splayer_id',
  cookie_level: 'splayer_level',
  url_ajax: 'game/ajax_player_stat',

  level_construct: 0,
  level_help: 1,
  level_adobe_link: 2,
  level_installed: 3,

  version: -1,
  browser: 0,
  new_level: -1,

  callbackInit: false,

  start: function()
  {
    this._init(this._updatePlayerInfo);
  },

  updateLevel: function(level)
  {
    var that = this;
    this._init(function() { that._updateLevel(level) })
  },

  allowGame: function()
  {
    return jQuery.browser.msie || this.getPlayerVersion(true) == this.valid_version;
  },

  _init: function(callback)
  {
    var that = this;
    var old_callback;
    if(!callback)
      callback = function() {};

    if(this.is_init)
      return callback();
    if(this.id = getCookie(this.cookie_id))
    {
      this.level = getCookie(this.cookie_level);
      this.is_init = true;
      return callback();
    } 
    old_callback = this.callbackInit;
    if(old_callback)
    {
      this.callbackInit = function()
      {
        old_callback();
        callback();
      }
      return;
    }
    this.callbackInit = callback;
    this._detectPlayer(
      function(installled) 
      { 
        var level;
        if(installled)
          level = that.level_installed;
        else
          level = that.level_construct;
        that._sendInfo(level, that.callbackInit);
      }
    );
  },

  _updatePlayerInfo: function()
  {
    if(jQuery.browser.msie)
      return;
    if(this.level < this.level_installed && getShockwaveVersion() == this.valid_version)
      this._sendInfo(this.level_installed);
  },

  _updateLevel: function(level)
  {
    if(level <= this.level)
      return;
    this._sendInfo(level);
  },
  
  _detectPlayer: function(callback)
  {
    if(jQuery.browser.msie)
    {
      detectShockwavePlayerIe.process(callback); 
    }
    else
    {
      callback(getShockwaveVersion() == this.valid_version);
    }
  },

  _sendInfo: function(level, call_back)
  {
    var that = this;

    jQuery.ajax({
      type: 'POST',
      url: this.url_ajax,
      dataType: 'json',
      data: {'id': this.id, 'level': level, 'browser_type': this.getBrowserType(), 'browser_version': jQuery.browser.version, 'player_version': this.getPlayerVersion()},
      success: function(data) {
        if(data.level)
          that.level = data.level;
        if(data.id)
          that.id = data.id;
        if(call_back)
          call_back();
      }
    })
  },

  getBrowserType: function()
  {
    if(jQuery.browser.mozilla)
      return 1;
    else if(jQuery.browser.safari)
      return 2;
    else if(jQuery.browser.opera)
      return 3;
    else if(jQuery.browser.msie)
      return 4;
    return 0;
  },

  getPlayerVersion: function(refresh)
  {
    var version = false;
    if(!refresh && this.version !== -1)
      return this.version;
    if(jQuery.browser.msie) {
      version = 0;
    } else {
      version = getShockwaveVersion();
    }
    this.version = version;
    return this.version;
  },

  clickAdobeLink: function()
  {
    if(this.click_adobe_link || jQuery.browser.msie)
      return;
    this.click_adobe_link = true;
    
    this.updateLevel(this.level_adobe_link);
    
    this.waitInstalledPlayer();
  },

  waitInstalledPlayer: function()
  {
    var that = this;
    if(this.wait_installed_player_interval)
      clearInterval(this.wait_installed_player_interval);
    this._detectPlayer(function(result) {
      if(!result)
      {
        that.wait_installed_player_interval = setTimeout(function() {that.waitInstalledPlayer()}, 5000);
        return;
      }
      that.updateLevel(SWPlaerStat.level_installed);
      alert('Плеер успешно установлен! Можно начинать игру.');
      window.location = GameVars.getBasePath() + '/member_play_game';
    }); 
  }
}

detectShockwavePlayerIe = 
{
  installled: -1,
  callback: function() {},
  wait_frame_response_interval: false,

  process: function(callback)
  {
    // TODO 
    return callback(0);
    var that = this;
    if(this.installled !== -1)
      return callback(this.installled);
    this.callback = callback;
    this.wait_frame_response_interval = setTimeout(function() { that.dcrFailedUpload() }, 5000);
    jQuery('body').append('<iframe src="shared/detect_player.html" frameborder="no" height="1" width="1" scrolling="no" hspace="0" vspace="0"></iframe>');
  },

  dcrFailedUpload: function()
  {
    this.response(false);
  },
    
  dcrSuccesUpload: function() 
  {
    this.response(true);
  },

  response: function(result)
  {
    this.installled = result;
    if(this.wait_frame_response_interval)
    {
      clearInterval(this.wait_frame_response_interval);
      this.wait_frame_response_interval = false;
    }
    if(this.callback)
      this.callback(result);
  }
}

function br2nl(text)
{         
  var regexp = /\n/g;
  text = text.replace(regexp, '');
  text = text.replace(/<br>/gi, "\n");
  text = text.replace(/<br\/>/gi, "\n");
  return text;
}

function nl2br(text)
{
  var regexp = /\n/g;
  return text.replace(regexp, '<br>');
}

function htmlentities(s)
{   
  var div = document.createElement('div');
  var text = document.createTextNode(s);
  div.appendChild(text);
  return div.innerHTML;
}

(function() {
  id_counter = 0;

  // win - Base modal window
  // {{{
  var win = function(container)
  {
    this.container = container || jQuery('#wrapper');
    this.id = 'modalwin_' + ++id_counter;
    this.is_removed = false;
  }
  
  win.prototype.hide_if_close = false;
  win.prototype.class_modal_window = 'modalWindow';

  win.prototype.buildOverlay = function() 
  {
    this.container.append('<div id="' + this.id + '" style="display:none;"></div>');
    this.windowOverlay = this.container.find('#'+this.id);
    if(this.container.find('div.modalWindowOverlay').length) // TODO хак
    {   
      this.container.find('div.modalWindowOverlay').show();
      return;
    }
    this.windowOverlay.append('<div class="modalWindowOverlay" ></div>');
  };

  win.prototype.buildWindow = function()
  {
    this.win = this.windowOverlay.find('.'+this.class_modal_window);
    if(!this.win.is('div'))
      this.setWin('<div class="'+this.class_modal_window+'"></div>');
  };

  win.prototype.setWin = function(html)
  {
    this.windowOverlay.append(html);
    this.win = this.windowOverlay.find('.'+this.class_modal_window);
  }

  win.prototype.afterBuild = function() {};

  win.prototype.build = function(data) 
  {
    this.buildOverlay(data);
    this.buildWindow(data);
    this.afterBuild(data);
    return this;
  };

  win.prototype.show = function() 
  {
    this.windowOverlay.show();
  };

  win.prototype.hide = function()
  {
    this.windowOverlay.hide();
  };

  win.prototype.addCloseButon = function(el, callback) 
  {
    el = el || this.win;
    el.append("<a href='javascript:void(0)' class='close_icon' title='Закрыть'><img src='images/1x1.gif' alt='Закрыть' /></a>");
    this.close_button = el.find('.close_icon');
    this.bindClose(callback, this.close_button);
  };

  win.prototype.bindClose = function(callback, button) 
  {
    button = button || this.win.find('.close_icon');
    callback = callback || function(w) {
      w.close();
      return true;
    };
    var w = this;
    button.bind('click', function() {callback(w);});
  };

  win.prototype.addBackground = function()
  {
    this.win.append('<div class="bgr"></div>');
  };

  win.prototype.close = function() {
    if(this.hide_if_close)
      this.hide();
    else
      this.remove();
  };

  win.prototype.remove = function() {
    this.windowOverlay.remove();
    this.is_removed = true;
  };
  // }}}

  // win_medal - Medal
// {{{
  var win_medal = function(container) { win.call(this, container); };
  win_medal.prototype = new win();
  win_medal.prototype.afterBuild = function(data) {
    this.win.append(
      '<div class="msg">'+
        '<h1><img src="images/1x1.gif" alt="Поздравляем!" /></h1>' + 
        '<h2><img src="images/1x1.gif" alt="У вас новая медаль!" /></h2>' +
        '<div class="medals_case"><img src="'+data.src+'" /></div>'+
        '<div class="medals_info">'+
          '<h4>'+data.title+'</h4>'+
          data.description+' <br/><br/>'+
          '<strong>'+data.effects+'</strong>'+
        '</div>'+
        '<div class="medals_other_info"><a href="">Мои Достижения</a></div>'+
      '</div>'+
      '<span class="title"><img src="images/1x1.gif" alt="Сообщение" /></span>'
      );
    this.addCloseButon();
    this.addBackground();
    this.win.attr('id', 'greetingsNewMedal_popup');
  };
  // }}}

  // save old interface
  window.modalWindow = {
    messageBlock: function(msg, container, callback) {return GameModalWindow.message(msg, container, callback);},
    confirmBlock: function(msg, target) { return GameModalWindow.confirm(msg, target); },
    confirmBlockCallback: function(msg, yes_function, no_function) {return GameModalWindow.confirmCallback(msg, yes_function, no_function);}
  }

  window.GameModalWindow = {
    simpleWin: function()
    {
      return new win(); 
    },

    newWindow: function(el, class_name) // selector or html
    {
      var w = new win();
      w.build();
      w.addCloseButon();
      w.addBackground();
      jQuery(el).appendTo(w.win);
      if(class_name)
        w.win.addClass(class_name);
      return w;
    },
    
    rawNewWindow: function(html, show) 
    {
      var w = new win();
      w.buildOverlay();
      w.setWin(html);
      w.bindClose();
      w.show();
      return w;
    },

    message: function(msg, container, callback)
    { 
      var w = new win(container);  
      w.build();
      w.win.attr('id', 'message_block');
      var on_close = function(w)
      {
        w.close();
        if(typeof(callback) === 'function')
          callback();
      }
      w.addCloseButon(false, on_close);
      w.win.append(
        '<div class="msg">' + msg + '</div>'+ 
        '<span class="title"><img src="images/1x1.gif" alt="Сообщение" /></span>'+
        '<a href="javascript:void(0)" class="button" id="ok_button">OK</a>'
      );
      w.addBackground();
      w.show();    
      w.win.find('#ok_button').focus().bind('click', function() {on_close(w);});
      return w; 
    }, 
    
    baseConfirm: function(message, cancel_callback)
    {
      var w = new win(); 
      w.build();
      w.win.attr('id', 'confirm_block');
      cancel_callback = cancel_callback || function(w) {w.close();};
      w.addCloseButon(false, cancel_callback);
      w.win.append(
        '<span class="title"><img src="images/1x1.gif"/></span>'+
        '<div class="msg">' + message + '</div>'+ 
        '<div class="button_panel">' +
        '<a href="javascript:void(0)" class="button" id="yes_button">OK</a>' +
        '<a href="javascript:void(0)" class="button" id="cancel_button">Отмена</a>'
      );
      w.yes_button = w.win.find('#yes_button');
      w.no_button = w.win.find('#cancel_button').bind('click', function() {cancel_callback(w);});
      w.addBackground();
      return w; 
    },

    confirm: function(msg, href)
    {
      var w = this.baseConfirm(msg);      
      w.yes_button.attr('href', href);
      w.show();
      return w;
    },

    confirmCallback: function(msg, yes_function, no_function)
    {
      var on_cancel = function(w) {if(typeof(no_function) == 'function') no_function(w); w.close();};
      var w = this.baseConfirm(msg, on_cancel);
      w.yes_button.bind('click', function() {w.close(); if(typeof(yes_function) == 'function') yes_function(w);});
      w.no_button.bind('click', function() {on_cancel(w)});
      w.show();
      return w;
    }
  };
})();

function GameTinyMceUrlConvertor(url, node, on_save) 
{
  return url; // not change
}

function GameDecode(a)
{
  var str = '';
  for(i=0;i< a.length;i++)
    str += ((a.charCodeAt(i)<=127) ? String.fromCharCode((a.charCodeAt(i)-65)*16+(a.charCodeAt(++i)-65)) : a.charAt(i));
  return str;
}

(function(dd) {
  dd.utils = dd.utils || {};
  dd.utils.dump = function(obj) {
    var m = '';
    if(typeof(obj) == 'object')
    {
      for(var i in obj) {
        try
        {
          if(typeof(obj[i]) !== 'function')
            m += "\n"+i+":"+obj[i];
        } catch (e) {};
      }
    }
    else
      m = typeof(obj) + ': ' + obj;  
    alert(m);
  };
  dd.utils.dumpf = function(obj) {
    var m = '';
    for(var i in obj)
      try
      {
        if(typeof(obj[i]) == 'function')
          m += "\n"+i;
      } catch (e) {};
    alert(m);
  };
})(GameVars);
