/*
 * @require Prototype 1.6+
 * @require PrototypeExtensions 0.1.2+
 */

if (typeof poiskn == 'undefined')
  poiskn = {};

// script.aculo.us slider.js v1.8.1, Thu Jan 03 22:07:12 -0500 2008

// Copyright (c) 2005-2007 Marty Haught, Thomas Fuchs 
//
// script.aculo.us is freely distributable under the terms of an MIT-style license.
// For details, see the script.aculo.us web site: http://script.aculo.us/

if (!Control) var Control = { };

// options:
//  axis: 'vertical', or 'horizontal' (default)
//
// callbacks:
//  onChange(value)
//  onSlide(value)
Control.Slider = Class.create({
  initialize: function(handle, track, options) {
    var slider = this;
    
    if (Object.isArray(handle)) {
      this.handles = handle.collect( function(e) { return $(e) });
    } else {
      this.handles = [$(handle)];
    }
    
    this.track   = $(track);
    this.options = options || { };

    this.axis      = this.options.axis || 'horizontal';
    this.increment = this.options.increment || 1;
    this.step      = parseInt(this.options.step || '1');
    this.range     = this.options.range || $R(0,1);
    
    this.value     = 0; // assure backwards compat
    this.values    = this.handles.map( function() { return 0 });
    this.spans     = this.options.spans ? this.options.spans.map(function(s){ return $(s) }) : false;
    this.options.startSpan = $(this.options.startSpan || null);
    this.options.endSpan   = $(this.options.endSpan || null);

    this.restricted = this.options.restricted || false;

    this.maximum   = this.options.maximum || this.range.end;
    this.minimum   = this.options.minimum || this.range.start;

    // Will be used to align the handle onto the track, if necessary
    this.alignX = parseInt(this.options.alignX || '0');
    this.alignY = parseInt(this.options.alignY || '0');
    
    this.trackLength = this.maximumOffset() - this.minimumOffset();

    this.handleLength = this.isVertical() ? 
      (this.handles[0].offsetHeight != 0 ? 
        this.handles[0].offsetHeight : this.handles[0].style.height.replace(/px$/,"")) : 
      (this.handles[0].offsetWidth != 0 ? this.handles[0].offsetWidth : 
        this.handles[0].style.width.replace(/px$/,""));

    this.active   = false;
    this.dragging = false;
    this.disabled = false;

    if (this.options.disabled) this.setDisabled();

    // Allowed values array
    this.allowedValues = this.options.values ? this.options.values.sortBy(Prototype.K) : false;
    if (this.allowedValues) {
      this.minimum = this.allowedValues.min();
      this.maximum = this.allowedValues.max();
    }

    this.eventMouseDown = this.startDrag.bindAsEventListener(this);
    this.eventMouseUp   = this.endDrag.bindAsEventListener(this);
    this.eventMouseMove = this.update.bindAsEventListener(this);

    // Initialize handles in reverse (make sure first handle is active)
    this.handles.each( function(h,i) {
      i = slider.handles.length-1-i;
      slider.setValue(parseFloat(
        (Object.isArray(slider.options.sliderValue) ? 
          slider.options.sliderValue[i] : slider.options.sliderValue) || 
         slider.range.start), i);
      h.makePositioned().observe("mousedown", slider.eventMouseDown);
    });
    
    this.track.observe("mousedown", this.eventMouseDown);
    document.observe("mouseup", this.eventMouseUp);
    document.observe("mousemove", this.eventMouseMove);
    
    this.initialized = true;
  },
  dispose: function() {
    var slider = this;    
    Event.stopObserving(this.track, "mousedown", this.eventMouseDown);
    Event.stopObserving(document, "mouseup", this.eventMouseUp);
    Event.stopObserving(document, "mousemove", this.eventMouseMove);
    this.handles.each( function(h) {
      Event.stopObserving(h, "mousedown", slider.eventMouseDown);
    });
  },
  setDisabled: function(){
    this.disabled = true;
  },
  setEnabled: function(){
    this.disabled = false;
  },  
  getNearestValue: function(value){
    if (this.allowedValues){
      if (value >= this.allowedValues.max()) return(this.allowedValues.max());
      if (value <= this.allowedValues.min()) return(this.allowedValues.min());
      
      var offset = Math.abs(this.allowedValues[0] - value);
      var newValue = this.allowedValues[0];
      this.allowedValues.each( function(v) {
        var currentOffset = Math.abs(v - value);
        if (currentOffset <= offset){
          newValue = v;
          offset = currentOffset;
        } 
      });
      return newValue;
    }
    if (value > this.range.end) return this.range.end;
    if (value < this.range.start) return this.range.start;
    return value;
  },
  setValue: function(sliderValue, handleIdx){
    if (!this.active) {
      this.activeHandleIdx = handleIdx || 0;
      this.activeHandle    = this.handles[this.activeHandleIdx];
      this.updateStyles();
    }
    handleIdx = handleIdx || this.activeHandleIdx || 0;
    if (this.initialized && this.restricted) {
      if ((handleIdx>0) && (sliderValue<this.values[handleIdx-1]))
        sliderValue = this.values[handleIdx-1];
      if ((handleIdx < (this.handles.length-1)) && (sliderValue>this.values[handleIdx+1]))
        sliderValue = this.values[handleIdx+1];
    }
    sliderValue = this.getNearestValue(sliderValue);
    this.values[handleIdx] = sliderValue;
    this.value = this.values[0]; // assure backwards compat
    
    this.handles[handleIdx].style[this.isVertical() ? 'top' : 'left'] = 
      this.translateToPx(sliderValue);
    
    this.drawSpans();
    if (!this.dragging || !this.event) this.updateFinished();
  },
  setValueBy: function(delta, handleIdx) {
    this.setValue(this.values[handleIdx || this.activeHandleIdx || 0] + delta, 
      handleIdx || this.activeHandleIdx || 0);
  },
  translateToPx: function(value) {
    return Math.round(
      ((this.trackLength-this.handleLength)/(this.range.end-this.range.start)) * 
      (value - this.range.start)) + "px";
  },
  translateToValue: function(offset) {
    return ((offset/(this.trackLength-this.handleLength) * 
      (this.range.end-this.range.start)) + this.range.start);
  },
  getRange: function(range) {
    var v = this.values.sortBy(Prototype.K); 
    range = range || 0;
    return $R(v[range],v[range+1]);
  },
  minimumOffset: function(){
    return(this.isVertical() ? this.alignY : this.alignX);
  },
  maximumOffset: function(){
    return(this.isVertical() ? 
      (this.track.offsetHeight != 0 ? this.track.offsetHeight :
        this.track.style.height.replace(/px$/,"")) - this.alignY : 
      (this.track.offsetWidth != 0 ? this.track.offsetWidth : 
        this.track.style.width.replace(/px$/,"")) - this.alignX);
  },  
  isVertical:  function(){
    return (this.axis == 'vertical');
  },
  drawSpans: function() {
    var slider = this;
    if (this.spans)
      $R(0, this.spans.length-1).each(function(r) { slider.setSpan(slider.spans[r], slider.getRange(r)) });
    if (this.options.startSpan)
      this.setSpan(this.options.startSpan,
        $R(0, this.values.length>1 ? this.getRange(0).min() : this.value ));
    if (this.options.endSpan)
      this.setSpan(this.options.endSpan, 
        $R(this.values.length>1 ? this.getRange(this.spans.length-1).max() : this.value, this.maximum));
  },
  setSpan: function(span, range) {
    if (this.isVertical()) {
      span.style.top = this.translateToPx(range.start);
      span.style.height = this.translateToPx(range.end - range.start + this.range.start);
    } else {
      span.style.left = this.translateToPx(range.start);
      span.style.width = this.translateToPx(range.end - range.start + this.range.start);
    }
  },
  updateStyles: function() {
    this.handles.each( function(h){ Element.removeClassName(h, 'selected') });
    Element.addClassName(this.activeHandle, 'selected');
  },
  startDrag: function(event) {
    if (Event.isLeftClick(event)) {
      if (!this.disabled){
        this.active = true;
        
        var handle = Event.element(event);
        var pointer  = [Event.pointerX(event), Event.pointerY(event)];
        var track = handle;
        if (track==this.track) {
          var offsets  = Position.cumulativeOffset(this.track); 
          this.event = event;
          this.setValue(this.translateToValue( 
           (this.isVertical() ? pointer[1]-offsets[1] : pointer[0]-offsets[0])-(this.handleLength/2)
          ));
          var offsets  = Position.cumulativeOffset(this.activeHandle);
          this.offsetX = (pointer[0] - offsets[0]);
          this.offsetY = (pointer[1] - offsets[1]);
        } else {
          // find the handle (prevents issues with Safari)
          while((this.handles.indexOf(handle) == -1) && handle.parentNode) 
            handle = handle.parentNode;
            
          if (this.handles.indexOf(handle)!=-1) {
            this.activeHandle    = handle;
            this.activeHandleIdx = this.handles.indexOf(this.activeHandle);
            this.updateStyles();
            
            var offsets  = Position.cumulativeOffset(this.activeHandle);
            this.offsetX = (pointer[0] - offsets[0]);
            this.offsetY = (pointer[1] - offsets[1]);
          }
        }
      }
      Event.stop(event);
    }
  },
  update: function(event) {
   if (this.active) {
      if (!this.dragging) this.dragging = true;
      this.draw(event);
      if (Prototype.Browser.WebKit) window.scrollBy(0,0);
      Event.stop(event);
   }
  },
  draw: function(event) {
    var pointer = [Event.pointerX(event), Event.pointerY(event)];
    var offsets = Position.cumulativeOffset(this.track);
    pointer[0] -= this.offsetX + offsets[0];
    pointer[1] -= this.offsetY + offsets[1];
    this.event = event;
    this.setValue(this.translateToValue( this.isVertical() ? pointer[1] : pointer[0] ));
    if (this.initialized && this.options.onSlide)
      this.options.onSlide(this.values.length>1 ? this.values : this.value, this);
  },
  endDrag: function(event) {
    if (this.active && this.dragging) {
      this.finishDrag(event, true);
      Event.stop(event);
    }
    this.active = false;
    this.dragging = false;
  },  
  finishDrag: function(event, success) {
    this.active = false;
    this.dragging = false;
    this.updateFinished();
  },
  updateFinished: function() {
    if (this.initialized && this.options.onChange) 
      this.options.onChange(this.values.length>1 ? this.values : this.value, this);
    this.event = null;
  }
});

