/**
 * @author dev2
 */

SpeedChecker = function(config) {
  // configurable {
  this.max_time = 4500;
  this.image_url = '/js/speed_checker/checker.jpg';
  this.zero_img = '/img/0.gif';
  // }
  
  $.extend(this, config);
}

SpeedChecker.prototype = {
  start:function() {
    this.current_time = new Date;
    this.timer = setTimeout($.proxy(this.onTimeOut, this), this.max_time);
    this.check_image = $('<div style="position: absolute; left: -2000px; top: -2000px; overflow: hidden; width:1px; height: 1px;"><img src="'+this.zero_img+'" alt="" /></div>').appendTo('body');
    $('#speed_checker').dialog('open');
    $('img', this.check_image).load($.proxy(this.onLoadImage, this)).attr('src', this.image_url+'?'+Math.random());
  },
  
  onTimeOut:function() {
    this.check_image.remove();
    $('#speed_checker_info').html('По результатам теста мы рекомендуем Вам загрузить облегченную версию сайта.');
    setTimeout(this.closeChecker, 4000);
    this.setLightweight(1);
    //this.loadLightVersion();
  },
  
  onLoadImage:function() {
    clearTimeout(this.timer);
    $('#speed_checker_info').html('По результатам теста мы рекомендуем Вам загрузить полную версию сайта.');
    setTimeout($.proxy(this.loadFullVersion, this), 4000);
    //this.loadFullVersion();
  },
  
  loadLightVersion:function() {
    this.setLightweight(1);
    location.href = location.href;
  },
  
  loadFullVersion:function() {
    this.setLightweight(0);
    location.href = location.href;
  },
  
  setLightweight:function(mode) {
    var exp = new Date();
    var oneYearFromNow = exp.getTime() + (365 * 24 * 60 * 60 * 1000);
    exp.setTime(oneYearFromNow);
    document.cookie = 'lightweight='+mode+';path=/;expires=' + exp.toGMTString();
  },
  
  closeChecker:function() {
    $('#speed_checker').dialog('close');
  }
}
