var isOPERA = (navigator.userAgent.indexOf('Opera') >= 0) ? true : false;
var isIE = (document.all && !isOPERA) ? true : false;
var isDOM = (document.getElementById && !isIE) ? true : false;
var UNI_IMAGE_ROOT = './images/';
var UNI_IMAGE_1X1 = UNI_IMAGE_ROOT + '1x1.png';
var UNIMAP_ICON_DEFAULT_SHADOW = UNI_IMAGE_ROOT + 'markers/shadow.png';

// UTILS

function openWin(ahref, awidth, aheight, ascroll) {
	var lwidth = awidth || 800;
	var lheight = aheight || 600;
	var lscroll = ascroll || 'no';
	lwidth = Math.min(window.screen.width, lwidth);
	lheight = Math.min(window.screen.height, lheight);
	var lleft = (window.screen.width - lwidth) / 2;
	var ltop = (window.screen.height - lheight) / 2;
	window.open(ahref,'_blank','scrollbars='+lscroll+',fullscreen=no,width='+lwidth+',height='+lheight+',left='+lleft+',top='+ltop);
 }
	
function evalJSON(json) {
  try {
    if (json.match(/\s*{/)) return eval('('+json+')');
	else return eval('({'+json+'})');
  } catch (e) {
    return {};
  }
}

function Tpl(str, func) {
	var regtpl = /\[[^\[\]\s\w]?\w+\]/g;
	this.tags = str.match(regtpl);
	this.values = [];
	var length = (this.tags ? this.tags.length : 0);
	var lindex2 = 0;
	for(var i = 0; i < length; i++) {
		var lindex1 = str.indexOf(this.tags[i], lindex2);
		this.values.push(str.substring(lindex2, lindex1));
		lindex2 = lindex1 + this.tags[i].length;
	}
	this.values.push(str.substr(lindex2));
	this.func = func || {};
}
Tpl.prototype.evaluate = function(arr) {
	var level = 0;
	var levels = [{tag: '', render: true}];
	var lx = this.values[0];
	var length = (this.tags ? this.tags.length : 0);
	for(var i = 0; i < length; i++) {
		var op = this.tags[i].substr(1, 1);
		if ('?/:!'.indexOf(op) != -1 || this.func[op]) {
			var tag = this.tags[i].substr(2, this.tags[i].length - 3);
		}
		else {
			op = '';
			var tag = this.tags[i].substr(1, this.tags[i].length - 2);
		}
		if (op == '') {
			if (levels[level].render) lx += (arr[tag] == '0' || arr[tag]) ? arr[tag] : '';
		}
		else if (op == '!') {
			if (levels[level].render && this.func[tag]) lx += this.func[tag](arr);
		}
		else if (op == '/') {
			if (levels[level].tag == tag) level--;
		}
		else if (op == '?') {
			if (levels[level].tag != tag)	level++;
			levels[level] = {tag: tag, render: arr[tag] ? true : false};
			if (!levels[level - 1].render) levels[level].render = false;
		}
		else if (op == ':') {
			if (levels[level].tag != tag)	level++;
			levels[level] = {tag: tag, render: arr[tag] ? false : true};
			if (!levels[level - 1].render) levels[level].render = false;
		}
		else if (this.func[op]) {
			if (levels[level].render) lx += this.func[op](arr[tag]);
		}
		if (levels[level].render) lx += this.values[i + 1];
	}
	return lx;
}

var Updater = Class.create();
Updater.prototype = {
  initialize: function(url, params, ops) {
   Object.extend(this, ops || {});
			var that = this;
			new Ajax.Request(url || document.location.href, {
				method: 'post',
				parameters: params,
				onSuccess: function(transport) {
					var response = evalJSON(transport.responseText);
					if (response._status == 'ok') that.onOK(response);
			else if (response && response.error) that.onError(response);
			else that.alertError(transport.responseText);
				},
				onFailure: function() { that.onFatalError(); },
				onLoading: function(a) { if (that.onLoading) that.onLoading(a); },
	    onInteractive: function(a) { if (that.onInteractive) that.onInteractive(a); },
				onComplete: function(a) { if (that.onComplete) that.onComplete(a); }
			});
  },
		
		onOK: function(response) {
		},
		
		defaultError: function(response) {
			alert(response.error);
		},
		
		onError: function(response) {
			this.defaultError(response);
		},
		
		onFatalError: function() {
			alert('Connection failed');
		},

		alertError: function(error) {
			alert(error);
		}
}

function chStatus(img, url, params) {
	if (img.options) params.value = ((img.options.status == '1') ? '0' : '1');
	new Updater(url, params, {
		onOK: function(response) {
			img.src = response.image;
			if (!img.options) img.options = {}
			img.options.status = params.value;
		}
	});
}

// end of UTILS


// DHTML

function setTransparentImage(el, imgFile) {
	if (!isIE) el.src = imgFile;
	else {el.src = UNI_IMAGE_1X1;	el.style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale,src="'+imgFile+'")';}
}

// From mootools.net
// window.ie - will be set to true if the current browser is internet explorer (any).
// window.ie6 - will be set to true if the current browser is internet explorer 6.
// window.ie7 - will be set to true if the current browser is internet explorer 7.
// window.khtml - will be set to true if the current browser is Safari/Konqueror.
// window.webkit - will be set to true if the current browser is Safari-WebKit (Safari3)
// window.gecko - will be set to true if the current browser is Mozilla/Gecko.
if (window.ActiveXObject) window.ie = window[window.XMLHttpRequest ? 'ie7' : 'ie6'] = true;
else if (document.childNodes && !document.all && !navigator.taintEnabled) window.khtml = true;
else if (document.getBoxObjectFor != null) window.gecko = true;
{
  var array = navigator.userAgent.match(new RegExp(/AppleWebKit\/([\d\.\+]*)/));
  window.webkit =  array && array.length == 2 ? parseFloat(array[1]) >= 420 : false;
}

var WindowUtilities = {  
  maxZIndex: 0,
		modalWins: [],
		getWindowScroll: function() {
    var w = window;
      var T, L, W, H;
      L = window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft;
      T = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;

      if (window.ie) 
        W = Math.max(document.documentElement.offsetWidth, document.documentElement.scrollWidth);
  		else if (window.khtml) 
  		  W = document.body.scrollWidth;
  		else 
  		  W = document.documentElement.scrollWidth;
  		  
  		if (window.ie) 
  		  H = Math.max(document.documentElement.offsetHeight, document.documentElement.scrollHeight);
    	else if (window.khtml) 
    	  H = document.body.scrollHeight;
    	else
    	  H = document.documentElement.scrollHeight;
    	
      return { top: T, left: L, width: W, height: H };
  }, 
  //
  // getPageSize()
  // Returns array with page width, height and window width, height
  // Core code from - quirksmode.org
  // Edit for Firefox by pHaez
  //
  getPageSize: function(){
    var xScroll, yScroll;

    if (window.innerHeight && window.scrollMaxY) {  
      xScroll = document.body.scrollWidth;
      yScroll = window.innerHeight + window.scrollMaxY;
    } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
      xScroll = document.body.scrollWidth;
      yScroll = document.body.scrollHeight;
    } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
      xScroll = document.body.offsetWidth;
      yScroll = document.body.offsetHeight;
    }

    var windowWidth, windowHeight;

    if (self.innerHeight) {  // all except Explorer
      windowWidth = self.innerWidth;
      windowHeight = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
      windowWidth = document.documentElement.clientWidth;
      windowHeight = document.documentElement.clientHeight;
    } else if (document.body) { // other Explorers
      windowWidth = document.body.clientWidth;
      windowHeight = document.body.clientHeight;
    }  
    var pageHeight, pageWidth;

    // for small pages with total height less then height of the viewport
    if(yScroll < windowHeight){
      pageHeight = windowHeight;
    } else { 
      pageHeight = yScroll;
    }

    // for small pages with total width less then width of the viewport
    if(xScroll < windowWidth){  
      pageWidth = windowWidth;
    } else {
      pageWidth = xScroll;
    }

    return {pageWidth: pageWidth ,pageHeight: pageHeight , windowWidth: windowWidth, windowHeight: windowHeight};
  },

  disableScreen: function(contentWin, className, overlayId, overlayOpacity) {
    var that = this;
    overlayId = overlayId || 'overlay_modal';
				overlayOpacity = overlayOpacity || 0.5;
    WindowUtilities.initLightbox(overlayId, className, function() {that._disableScreen(className, overlayId, overlayOpacity, contentWin)});
  },

  _disableScreen: function(className, overlayId, overlayOpacity, contentWin) {
    var objBody = document.body;

    // prep objects
    var objOverlay = $(overlayId);

    var pageSize = WindowUtilities.getPageSize();

    // Hide select boxes as they will 'peek' through the image in IE, store old value
    WindowUtilities._hideSelect();
    if (contentWin) {
      WindowUtilities._showSelect(contentWin);
    }  
  
    // set height of Overlay to take up whole page and show
    objOverlay.style.height = (pageSize.pageHeight + 'px');
    objOverlay.style.display = 'none';
				objOverlay.setStyle({'opacity': overlayOpacity});
    if (0 && overlayId == "overlay_modal" && Window.hasEffectLib && Windows.overlayShowEffectOptions) {
      objOverlay.overlayOpacity = overlayOpacity;
      new Effect.Appear(objOverlay, Object.extend({from: 0, to: overlayOpacity}, Windows.overlayShowEffectOptions));
    }
    else
      objOverlay.style.display = "block";
  },
  
  enableScreen: function(id) {
    id = id || 'overlay_modal';
    var objOverlay =  $(id);
    if (objOverlay) {
      // hide lightbox and overlay
      if (0 && id == "overlay_modal" && Window.hasEffectLib && Windows.overlayHideEffectOptions)
        new Effect.Fade(objOverlay, Object.extend({from: objOverlay.overlayOpacity, to:0}, Windows.overlayHideEffectOptions));
      else {
        objOverlay.style.display = 'none';
        objOverlay.parentNode.removeChild(objOverlay);
      }
      
      // make select boxes visible using old value
      if (id != "__invisible__") 
        WindowUtilities._showSelect();
    }
  },

  _hideSelect: function(parentElement) {
    if (window.ie) {
//      id = id ==  null ? "" : "#" + id + " ";
//      $$(id + 'select').each(function(element) {
      $A(($(parentElement) || document.body).getElementsByTagName('select')).each(function(element) {
        element = $(element);
								if (! WindowUtilities.isDefined(element.oldVisibility)) {
          element.oldVisibility = element.style.visibility ? element.style.visibility : "visible";
          element.style.visibility = "hidden";
        }
      });
    }
  },
  
  _showSelect: function(parentElement) {
    if (window.ie) {
//      id = id ==  null ? "" : "#" + id + " ";
//      $$(id + 'select').each(function(element) {
      $A(($(parentElement) || document.body).getElementsByTagName('select')).each(function(element) {
        if (WindowUtilities.isDefined(element.oldVisibility)) {
          // Why?? Ask IE
          try {
            element.style.visibility = element.oldVisibility;
          } catch(e) {
            element.style.visibility = "visible";
          }
          element.oldVisibility = null;
        }
        else {
          if (element.style.visibility)
            element.style.visibility = "visible";
        }
      });
    }
  },

  isDefined: function(object) {
    return typeof(object) != "undefined" && object != null;
  },
  
  // initLightbox()
  // Function runs on window load, going through link tags looking for rel="lightbox".
  // These links receive onclick events that enable the lightbox display for their targets.
  // The function also inserts html markup at the top of the page which will be used as a
  // container for the overlay pattern and the inline image.
  initLightbox: function(id, className, doneHandler) {
    // Already done, just update zIndex
    if ($(id)) {
      Element.setStyle(id, {zIndex: WindowUtilities.maxZIndex + 1});
      WindowUtilities.maxZIndex++;
      doneHandler();
    }
    // create overlay div and hardcode some functional styles (aesthetic styles are in CSS file)
    else {
      var objBody = document.body;
      var objOverlay = document.createElement("div");
      objOverlay.setAttribute('id', id);
      objOverlay.style.backgroundColor = '#666666';
						objOverlay.style.display = 'none';
      objOverlay.style.position = 'absolute';
      objOverlay.style.top = '0';
      objOverlay.style.left = '0';
      objOverlay.style.zIndex = WindowUtilities.maxZIndex + 1;
      WindowUtilities.maxZIndex++;
      objOverlay.style.width = '100%';
      objBody.insertBefore(objOverlay, objBody.firstChild);
      if (window.khtml && id == "overlay_modal") {
        setTimeout(function() {doneHandler()}, 10);
      }
      else
        doneHandler();
    }    
  },
  
  setCookie: function(value, parameters) {
    document.cookie= parameters[0] + "=" + escape(value) +
      ((parameters[1]) ? "; expires=" + parameters[1].toGMTString() : "") +
      ((parameters[2]) ? "; path=" + parameters[2] : "") +
      ((parameters[3]) ? "; domain=" + parameters[3] : "") +
      ((parameters[4]) ? "; secure" : "");
  },

  getCookie: function(name) {
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
      begin = dc.indexOf(prefix);
      if (begin != 0) return null;
    } else {
      begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1) {
      end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
  },
		
  centerEl: function(el) {
    var windowScroll = WindowUtilities.getWindowScroll();    
    var pageSize = WindowUtilities.getPageSize();
				var left,top;
				el.style.position = 'absolute';
    el.style.display = 'block';
				top = (pageSize.windowHeight - el.offsetHeight)/2;
				top += windowScroll.top;
    left = (pageSize.windowWidth - el.offsetWidth)/2;
    left += windowScroll.left; 
				el.style.top = parseInt(top) + 'px';
    el.style.left = parseInt(left) + 'px';
  },
    
  showModal: function(el) {
			if (!el) return;
			WindowUtilities.disableScreen(el);
			document.getElementsByClassName('divtopr', el).each(
//			el.getElementsByClassName('divtopr').each(
				function(el2) { 
					el2.innerHTML = '<a href="" onclick="WindowUtilities.hideModal(); return false;">X</a>'; 
				}
			);
			el.getElementsByClassName('divtopc').each(
				function(el2) { 
					new Draggable(el2, el); 
				}
			);
			el.style.zIndex = WindowUtilities.maxZIndex;
			el.className = 'modalwin';
			WindowUtilities.modalWins.push(el);
			WindowUtilities.centerEl(el);
  },
		
		hideModal: function() {
			var win = WindowUtilities.modalWins.pop();
			win.hide();
			WindowUtilities.enableScreen();
		},
		
		moveElementToBody: function(el, els) {
			if (!el) return;
			var objBody = document.body;
			if (el.parentNode == objBody) return el;
			var win = document.createElement("div");
			win.innerHTML = el.innerHTML;
			win.setAttribute('id', el.getAttribute('id'));
			var els = Object.extend({display: 'none'}, els || {});
			Object.extend(win.style, els);
			win.className = el.className;
   objBody.insertBefore(win, objBody.firstChild);
			el.remove();
			return win;
		}
		
}