/**
 *
 * Taken from http://www.quirksmode.org/js/cookies.html
 *
 */
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}


/*
 pn-range.js v1.0

 Copyright (c) 2008 http://www.meremyanin.com
 Author: Vladimir Meremyanin

 An extension to script.aculo.us's Slider.

*/

var PNRange = Class.create(Control.Slider, {

  initialize: function($super, handles, inputs, track, options) {
      if (handles.length != 2 || inputs.length != 2) {
        throw 'PNRange accepts only 2 handles and 2 inputs';
      }
      options = options || {};
      this.inputs = $A(inputs).map(function(e) {return $(e)});
      options['onSlide'] = options['onSlide'] || this.slideHandler.bind(this);
      this.inputs.each(function(input, i) {
        Event.observe(input, 'change', function() {
          this.setValue($F(input), i);
        }.bind(this));
      }.bind(this));
      options['restricted'] = true;
      $super(handles, track, options);
      this.handleLength = 1; //this.handles[0].getWidth();
    },

  setValue: function($super, val, idx) {
    if (this.initialized && Object.isUndefined(idx) && !this.dragging) {
      idx = this.values.inject({}, function(closest, handle_value, handle_index) {
        var cur = {
          distance: Math.abs(handle_value - val),
          index: handle_index
        };
        if (closest.distance && closest.distance < cur.distance) {
          return closest;
        } else {
          if (closest.distance && closest.distance == cur.distance) {
            if (val > handle_value) {
              return (closest.index < cur.index) ? cur : closest;
            }
            else {
              return (closest.index > cur.index) ? cur : closest;
            }
          } else {
            return cur;
          }
        }
      }).index;
      this.activeHandleIdx = idx;
      this.activeHandle = this.handles[idx];
      this.updateStyles();
    }
    $super(val, idx);
  },

  setValues: function(min, max) {
    var good_onchange = this.options.onChange;
    this.options.onChange = null;
    this.setValue(min, 0);
    this.options.onChange = good_onchange;
    this.setValue(max, 1);
  },

  slideHandler: function() {
    this.inputs.each(function(input, i) {
      $(input).value = this.values[i];
    }.bind(this));
  }

});

