if(!Array.indexOf){
  Array.prototype.indexOf = function(obj){
    for(var i=0; i<this.length; i++){
      if(this[i]==obj){
        return i;
      }
    }
    return -1;
  }
}
(function(){
  var observer = {};
  var startTime = Date.now();
  var Observer = function(){
    var init = function(){
      var self = this;
      self.remembedBaloons = [];
      //self.startTime = Date.now();
      self.conf = {
        url:'http://userstat.maplos.com/client',
        //url:'http://stat.maplos.local/client',
        maxDelay:180000
      }
      self.firstSearch = true;
      self.searchStarted = false;
      self.counters = {
        url:window.location.href,
        ua:navigator.userAgent,
        clicks:0,
        sid:Cookie.get('sid'),
        balloonClicks:[],
        hint:0,
        formSubmit:0,
        columnOpenMoreResults:0,
        anyLinkClicks:0,
        resize:0,
        mousedown:0,
        subquery:0,
        yad:0,
        clickTop:0,
        clickFooter:0,
        result:{
          time:0,
          status:'',
          notWait:1
        },
        scroll:{
          results:0,
          page:0
        },
        map:{
         moves:0,
         zoom:0,
         mousedown:0
        },
        autoOpenBalloon:0,
        resultClick:0,
        resultRedirects:{
          column:0,
          balloon:0,
          bottom:0,
          autoOpenBalloon:0
        },
        focus:{
          what:0,
          where:0
        },
        times:[
        ]
      };
      self.memory = {
        balloonClicks:[]
      }
      self.beforeMapLoad();
      Event.bind('load.map',function(){
        self.getRef();
        self.getWhat();
        self.activity();
        self.stopWatch = StopWatch;
        self.start();
      })
    }
    init.prototype = {
      getWhat:function(){
        var self = this;
        match = window.location.href.match(/^http\:\/\/[^\/]+\/kiev\/([^#\/]+)/);
        what = match ? match[1] : '';
        try{
          what = decodeURIComponent(what);
        }catch(e){};
        self.counters.what = what;
      },
      getRef:function(){
        var self = this;
        var from,ref = document.referrer,domen = window.location.href.match(/http\:\/\/([^\/]+)/)[1];
        if(!ref.length)from = 'direct';
        else if (document.referrer.match(/^https?\:\/\/(www\.)?google/)) from = 'google';
        else if (document.referrer.match(new RegExp('^http\:\/\/'+domen))) from = 'local';
        else from = 'link';
        self.counters.referrer = ref;
        self.counters.from = from;
      },
      beforeMapLoad:function(){
        var self = this;
        Event.bind('search.started',function(){
          self.searchStarted = true;
        })
        Event.bind('scroll.autoColumn',function(){
          if(--self.counters.scroll.results < 0) self.counters.scroll.results = 0;
            
        })
      },
      activity:function(){
        var self = this;
        self.activity = false;
        YMaps.Events.observe(Map.map, Map.map.Events.MouseMove,function(){
          self.extendActivity();
        });
        YMaps.Events.observe(Map.map, Map.map.Events.Click,function(){
          self.extendActivity();
        });
        jQuery(window).bind('mousemove keyup mouseup',function(){
          self.extendActivity();
        })
      },
      extendActivity:function(){
        var self = this;
        self.runTimer();
        if(self.activity)return;
        self.stopWatch.start();
        self.activity = true;
      },
      runTimer:function(){
        var self = this;
        clearTimeout(self.timer);
        self.timer = setTimeout(function(){
          self.activity = false;
          self.stopWatch.stop(self.conf.maxDelay);
        },self.conf.maxDelay)
      },
      isLink:function(e){
        var self = this;
        try{
          if(e.nodeName == 'BODY')
            return false;
          if(e.nodeName == 'A')
            return true;
        }catch(e){
          return false;
        }
        return self.isLink(e.parentNode);
      },
      start:function(){
        var self = this;
        Event.bind('balloon.open',function(data){
          self.autoOpenBalloon = false;
          self.balloonClick(data);
        });
        Event.bind('balloon.resultClick',function(balloon){
          if(self.autoOpenBalloon && self.autoOpenBalloon == balloon.resultPoint){
            self.counters.resultRedirects.autoOpenBalloon = 1;
          }else{
            self.counters.resultRedirects.balloon++;
          }
        });
        Event.bind('balloon.hintOpen',function(){
          self.counters.hint++;
        })
        Event.bind('balloon.autoOpen',function(balloon){
          self.autoOpenBalloon = balloon;
          self.counters.autoOpenBalloon = 1;

        });
        Event.bind('form.submit',function(){
         self.counters.formSubmit = 1;
        });
        Event.bind('search.finished',function(status){
          if(!self.firstSearch)
            return;
          self.firstSearch = false;
          self.counters.result = {
            time   : Date.now() - startTime,
            status : status,
            notWait: 0
          }
        })
        Event.bind('search.subquery',function(status){
          self.counters.subquery++;
        })
        window.addEventListener('mousedown',function(){
          self.counters.mousedown++
        },true);
        window.addEventListener('click',function(e){
          self.counters.clicks++;
          if(self.isLink(e.target)){
            self.counters.anyLinkClicks++;
          }
        },true);
        window.addEventListener('touchstart', function(e) {
          self.counters.mousedown++;
          if(self.isLink(e.target)){
            self.counters.anyLinkClicks++;
          }
        }, true);
        window.addEventListener('resize',function(){
          self.counters.resize++;
        },false)
        jQuery('#results .rel-green').live('click',function(){
          self.counters.resultClick++;
        })
        jQuery('#results .result-item-holder a').live('mouseup',function(){
          self.counters.resultRedirects.column++;
        });
        jQuery('#other-results a').live('mouseup',function(){
          self.counters.resultRedirects.bottom++;
        });
        jQuery('#results h4>.action').live('click',function(){
          self.counters.columnOpenMoreResults++;
        });
        jQuery('#yandex_direct a').live('click',function(){
          self.counters.yad++;
        });
        jQuery('#maplos-inputs input[name=what]').bind('focus',function(){
          self.counters.focus.what++;
        })
        jQuery('#maplos-inputs input[name=where]').bind('focus',function(){
          self.counters.focus.where++;
        })
        YMaps.Events.observe(Map.map, Map.map.Events.MoveEnd,function(){
          self.counters.map.moves++;
        });
        //YMaps.Events.observe(Map.map, Map.map.Events.MouseDown,function(){
        //  self.counters.map.mousedown++;
        //});
        jQuery('#map .map-holder')[0].addEventListener('mousedown',function(){
          self.counters.map.mousedown++;
        },true)
        YMaps.Events.observe(Map.map, Map.map.Events.SmoothZoomEnd,function(){
          self.counters.map.zoom++;
        });
        jQuery('#results .result-holder').bind('scroll',function(){
          self.counters.scroll.results++;
        })
        jQuery(window).bind('scroll',function(){
          self.counters.scroll.page++;
        })
        jQuery('#top').bind('click',function(){
          self.counters.clickTop++;
        })
        jQuery('#bottom, #bottom a').bind('click',function(){
          self.counters.clickFooter++;
        })
      },
      balloonClick:function(data){
        var self = this; 
        var key = 0;
        if((key = self.memory.balloonClicks.indexOf(data))==-1){
          self.memory.balloonClicks.push(data);
          self.counters.balloonClicks.push({
            relevance:data.resultPoint.relevance,
            color:data.color,
            click:1
          })
        }else{
          self.counters.balloonClicks[key].click++;
        }

      },
      close:function(){
        var self = this;
        self.counters.timeTotal = Date.now() - startTime;
        self.counters.times = self.stopWatch.stop();
        if(self.counters.result.notWait){
          self.counters.result = {
            time   : Date.now() - startTime,
            status : self.searchStarted ? 'notWait' : 'notSearch',
            notWait: 1
          }
        }
        try{
          jQuery.ajax({
            url:self.conf.url,
            async:false,
            data:{csv:JSON.stringify(self.counters)}
          });
        }catch(e){};
      }
    }
    return new init();
  };
  var StopWatch= {
    arr:[],
    startTime:Date.now(),
    start:function(){
      this.arr.push({
        start:Date.now() - this.startTime
      })
    },
    stop:function(time){
      var last = this.arr.length ? this.arr[this.arr.length-1] : false;
      if(last && !last.end){
        last.end = Date.now() - this.startTime;
        if(time) last.end -= time;
      }
      return this.arr;
    }
  };
  observer = new Observer();
  jQuery(window).bind('unload',function(){observer.close() });
})();