var Draggable = Class.create();
Draggable.prototype = {
  rangeX: {},
  rangeY: {},
  multipleX: 1,
  multipleY: 1,
		notified: 0,
		startValue: {},
  initialize: function(element, elementToDrag, ops) {
   this.element = element;
   this.elementToDrag = elementToDrag || element;
   element.onmousedown = this.startDrag.bindAsEventListener(this);
   Object.extend(this, ops || {});
  },
  
  remove: function() {
   this.element.onmousedown = null;
  },
  
  finishDrag: function() {
   document.onmouseup = null;
   document.onmousemove = null;
   this.onComplete();
  },
  
  onComplete: function() {
  },
  
  reset: function() {
			Object.extend(this.value, this.startValue);
			this.onDrag();
		},
		
		startDrag: function(e) {
			this.notified = 0;
   this.x = Event.pointerX(e);
   this.y = Event.pointerY(e);
   this.value = this.getValues();
			Object.extend(this.startValue, this.value);
   document.onmousemove = this.onMouseMove.bindAsEventListener(this);
   document.onmouseup = this.onMouseUp.bindAsEventListener(this);
   Event.stop(e);
  },
  
  onMouseMove: function(e) {
			if (!this.notified) {
				this.notified = 1;
				if (this.onDragStart) this.onDragStart();
			}
			var lx = Event.pointerX(e);
   var ly = Event.pointerY(e);
   var dx = this.x - lx;
   var dy = this.y - ly;
   this.x = lx;
   this.y = ly;
   this.drag(dx, dy);
   Event.stop(e);
  },

  onMouseUp: function(e) {
   this.finishDrag();
   Event.stop(e);
  },
    
  calculatePos: function(x, range) {
   if (!range) return x;
   if (range.min !== undefined) x = Math.max(x, range.min);
   if (range.max !== undefined) x = Math.min(x, range.max);
   return x;
  },
  
  getValues: function() {
   return {
    x: parseInt(this.elementToDrag.style.left),
    y: parseInt(this.elementToDrag.style.top)
   };
  },
  
  drag: function(dx, dy) {
   this.value.x = this.calculatePos(this.value.x - dx, this.rangeX);
   this.value.y = this.calculatePos(this.value.y - dy, this.rangeY);
   this.onDrag();
  },
  
  defaultAction: function() {
   this.elementToDrag.style.left = this.value.x;
   this.elementToDrag.style.top = this.value.y;
  },
  
  onDrag: function() {
   this.defaultAction();
  }

} 