PNRange.map_slider_value = function(values, x) {
  return values[Math.round(x)];
}
PNRange.antimap_slider_value = function(values, x) {
  for (var i = 0; i < values.length; i++) {
    if (values[i] >= x) {
      return i;
    }
  }
  return values.length-1;
}


/**
 * @author    Roland Franssen <franssen.roland@gmail.com>
 * @website   http://code.google.com/p/prototype-dialog/
 * @copyright 2008 http://roland.devarea.nl/dialog/
 * @license   http://creativecommons.org/licenses/by-nd/3.0/
 * @version   2.0
 */

var Dialogs = {
	Lang:{
		close:   '&nbsp;&times;&nbsp;',
		prev:    '&laquo; Previous',
		next:    'Next &raquo;',
		loading: 'Loading...',
		ok:      'OK',
		yes:     'Yes',
		no:      'No'
	},
	Default:{
		handle:          null,                   // css rule | element | null
		background:     ['#000', '#fff'],        // array
		width:          'auto',                  // auto | max | integer
		height:         'auto',                  // auto | max | integer
		minWidth:       null,                    // null | pixel value
		minHeight:      null,                    // null | pixel value
		innerScroll:    false,                    // true | false
		opacity:        .75,                     // float | false
		margin:         10,                      // integer
		padding:        10,                      // integer
		title:          null,                    // string | null
		className:      null,                    // string | null
		content:        null,                    // string | element | array | object | function
		iframe:         null,                    // string | null
		target:{
		  id:           null,                    // string | null
		  auto:         true                     // true | false
		},
		ajax:{
		  url:          null,                    // string | null
		  jsonTemplate: null,                    // interpolation template string | null
		  options:      {}                       // default ajax options
		},
		close:{
		  link:         true,                    // true | false
		  esc:          true,                    // true | false
		  overlay:      true                     // true | false
		},
		afterOpen:      Prototype.emptyFunction, // function
		afterClose:     Prototype.emptyFunction, // function
		afterClick:     Prototype.emptyFunction  // function
	},
	Browser:{
		IE6:(Prototype.Browser.IE && parseInt(navigator.appVersion) == 4 && navigator.userAgent.toLowerCase().indexOf('msie 6.') != -1)
	}
};