var Slider = Class.create();
Object.extend(Slider.prototype, Draggable.prototype);
Object.extend(Slider.prototype, {
  initialize: function(element, elementToDrag, props) {
   this.element = element;
   this.elementToDrag = elementToDrag || element;
   element.onmousedown = this.startDrag.bindAsEventListener(this);
   this.divValue = document.getElementsByClassName('voteValue', element.parentNode).pop();
   this.divTxt = document.getElementsByClassName('voteTxt', element.parentNode).pop();
   Object.extend(this, props || {});
  },
  
  onDrag: function() {
   this.defaultAction();
   this.divTxt.innerHTML = Math.round(this.multipleX * this.value.x);
   this.divValue.style.width = this.value.x;
  }
});

// end of DHTML

// unimap

function UniMarker(point, ops) {
 this.point = point;
 this.title = '';
 this.text = '';
	this.icon = new GIcon(G_DEFAULT_ICON);
	this.icon.shadow = UNIMAP_ICON_DEFAULT_SHADOW;
	this.icon.shadowSize = new GSize(37, 34);
	this.onclick = function() {};
	this.onmouseover = function() {};
	this.onmouseout = function() {};
	Object.extend(this, ops || {});
	if (this.image) this.icon.image = this.image;
 this._onclick = this.onclick.bindAsEventListener(this);
 this._onmouseover = this.onmouseover.bindAsEventListener(this);
 this._onmouseout = this.onmouseout.bindAsEventListener(this);
}

if (window.GOverlay) Object.extend(UniMarker.prototype, GOverlay.prototype);
Object.extend(UniMarker.prototype, {
 initialize: function(map) {
  this.map = map;
		var zindex = GOverlay.getZIndex(this.point.lat());
		var div = document.createElement("div");
  div.style.position = "absolute";
  div.style.fontSize = "8pt";
  div.style.fontFamily = "Arial";
		div.style.zIndex = zindex;
  var img = document.createElement("img");
		setTransparentImage(img, this.icon.image);
  img.style.position = "absolute";
  img.style.left = 0;
  img.style.top = 0;
		img.style.width = this.icon.iconSize.width;
		img.style.height = this.icon.iconSize.height;
		div.appendChild(img);
  var span = document.createElement("div");
  span.style.position = "absolute";
  span.style.fontSize = "8pt";
  span.style.fontFamily = "Arial";
//	span.className = 'markerText';
  span.style.left = 0;
  span.style.top = 3;
  span.style.width = this.icon.iconSize.width;
		span.innerHTML = this.text;
  span.style.textAlign = "center";
		div.appendChild(span);
		
		map.getPane(G_MAP_MARKER_PANE).appendChild(div);

		var divMouse = document.createElement("div");
  divMouse.style.position = "absolute";
		divMouse.style.cursor = 'pointer';
		divMouse.style.width = this.icon.iconSize.width;
		divMouse.style.height = this.icon.iconSize.height;
		divMouse.style.backgroundColor = '#ffff00';
		divMouse.title = this.title;
		$(divMouse).setOpacity(0);

		map.getPane(G_MAP_FLOAT_PANE).appendChild(divMouse);
		Event.observe(divMouse, 'click', this._onclick);
		Event.observe(divMouse, 'mouseover', this._onmouseover);
		Event.observe(divMouse, 'mouseout', this._onmouseout);
		
  var shadow = document.createElement("img");
		setTransparentImage(shadow, this.icon.shadow);
  shadow.style.position = "absolute";
		shadow.style.width = this.icon.shadowSize.width;
		shadow.style.height = this.icon.shadowSize.height;
		shadow.style.zIndex = zindex;
		shadow.className = 'gmnoprint';
		map.getPane(G_MAP_MARKER_SHADOW_PANE).appendChild(shadow);

		if (this.draggable) {
   var that = this;
 		this._ondrag = new Draggable(divMouse, divMouse, {
 			onDragStart: function() {
 				if (that.ondragstart) that.ondragstart();
 			},
 			onDrag: function() {
 				this.defaultAction();
 				div.style.left = this.value.x;
 				div.style.top = this.value.y;
 				shadow.style.left = this.value.x;
 				shadow.style.top = this.value.y;
 			},
 			onComplete: function() {
 				that.point = that.map.fromDivPixelToLatLng(new GPoint(this.value.x + that.icon.iconAnchor.x, this.value.y + that.icon.iconAnchor.y));
 				that.redraw(1);
 				if (that.ondragend) that.ondragend();
 			}
 		});
  }

  this._visibility = 'visible';
  this.divEl = div;
		this.divMouse = divMouse;
		this.iconEl = img;
  this.shadowEl = shadow;
	},
	
	remove: function() {
		Event.stopObserving(this.divMouse, 'click', this._onclick);
		Event.stopObserving(this.divMouse, 'mouseover', this._onmouseover);
		Event.stopObserving(this.divMouse, 'mouseout', this._onmouseout);
  if (this._ondrag) this._ondrag.remove();
		this.divEl.parentNode.removeChild(this.divEl);
  this.divMouse.parentNode.removeChild(this.divMouse);
  this.shadowEl.parentNode.removeChild(this.shadowEl);
	},
	
	copy: function() {
  return new UniMarker(this.point, this);
	},
	
 redraw: function(force) {
  if (!force) return;

  var c1 = this.map.fromLatLngToDivPixel(this.point);

  this.divEl.style.left = (c1.x - this.icon.iconAnchor.x) + "px";
  this.divEl.style.top = (c1.y - this.icon.iconAnchor.y) + "px";

  this.divMouse.style.left = (c1.x - this.icon.iconAnchor.x) + "px";
  this.divMouse.style.top = (c1.y - this.icon.iconAnchor.y) + "px";
  var latlng = this.map.fromDivPixelToLatLng(new GPoint(c1.x, c1.y + 48));
		this.divMouse.style.zIndex = GOverlay.getZIndex(latlng.lat());

  this.shadowEl.style.left = (c1.x - this.icon.iconAnchor.x) + "px";
  this.shadowEl.style.top = (c1.y - this.icon.iconAnchor.y) + "px";
	},
	
	_changeVisibility: function(avisibility) {
		if (this._visibility == avisibility) return;
		this._visibility = avisibility;
		this.divEl.style.visibility = avisibility;
		this.divMouse.style.visibility = avisibility;
		this.shadowEl.style.visibility = avisibility;
	},
	
	show: function() {
		this._changeVisibility('visible');
	},
	
	hide: function() {
		this._changeVisibility('hidden');
	},
	
	isVisible: function() {
		return (this._visibility = 'visible');
	},
	
	openInfoWindowHtml: function(html) {
		this.map.openInfoWindowHtml(this.point, html, {noCloseOnClick: true});
	},
	
	openInfoWindow: function(node) {
		this.map.openInfoWindow(this.point, node, {noCloseOnClick: true});
	}
	
});

// end of unimap