eval(function(p,a,c,k,e,d){e=function(c){return(c<a?"":e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('9.1r(4,{1L:11,12:11,Y:{L:[\'X\',\'G-L\',\'2z\'],14:[\'X\',\'G-14\',\'2z\'],q:[\'X\',\'G-q\'],1G:[\'X\',\'G-1G\'],E:[\'X\',\'G-E\'],17:[\'X\',\'G-17\'],R:[\'2A\',\'G-R\'],j:[\'a\',\'G-j\'],15:[\'a\',1s,\'15\'],19:[\'a\',1s,\'19\'],1j:[\'2A\',1s,\'1j\']},1e:{Q:4.1M.1N,1c:4.1M.1N},1f:8(){g 1f=1l.3B,28=1f.1W(),1H={r:28.r,u:28.u};5(4.1e.Q){g Q=1f.2K();1H.E=Q.E;1H.W=Q.W}O 1H},7:8(7){O 4.Y[7]},1O:8(){5(!!4.1L)O;4.1L=I;g e=4.Y;2d(g x 2h e){g d=e[x],a={18:\'25:24\'};5(d[1])a[\'1w\']=d[1];5(d[2])a[\'1F\']=d[2];2L(d[0]){3x\'a\':a[\'2M\']=\'2N:;\';2O}g 1h=N 1d(d[0],a);5(4.1m[x])1h.10(4.1m[x]);4.Y[x]=1h}1l.B(\'3m:39\',8(){g e=4.Y;$(1l.2R).A(e[\'L\']).A(e[\'14\'].A(e[\'E\'].A(e[\'R\']).A(e[\'j\'])).A(e[\'q\']).A(e[\'17\'].A(e[\'19\']).A(e[\'1j\']).A(e[\'15\'])));5(4.1M.1N)e[\'E\'].A(N 1d(\'X\',{18:\'2S:2T\'}))})},j:8(){[4.7(\'R\'),4.7(\'q\'),4.7(\'1j\')].H(\'10\',\'\');2d(g x 2h 4.Y)4.Y[x].1k(\'18\',\'25:24\');4.7(\'14\').C(\'1g:-2i 0 0 -2i\');5(4.1e.1c)$$(\'1c.G-1U\').H(\'J\').H(\'2W\',\'G-1U\');4.12=11},2j:8(s){g o=N 1d(\'27\',{1P:4.1m.2X,26:\'1R\'}),a=N 1y({1F:\'2j\',j:{1n:11,2t:I},1q:20,q:8(){o.B(\'Z\',4.j);O[s,\'<1D /><1D />\',o]},1A:8(){o.2n()}});a.1p()},2k:8(s,23,1S){g y=N 1d(\'27\',{1P:4.1m.2Y,26:\'1R\'}),n=N 1d(\'27\',{1P:4.1m.2Z,26:\'1R\'}),c=N 1y({1F:\'2k\',j:{1n:11},1q:20,q:8(){y.B(\'Z\',8(){5(9.U(23))23();4.j()});n.B(\'Z\',8(){5(9.U(1S))1S();4.j()});O[s,\'<1D /><1D />\',y,n]},1A:8(){y.2n()}});c.1p()}});4.1O(I);g 1y=31.32();1y.33={3i:8(6){3.6=9.1r(9.34(4.35),6||{});g c=3.6.q;5(9.U(c))9.1r(3.6,{q:c()});c=3.6.q;5(9.P(3.6.1x.1w)||9.1v(3.6.1x.1w)){g b=$(3.6.1x.1w);9.1r(3.6,{q:b.36});5(3.6.1x.F){g a=/#(.+)$/.S(1Y.37);5(9.21(a)&&9.P(a[1])){a=a[1].38(\',\').3a();5(a==b.2e())3.1p.1t(3).3b(1)}}}M 5(9.2u(c))3.z={i:0,k:c.3c(),v:c.3d(),m:c.3f()};3.2q()},S:8(2p){O 4.12==3.12&&4.7(\'L\').K()&&2p},2q:8(){1b.B(1Y,\'3h\',3.1i.T(3));5(4.1e.Q)1b.B(1Y,\'Q\',3.2a.T(3));g 1o=[];5(9.1v(3.6.V))1o.2r($(3.6.V));M 5(9.21(3.6.V))3.6.V.22(8(V){1o.2r($(V))});M 5(9.P(3.6.V))1o=$$(3.6.V);1o.H(\'B\',\'Z\',8(e){e.3k();5(!4.7(\'L\').K()){5(9.U(3.6.2s))3.6.2s(e);3.1p()}}.T(3));4.7(\'j\').B(\'Z\',8(){5(3.S(3.6.j.1n))3.j()}.T(3));4.7(\'L\').B(\'Z\',8(){5(3.S(3.6.j.L))3.j()}.T(3));1l.B(\'3l\',8(e){5(3.S(3.6.j.2t&&(e.1X||e.1V)==1b.3n))3.j()}.T(3));5(3.z){[4.7(\'19\'),4.7(\'15\')].H(\'B\',\'Z\',3.1T.T(3));1l.B(\'3o\',8(e){g c=e.1X||e.1V;5(3.S((c==1b.3p)||(c==1b.2o)))3.1T(e)}.T(3))}},2v:8(){3.F={1a:0};g t=4.7(\'R\'),c=4.7(\'j\');[t,c].H(\'C\',\'1C:24\');$w(\'E q 17\').22(8(b){g c=4.7(b);5(!c.K())3.F[b]={r:0,u:0};M{c.1k(\'18\',\'25:3q;1C:W;29:K;3r-3s:3t\');3.F[b]=c.1W();c.1k(\'18\',\'29:3u\');5(b==\'q\')3.F[b].r+=(13(3.6.1q)||0)*2;5(3.F[b].r>3.F.1a)3.F.1a=3.F[b].r}}.1t(3));t.C(\'1C:W\');c.C(\'1C:3v\')},1i:8(){5(!3.S(I))O;3.2v();g a=3.F,d=4.1f(),t=4.7(\'q\'),c=4.7(\'14\'),o={m:((13(3.6.1g)||0)*2),p:((13(3.6.1q)||0)*2),t:a.E.u,b:a.17.u},m={r:(d.r-o.m),u:(d.u-o.m-o.t-o.b)},h=3.6.u,w=3.6.r,x=y=11;5(9.1E(w))w+=o.p;5(w==\'1a\')w=m.r;5(!9.1E(w))w=a.1a;5(w<(3.6.2w||0))w=3.6.2w||0;5(w>m.r){w=m.r;x=I}t.C(\'r:\'+(w-o.p)+\'D;u:F\');5(9.1E(h))h+=o.p;5(h==\'1a\')h=m.u;5(!9.1E(h))h=t.3z()+o.p;5(h<(3.6.2x||0))w=3.6.2x||0;5(h>m.u){h=m.u;y=I}t.C(\'u:\'+(h-o.p)+\'D;1q:\'+(o.p/2)+\'D\');5(3.6.3A&&(x||y))t.C(\'29:Q\');g s={w:w,h:(h+o.t+o.b)};c.C(\'r:\'+s.w+\'D;u:\'+s.h+\'D;1g:-\'+13(s.h/2)+\'D 0 0 -\'+13(s.w/2)+\'D\');5(4.1e.Q){4.7(\'L\').C(\'r:\'+d.r+\'D;u:\'+d.u+\'D\');3.2a()}},2a:8(){5(!3.S(I))O;g v=4.1f(),c=4.7(\'14\'),d=c.1W(),t=v.E+13((v.u-d.u)/2),l=v.W+13((v.r-d.r)/2);c.C(\'1g:0;E:\'+t+\'D;W:\'+l+\'D\');4.7(\'L\').C(\'1g:\'+v.E+\'D 0 0 \'+v.W+\'D\')},1Z:8(){g l=4.7(\'1G\').J(),t=4.7(\'q\'),b=t.2B(\'#\'+l.2e());5(!9.1v(b))t.A(l)},2c:8(){3.1Z();g o=3.6.1I.2D||{},c=(o.1B&&9.U(o.1B)?o.1B:1s),a=8(t){g 1K=3.6.1I.2F;5(t.2g&&9.P(1K))4.7(\'q\').10(1K.2G(t.2g));M 4.7(\'q\').10(t.2H||\'\');3.1i();5(9.U(c))c(t)}.1t(3);9.1r(o,{1B:a});N 2P.2Q(3.6.1I.2b,o)},2f:8(){3.1Z();g f=N 1d(\'1J\',{2U:3.6.1J,2V:0});4.7(\'q\').A(f);f.B(\'1O\',8(){4.7(\'1G\').16();f.C(\'r:2l%;u:2l%\');3.1i()}.T(3))},1T:8(1u){5(!3.S(I))O;g m=3.z.m,s=11,n=4.7(\'15\'),p=4.7(\'19\');5((1u.1X||1u.1V)==1b.2o||1u.3e().3g(\'15\')){5(3.z.i<(m-1))s=I;5(s)++3.z.i;5(((3.z.i+1)>=m)&&n.K())n.16();5(((3.z.i-1)>=0)&&!p.K())p.J()}M{5(3.z.i>0)s=I;5(s)--3.z.i;5(((3.z.i-1)<0)&&p.K())p.16();5(((3.z.i+1)<=m)&&!n.K())n.J()}5(s)3.1Q()},1Q:8(){g c=3.6.q,t=4.7(\'q\');5(9.P(c)||9.1v(c))t.A(c);M 5(9.21(c))c.22(8(b){t.A(b)});M 5(9.2u(c)){g b=4.7(\'17\');t.10(\'\').A(3.z.v[3.z.i]);4.7(\'1j\').10(3.z.k[3.z.i]);5(!b.K()){b.3y().H(\'J\');b.J()}5(3.z.i<=0)4.7(\'19\').16();5(3.z.i>=(3.z.m-1))4.7(\'15\').16()}M 5(9.P(3.6.1I.2b))3.2c();M 5(9.P(3.6.1J))3.2f();3.1i.1t(3).2I()},1p:8(){5(4.1e.1c)$$(\'1c\').1c(8(1h){O 1h.K()}).H(\'16\').H(\'30\',\'G-1U\');5(9.P(3.6.R)||3.6.j.1n){5(9.P(3.6.R))4.7(\'R\').J().10(3.6.R);5(3.6.j.1n)4.7(\'j\').J();4.7(\'E\').J()}g o=4.7(\'L\'),c=4.7(\'14\'),t=4.7(\'q\');[o,c,t].H(\'J\');o.3C(3.6.3D||1).C({1z:3.6.1z[0]||\'#2E\'});c.1k(\'18\',\'W:2m%;E:2m%;1z:\'+(3.6.1z[1]||\'#3j\'));t.1k(\'3w\',3.6.1F||\'\');4.12=N 2C().2J();3.12=4.12;3.1Q();5(9.U(3.6.1A))3.6.1A()},j:8(){4.j();5(9.U(3.6.2y))3.6.2y()}};',62,226,'|||this|Dialogs|if|opt|elm|function|Object|||||||var|||close|||||||content|width|||height|||||steps|insert|observe|setStyle|px|top|auto|dialog|invoke|true|show|visible|overlay|else|new|return|isString|scroll|title|exec|bindAsEventListener|isFunction|handle|left|div|_elements|click|update|false|_open|parseInt|container|next|hide|bottom|style|prev|max|Event|select|Element|fix|view|margin|el|setDimensions|curr|writeAttribute|document|Lang|link|handles|open|padding|extend|null|bind|ev|isElement|id|target|Dialog|background|afterOpen|onComplete|float|br|isNumber|className|loading|data|ajax|iframe|tpl|_exec|Browser|IE6|load|value|setContent|button|n_call|setSteps|hideselect|keyCode|getDimensions|which|window|setLoad||isArray|each|y_call|none|display|type|input|dim|overflow|setScroll|url|setAjax|for|identify|setIframe|responseJSON|in|99999px|alert|confirm|100|50|focus|KEY_RIGHT|bool|attachEvents|push|afterClick|esc|isHash|setAuto|minWidth|minHeight|afterClose|fixed|span|down|Date|options|000|jsonTemplate|interpolate|responseText|defer|getTime|getScrollOffsets|switch|href|javascript|break|Ajax|Request|body|clear|both|src|frameborder|removeClassName|ok|yes|no|addClassName|Class|create|prototype|clone|Default|innerHTML|location|split|loaded|last|delay|keys|values|element|size|hasClassName|resize|initialize|fff|stop|keyup|dom|KEY_ESC|keydown|KEY_LEFT|inline|white|space|nowrap|hidden|right|class|case|childElements|getHeight|innerScroll|viewport|setOpacity|opacity'.split('|')))


/*
 * @require Prototype 1.6+
 * @optional cookies.js
 */

if (typeof poiskn == 'undefined')
  poiskn = {};

poiskn.Currency = Class.create({

  initialize: function(rate, template, display_name) {
    this.rate = rate;
    this.template = template;
    this.display_name = display_name;
  },

  printAmount: function(amount) {
    return this.template.interpolate({amount: amount});
  }

});

poiskn.Currency.from_id = function(id) {
  var id_map = {"1":"rur","2":"eur","3":"usd"};
  return poiskn.Currency[id_map[id]];
}

poiskn.Currency.rur = new poiskn.Currency(1, '#{amount}&nbsp;руб.', 'р.');
poiskn.Currency.eur = new poiskn.Currency(39.2901, '€#{amount}', '€');
poiskn.Currency.usd = new poiskn.Currency(30.6858, '$#{amount}', '$');

poiskn.Currency.current = poiskn.Currency.rur;
document.observe('dom:loaded', function() {
  if (typeof readCookie == 'function') {
    var currency_name = readCookie('poiskn.curr');
    if (currency_name && poiskn.Currency[currency_name]) {
      poiskn.Currency.setCurrent(poiskn.Currency[currency_name]);
    }
  }
})
poiskn.Currency.getCurrencyName = function(curr) {
  return ["rur","eur","usd"].find(function(currency_name) {
    if (curr == poiskn.Currency[currency_name]) {
      return currency_name;
    }
  });
}
poiskn.Currency.setCurrent = function(curr) {
  var currency_name = poiskn.Currency.getCurrencyName(curr);
  if (currency_name) {
    poiskn.Currency.current = curr;
    if (typeof createCookie == 'function') {
      createCookie("poiskn.curr", currency_name);
    }
    document.fire('poiskn:currency_changed');
  }
}

poiskn.Money = Class.create({

  initialize: function(amount, currency) {
    this.amount = amount;
    this.currency = currency;
  },

  convert: function(currency) {
    return new poiskn.Money(this.amount * this.currency.rate / currency.rate, currency);
  },

  toString: function() {
    return this.currency.printAmount(poiskn.nice_price(this.amount, true));
  },

  toCurrent: function() {
    return this.convert(poiskn.Currency.current);
  }

});



poiskn.SearchForm = Class.create({

  /**
    * Valid options are:
    *   - view_mode: 'map', or 'list'
    */
  initialize: function(options) {
    this.google_map = options['google_map'];
    if (!this.google_map) {
      throw 'The "google_map" option is required';
    }

    this.holder_element = $(options['element']);
    if (!this.holder_element) {
      throw 'The "element" option is required';
    }

    this.update_results_callback = options['update_results_callback'];
    if (!this.update_results_callback) {
      throw 'The "update_results_callback" option is required';
    }
    this.view_mode = options['view_mode'] || 'list';

    this.ready = false;
    this.sliders = $H();
    this.cache = $H();

    this.offersSearchUrl = "http://poiskn.ru/api/83dc2a72f19a24de0511189f412e80ca441433e9/latest/offers.json";

    if (typeof History != 'undefined') {
      History.Observer.start();
    }
  },

  show: function() {
    if (this.formElement) {
      this.formElement.show();
    } else {
      this.formElement = this._createFormElement();
    }

    google.maps.event.addListener(this.google_map, 'bounds_changed', this.boundsChangedHandler.bind(this));
  },

  observe: function(event, handler) {
    this.holder_element.observe(event, handler);
  },

  _createFormElement: function() {
    var form_el = new Element('form', {action: '#'});

    form_el.insert(this._createCollapsibleBlock('Площадь', {html: {'class': 'square_block'}}, function(div) {
  div.insert(new Element('p', {'class':'disabled'}).update('Нет данных</p>'))
}));

form_el.insert(this._createCollapsibleBlock('Категория земель', {html: {'class': 'square_block'}}, function(div) {
  var values = $A([{"value":"\u0437\u0435\u043c\u043b\u0438 \u0441/\u0445 \u043d\u0430\u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f","id":36},{"value":"\u0437\u0435\u043c\u043b\u0438 \u043d\u0430\u0441\u0435\u043b\u0435\u043d\u043d\u044b\u0445 \u043f\u0443\u043d\u043a\u0442\u043e\u0432","id":37},{"value":"\u0437\u0435\u043c\u043b\u0438 \u043e\u0441\u043e\u0431\u043e \u043e\u0445\u0440\u0430\u043d. \u0442\u0435\u0440\u0440\u0438\u0442\u043e\u0440\u0438\u0439","id":38},{"value":"\u0437\u0435\u043c\u043b\u0438 \u043f\u0440\u043e\u043c\u044b\u0448\u043b\u0435\u043d\u043d\u043e\u0441\u0442\u0438","id":39},{"value":"\u0437\u0435\u043c\u043b\u0438 \u043b\u0435\u0441\u043d\u043e\u0433\u043e \u0444\u043e\u043d\u0434\u0430","id":40},{"value":"\u0437\u0435\u043c\u043b\u0438 \u0432\u043e\u0434\u043d\u043e\u0433\u043e \u0444\u043e\u043d\u0434\u0430","id":41}]);
  values.each(function(v) {
    var p = new Element('p');
    var cat_id = 'cat_' + v.id;
    var checked = true;
    var inp = new Element('input', {'type': 'checkbox', 'name': 'search_filter[land_categories][]', 'value': v.id, 'id': cat_id});
    (History.get(cat_id) == 'unchecked') ? checked = false : null;
    inp.checked = checked;
    if (Prototype.Browser.IE) {
      (function(inp) {
        inp.checked = checked;
      }).defer(inp);
    }

    p.insert(inp);

    inp.observe('click', this.updateSearchResults.bind(this));
    inp.observe('click', function(){
      (History.get(cat_id) == 'unchecked') ? History.unset(cat_id) : History.set(cat_id, 'unchecked');
    });

    var observe_params_cat = {
      id: cat_id,
      onStateChange: function(value) {
        History.get(cat_id) == 'checked' ? $(cat_id).checked = true : $(cat_id).checked = false;
      }.curry(cat_id)
    }

    History.Registry.set(observe_params_cat);

    var label = new Element('label', {'for': inp.identify()}).update(v.value);
    p.insert(' ');
    p.insert(label);
    div.insert(p);
  }.bind(this))
}));



    form_el.insert(this._createCollapsibleBlock('Стоимость', {html: {'class': 'price_block'}}, function(div) {
      var currency_selector_div = new Element('div', {'class': 'currency_selector'});
      var currency_options = [{"value":"1","name":"\u0440."},{"value":"2","name":"\u20ac"},{"value":"3","name":"$"}];

      form_el.insert(new Element('input', {'type': 'hidden', 'name': 'search_filter[currency_id]', 'value': '1'}));

      var currency_selector_select = this._createSelect('_fake_currency_id', currency_options);
      currency_selector_div.insert(currency_selector_select);
      currency_selector_select.observe('change', function() {
        poiskn.Currency.setCurrent(poiskn.Currency.from_id($F(currency_selector_select)));
      }.bind(this));
      var syncCurrency = function() {
        currency_selector_select.selectedIndex = ["rur","eur","usd"].indexOf(poiskn.Currency.getCurrencyName(poiskn.Currency.current));
        this.sliders.get('price') && this.sliders.get('price').setValueBy(0);
      }.bind(this);
      document.observe('poiskn:currency_changed', syncCurrency);
      syncCurrency();

      div.insert(currency_selector_div);
      div.insert(new Element('p', {'class':'disabled'}).update('Нет данных</p>'))
    }));

    $w('lat_min lat_max lng_min lng_max').each(function(s) {
      form_el.insert(new Element('input', {'name': 'search_filter['+s+']', 'type': 'hidden', 'class': s}));
    })

    this.holder_element.insert(form_el);

    (function() {
      this.holder_element.fire('poiskn:form_added');
      this.ready = true;
      this.updateSearchResults();
    }).bind(this).defer();
    return form_el;
  },

  boundsChangedHandler: function() {
    if (!!this.bounds_changed_timeout) {
      window.clearTimeout(this.bounds_changed_timeout);
    }
    this.bounds_changed_timeout = this.updateSearchResults.bind(this).delay(0.333);
  },

  updateSearchResults: function(keep_cache) {
    if (this.ready) {
      if (!keep_cache) {
        this.cache = $H();
      }

      var b = this.google_map.getBounds();
      if (b == null) {
        return arguments.callee.bind(this).defer();
      }

      this.formElement.down('.lat_min').value = b.getSouthWest().lat();
      this.formElement.down('.lng_min').value = b.getSouthWest().lng();
      this.formElement.down('.lat_max').value = b.getNorthEast().lat();
      this.formElement.down('.lng_max').value = b.getNorthEast().lng();

      this.holder_element.fire('poiskn:before_update');

      poiskn._fetch_external(this.offersSearchUrl, $H(Form.serialize(this.formElement, true)).merge({object_type: 'land', 'search_filter[offer_variant]': '116', 'view_mode': this.view_mode, 'zoom': this.google_map.getZoom()}), function(offers) {
        this.cache.set(this.view_mode, offers);
        this.update_results_callback(offers, this.view_mode); /* XXX maybe should wrap in a try/catch? */
        this.holder_element.fire('poiskn:after_update');
      }.bind(this));
    }
  },

  toggleViewMode: function() {
    this.view_mode = (this.view_mode == 'map')? 'list' : 'map';
    if (this.cache.get(this.view_mode)) {
      this.update_results_callback(this.cache.get(this.view_mode), this.view_mode); /* XXX maybe should wrap in a try/catch? */
    } else {
      this.updateSearchResults(true);
    }
    return this.view_mode;
  },

  _createSlider: function(div, heights, values, name, nice_fx) {
    var slider_div = new Element('div', {'class': 'slider'});

    var slider_handle_min_div = new Element('div', {'class': 'handle left'})
    var slider_nice_min = new Element('span', {'class': 'nice_min'});
    slider_handle_min_div.insert(slider_nice_min);
    slider_div.insert(slider_handle_min_div);

    var slider_handle_max_div = new Element('div', {'class': 'handle right'})
    var slider_nice_max = new Element('span', {'class': 'nice_max'});
    slider_handle_max_div.insert(slider_nice_max);
    slider_div.insert(slider_handle_max_div);

    var slider_span = new Element('span', {'class': 'span'});
    slider_div.insert(slider_span);

    var frv_holder_div = new Element('div', {'class': 'frv_holder'});
    var factor = heights.max() > 0 ? (20.0/heights.max()) : 1.0;
    heights.each(function(val, i) {
      frv_holder_div.insert(new Element('div', {'class': 'frv'}).setStyle({'height': (val*factor + 1)+'px', 'left': (i*2)+'px'}))
    });
    slider_div.insert(frv_holder_div);

    var search_filter_min_field = new Element('input', {'type': 'hidden', 'name': 'search_filter['+name+'_min]'});
    slider_div.insert(search_filter_min_field);

    var search_filter_max_field = new Element('input', {'type': 'hidden', 'name': 'search_filter['+name+'_max]'});
    slider_div.insert(search_filter_max_field);

    var slider_map = PNRange.map_slider_value.curry(values);
    var slider_antimap = PNRange.antimap_slider_value.curry(values);
    var slider_show_nice = function(v_min, v_max) {
      slider_nice_min.update(nice_fx(search_filter_min_field.value = slider_map(v_min)));
      slider_nice_max.update(nice_fx(search_filter_max_field.value = slider_map(v_max)));
    }.bind(this);
    
    this.holder_element.observe('poiskn:form_added', function() {
      var filter_slider = new PNRange([slider_handle_min_div, slider_handle_max_div], [search_filter_min_field, search_filter_max_field], slider_div, {
          range: $R(0, values.length - 1),
          spans: [slider_span],
          onSlide: function(v){ slider_show_nice(v.min(), v.max()); },
          onChange: function(v){
                        History.set(name + '_slider_min', slider_map(v.min()));
                        History.set(name + '_slider_max', slider_map(v.max()));
                        slider_show_nice(v.min(), v.max()); 
                        this.updateSearchResults(); 
                    }.bind(this)
      });

      var good_onchange = filter_slider.options.onChange;
      filter_slider.options.onChange = null;
      
      filter_slider.setValue(slider_antimap(History.get(name + '_slider_min') ? History.get(name + '_slider_min') : values.min()), 0);
      filter_slider.setValue(slider_antimap(History.get(name + '_slider_max') ? History.get(name + '_slider_max') : values.max()), 1);
      filter_slider.options.onChange = good_onchange;

      /* TODO remove this veeery strange call */ 
      filter_slider.setValue(slider_antimap(History.get(name + '_slider_min') ? History.get(name + '_slider_min') : values.min()), 0);

      observe_params_min = {
                        id: name + '_slider_min',
                        onStateChange:  function(value) {
                                          filter_slider.setValues(slider_antimap(History.get(name + '_slider_min')), slider_antimap(History.get(name + '_slider_max')));
                                        }
                        }      

      History.Registry.set(observe_params_min);

      observe_params_max = {
                        id: name + '_slider_max',
                        onStateChange:  function(value) {
                                          filter_slider.setValues(slider_antimap(History.get(name + '_slider_min')), slider_antimap(History.get(name + '_slider_max')));
                                        }
                        }      

      History.Registry.set(observe_params_max);

      slider_span.setStyle({opacity: 0.4});
      this.sliders.set(name, filter_slider);
    }.bind(this));

    div.insert(slider_div);
    div.insert(new Element('div', {'class': 'clear'}));
  },

  /**
    * block is called with div as an argument
    */
  _createCollapsibleBlock: function(title, options, block) {
    var header = new Element('h4', {'class': (options.collapsed ? 'collapsed' : '')});
    header.update(title +'<i>↓</i>');

    Event.observe(header, 'click', function(event) {
      $(this).next().toggle();
      $(this).toggleClassName("collapsed")
    });

    var div_html_options = options.html || {};
    var div = new Element('div', div_html_options);
    div.addClassName('p');
    div.setStyle({'display': (options.collapsed ? 'none' : 'block')});
    block.call(this, div);

    return new Element('div').insert(header).insert(div);
  },

  _createSelect: function(name, options) {
    var select = new Element('select', {'name': name});
    $A(options).each(function(opt) {
      select.options[select.options.length] = new Option(opt.name, opt.value, opt.selected);
    })
    return select;
  }
});

poiskn.getOfferDetails = function(id, callback) {
  poiskn._fetch_external("http://poiskn.ru/offers/"+ id + ".json", {}, callback);
}

poiskn.openInfoWindow = function(google_map, options) {
  if (!poiskn.__info_window) {
    poiskn.__info_window = new google.maps.InfoWindow();
  } else {
    poiskn.__info_window.close();
  }
  poiskn.__info_window.setOptions(options);
  poiskn.__info_window.open(google_map);
}

/**
 * Valid options are:
 *   click_handler - callback to be called on offer click. offer and polygon are passed to it
 */
poiskn.showGenPlan = function(settlement_id, google_map, center_map, options) {
  poiskn._fetch_external("http://poiskn.ru/settlements/" + settlement_id +".json", {}, function(settlement) {

    if (settlement.gen_plan) {
      var bounds = new google.maps.LatLngBounds(new google.maps.LatLng(settlement.lat_min, settlement.lng_min), new google.maps.LatLng(settlement.lat_max, settlement.lng_max));
      if (center_map) {
        google_map.setCenter(bounds.getCenter());
        google_map.fitBounds(bounds);
      }
      new google.maps.GroundOverlay(settlement.gen_plan.url, bounds, {
        map: google_map,
        clickable: false
      });
    }

    if (settlement.offers.length > 0) {
      var click_handler = ((options && options['click_handler']) || function(params) {
        var offer = params.offer;
        var pgon = params.pgon;
        var booking_handler = params.booking_handler;

        var p_opts = {'style': 'margin: 0'};
        var div = new Element('div');
        div.insert(new Element('p', p_opts).update([
          '№'+ offer.number,
          poiskn.nice_square(offer.square || offer.land_square)
        ].join(' &nbsp; ')));
        if (offer.status == 'sold') {
          div.insert(new Element('p', p_opts).update('Участок продан'));
        } else {
          if (offer.status == 'booked') {
            div.insert(new Element('p', p_opts).update('Участок забронирован'));
          } else {
            div.insert(new Element('p', p_opts).update([
              new poiskn.Money(offer.price, poiskn.Currency.rur).toCurrent() +' за участок',
              new poiskn.Money(offer.price_for_are, poiskn.Currency.rur).toCurrent() +' за сотку'
            ].join(' <br/> ')));
             /***** TODO optimize it */
              var book_link = new Element('a', {href: '#', 'class': 'book-link'}).update('Забронировать');
              booking_handler(book_link);
              div.insert(book_link);
            
          }
        }
        poiskn.openInfoWindow(google_map, {content: div, position: new google.maps.LatLng(offer.lat, offer.lng)})

        return div;
      });

      $A(settlement.offers).each(function(offer) {
        var status_colors = {
          free: '#33cc33',
          booked: '#ddcc00',
          sold: '#cc3333'
        };
        var pts = $A(offer.map_points).map(function(p) {
          return new google.maps.LatLng(p.lat, p.lng);
        });
        pts.push(pts.first());
        var color = status_colors[offer.status];
        var pgon = new google.maps.Polygon({
          map: google_map,
          paths: pts,
          strokeColor: color,
          strokeWeight: 1.5,
          strokeOpacity: 0.5,
          fillColor: color,
          fillOpacity: 0.4
        });
        google.maps.event.addListener(pgon, 'mouseover', function(g) {
          g.setOptions({fillOpacity: 1});
        }.curry(pgon));
        google.maps.event.addListener(pgon, 'mouseout', function(g) {
          g.setOptions({fillOpacity: 0.4});
        }.curry(pgon));
        google.maps.event.addListener(pgon, 'click', click_handler.curry({
              offer: offer,
              pgon: pgon,
              booking_handler: function(book_link) {
                new Dialog({
                  'handle': book_link,
                  'title': 'Анкета бронирования',
                  'width': 640,
                  'height': 400,
                  'padding': 10,
                  'margin': 75,
                  'iframe': 'http://poiskn.ru/bookings/new?client_key=83dc2a72f19a24de0511189f412e80ca441433e9&compact=true&offer_id='+ offer.id
                });
              }
            }));
      })
    }
  });
  poiskn._load_css('http://poiskn.ru/stylesheets/dialog.2.0.css');
}

poiskn._callbacks = $H();
poiskn._fetch_external = function(url, params, callback) {
  if (!arguments.callee._counter) {
    arguments.callee._counter = 33;
  }
  var callback_id = arguments.callee._counter;
  arguments.callee._counter = callback_id + 1;

  var script = new Element("script");
  script.src = url + '?' + $H(params).merge({handler_id: callback_id}).toQueryString();
  script.type = "text/javascript";
  $$("head").first().appendChild(script);

  poiskn._callbacks.set(callback_id, {callback: callback, script_id: script.identify()});
}
poiskn._invoke_callback = function(callback_id, data) {
  var callback = poiskn._callbacks.unset(callback_id);
  if (callback) {
    callback.callback(data);
    $(callback.script_id).remove();
  }
}
poiskn._load_css = function(url, media) {
  // We are preventing loading a file already loaded
  var _links = document.getElementsByTagName("link");
  if (_links.length > 0 && _links["href"] == url) return;

  // Optional parameters check
  var _media = media === undefined || media === null ? "all" : media;

  var _elstyle = document.createElement("link");
  _elstyle.setAttribute("rel", "stylesheet");
  _elstyle.setAttribute("type", "text/css");
  _elstyle.setAttribute("media", _media);
  _elstyle.setAttribute("href", url);

  $$("head").first().appendChild(_elstyle);
}

//XXX remove this?
poiskn._round1 = function(x) {
  return Math.round(x);
}
poiskn.nice_square = function(x) {
  if (Math.abs(x) > 12000) {
    return poiskn._round1(x / 10000) +'&nbsp;га';
  } else {
    if (Math.abs(x) > 140) {
      return poiskn._round1(x / 100) +'&nbsp;сот.';
    } else {
      return poiskn._round1(x) +'&nbsp;м²';
    }
  }
}
poiskn.nice_meters = function(x, unit) {
  if (unit == null || unit == undefined) {
    unit = '&nbsp;м²';
  }
  return poiskn._round1(x) + '&nbsp;' + unit;
}
poiskn.pad3 = function(x) {
  return '0'.times(3 - x.toString().length) + x;
}
poiskn.nice_number = function(x) {
  var x = Math.round(100 * x) / 100.0;
  if (Math.floor(x) < x) {
    return poiskn.nice_number(Math.round(x));
  } else {
    if (Math.abs(x) > 1000) {
      return poiskn.nice_number(Math.floor(x / 1000)) +'&nbsp;'+ poiskn.pad3((Math.abs(x) % 1000));
    } else {
      return x;
    }
  }
}
poiskn.nice_price = function(x_orig, raw) {
  var x = raw ? x_orig : new poiskn.Money(x_orig, poiskn.Currency.rur).convert(poiskn.Currency.current).amount;
  return poiskn.nice_number(x);
}


poiskn.loadMapState = function(google_map, default_center, default_zoom) {
  var cv = readCookie('map_position');
  var center = default_center;
  var zoom = default_zoom;
  if (cv && cv.isJSON()) {
    var h = cv.evalJSON(true);
    if (h.c) { /* center */
      center = new google.maps.LatLng(h.c.lat, h.c.lng);
    }
    if (h.z) { /* zoom-zoom */
      zoom = h.z;
    }
    if (h.t) { /* map type */
      google_map.setMapTypeId(h.t);
    }
  }
  google_map.setCenter(center);
  google_map.setZoom(zoom);
}
poiskn.saveMapState = function(google_map) {
  var c = google_map.getCenter();
  var s = {
    c: {lat: c.lat(), lng: c.lng()},
    z: google_map.getZoom(),
    t: google_map.getMapTypeId()
  };
  createCookie("map_position", Object.toJSON(s));
}
poiskn.autosaveMapState = function(google_map, loadPrevious) {
  if(loadPrevious) {
    this.loadMapState(google_map);
  } else {
    this.saveMapState(google_map);
  }
  google.maps.event.addListener(google_map, 'bounds_changed', this.saveMapState.bind(this, google_map));
  google.maps.event.addListener(google_map, 'maptypeid_changed', this.saveMapState.bind(this, google_map));
}

