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 = {
		'default': function(x) {
			return this.htmlspecialchars(x);
		},
		'htmlspecialchars': function(x) {
			return x.toString().replace(/[<>"&']/g, function(a) {
				var b = {'<':'&lt;', '>':'&gt;', '"':'&quot;', '&': '&amp;', "'": '&#039;'};
				return b[a];
			});
		}
	}
	if (func) Object.extend(this.func, func);
}
Tpl.prototype.evaluate = function(arr) {
	if (typeof arr === 'undefined') arr = {};
	var level = 0;
	var levels = [{tag: '', render: true}];
	var lx = this.values[0];
	var length = (this.tags ? this.tags.length : 0);
	var arr2 = {};
	var counter2 = {};
	var arrays2 = {};
	for(var i = 0; i < length; i++) {
	try {
		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);
		}
		var pos = tag.lastIndexOf(' ');
		var param = '';
		if (pos != -1) {
			param = tag.substr(pos + 1);
			tag = tag.substr(0, pos);
		}
		var pos = tag.lastIndexOf('.');
		if (pos == -1) {
			var pos2 = tag.lastIndexOf('-');
			var tag_value = (pos2 == -1 ? arr[tag] : arr[tag.substr(0, pos2)][tag.substr(pos2 + 1)]);
		}
		else {
			var tag_value1 = arr2[tag.substr(0, pos)];
			var tag2 = tag.substr(pos + 1);
			if (tag2 === '') {
				var tag_value = counter2[tag.substr(0, pos)];
			}
			else {
				var pos2 = tag2.lastIndexOf('-');
//			var tag_value = (pos2 == -1 ? tag_value1[tag2] : tag_value1[tag2.substr(0, pos2)][tag2.substr(pos2 + 1)]);//+tag.substr(pos2 + 1));
				var tag_value = (pos2 == -1 ? tag_value1[tag2] : tag_value1[tag2.substr(0, pos2)][tag2.substr(pos2 + 1)]);//+tag.substr(pos2 + 1));
				//var tag_value = (pos2 == -1 ? tag_value1[tag.substr(pos + 1)] : tag_value1[tag.substr(pos + 1).substr(0, pos2)][tag.substr(pos2 + 1)]);
			}
		}
		if (op == '') {
			if (param) tag_value = eval('tag_value '+param);
			if (levels[level].render) lx += (tag_value == '0' || tag_value) ? this.func['default'](tag_value) : '';
		}
		else if (op == '-') {
			if (param) tag_value = eval('tag_value '+param);
			if (levels[level].render) lx += (tag_value == '0' || tag_value) ? tag_value : '';
		}
		else if (op == '!') {
			if (levels[level].render && this.func[tag]) lx += this.func[tag](arr);
		}
		else if (op == '/') {
			if (levels[level].tag == tag) {
				if (!levels[level].runTimes || levels[level].counter + 1 >= levels[level].runTimes || !levels[level].render)
					level--;
				else {
					levels[level].counter++;
					i = levels[level].startIndex;
					arr2[levels[level].tag] = levels[level].isobj ? arrays2[tag][levels[level].counter] : {};
					counter2[tag] = levels[level].counter;
				}
			}
		}
		else if (op == '@') {
			if (levels[level].tag != tag)	level++;
			levels[level] = {tag: tag, render: true, counter: 0, isobj: typeof tag_value == 'object', startIndex: i};
			if (levels[level].isobj) {
				arrays2[tag] = (tag_value.constructor == Array) ? tag_value : Utils.toArray(tag_value);
			}
			levels[level].runTimes = levels[level].isobj ? arrays2[tag].length : parseInt(tag_value);
			if (!levels[level - 1].render || !levels[level].runTimes) levels[level].render = false;
			arr2[tag] = (levels[level].isobj && levels[level].runTimes) ? arrays2[tag][0] : {};
			counter2[tag] = 0;
		}
		else if (op == '?') {
			if (param) {
				var tmparr = param.split(param.substr(0, 1));
				if (levels[level].render) lx += tag_value ? tmparr[1] : tmparr[2];
			}
			else {
				if (levels[level].tag != tag)	level++;
				levels[level] = {tag: tag, render: tag_value ? 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: tag_value ? false : true};
			if (!levels[level - 1].render) levels[level].render = false;
		}
		else if (this.func[op]) {
			if (levels[level].render) lx += this.func[op](tag_value, param);
		}
		if (levels[level].render) lx += this.values[i + 1];
	} catch(e) {}
	}
	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 = response.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+'")';}
}

var WindowUtilities = {  
	modalWins: [],
	isIE: window.ActiveXObject ? true : false,
	isKHTML: (!window.ActiveXObject && document.childNodes && !document.all && !navigator.taintEnabled),
	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 (this.isIE) 
		W = Math.max(document.documentElement.offsetWidth, document.documentElement.scrollWidth);
		else if (this.isKHTML) 
		  W = document.body.scrollWidth;
		else 
		  W = document.documentElement.scrollWidth;
		  
		if (this.isIE) 
		  H = Math.max(document.documentElement.offsetHeight, document.documentElement.scrollHeight);
		else if (this.isKHTML) 
		  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(exact){
    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(!exact && yScroll < windowHeight){
      pageHeight = windowHeight;
    } else { 
      pageHeight = yScroll;
    }

    // for small pages with total width less then width of the viewport
    if(!exact && xScroll < windowWidth){  
      pageWidth = windowWidth;
    } else {
      pageWidth = xScroll;
    }

    return {pageWidth: pageWidth ,pageHeight: pageHeight , windowWidth: windowWidth, windowHeight: windowHeight};
  },

  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, tween) {
    var windowScroll = WindowUtilities.getWindowScroll();    
    var pageSize = WindowUtilities.getPageSize();
	var left,top;
	el.style.position = 'absolute';
    el.style.display = 'block';
	top = Math.max(0, (pageSize.windowHeight - el.offsetHeight)/2+windowScroll.top);
    left = Math.max(0, (pageSize.windowWidth - el.offsetWidth)/2 + windowScroll.left);
	if (!tween) {
		el.style.top = parseInt(top) + 'px';
		el.style.left = parseInt(left) + 'px';
	}
	else if (tween.action == 'move') {
		el.style.top = windowScroll.top + 'px';
		el.style.left = windowScroll.left + 'px';
	}
	if (tween) {
		if (tween.action == 'move') Utils.effectMoveTo(el, left, top, tween.duration || 1000, tween.method);
		if (tween.action == 'appear') Utils.effectAppear(el, tween.duration || 1000, tween.method);
	}
  },
    
	createBodyElement: function(html, opt) {
		var win = $(document.createElement("div"));
		win.innerHTML = html;
		var els = Object.extend({display:'block', visibility:'hidden', position: 'absolute'}, opt || {});
		Element.setStyle(win, els);
		document.body.appendChild(win);
		return win;
	},

	createModal: function(html, opt, opt2, el, tween) {
		var pageSize = WindowUtilities.getPageSize();
		var isupdate = el ? true : false;
		if (el) {
			el.style.visibility = 'hidden';
			el.innerHTML = html;
		}
		else {
			var lightbox = this.createBodyElement('', Object.extend({background:'#666666', opacity:.5, left:'0px', top: '0px', width:'100%', height:pageSize.pageHeight+'px'}, opt2 || {}));
			WindowUtilities.modalWins.push(lightbox);
			el = this.createBodyElement(html, opt);
			WindowUtilities.modalWins.push(el);
		}
		$A(el.getElementsByClassName('draggable')).each(
			function(el2) { 
				new Draggable(el2, el, {rangeX: {min:0, max:pageSize.pageWidth - el.offsetWidth}, rangeY:{min:0, max:pageSize.pageHeight - el.offsetHeight}}); 
			}
		);
		WindowUtilities.centerEl(el, tween);
		if (!isupdate) lightbox.style.visibility = 'visible';
		el.style.visibility = 'visible';
		return el;
	},

	createWin: function(el, html, opt) {
		var pageSize = WindowUtilities.getPageSize();
		if (!el) el = this.createBodyElement(html, opt);
		else el.innerHTML = html;
		$A(el.getElementsByClassName('draggable')).each(
			function(el2) { 
				new Draggable(el2, el, {rangeX: {min:0, max:pageSize.pageWidth - el.offsetWidth}, rangeY:{min:0, max:pageSize.pageHeight - el.offsetHeight}}); 
			}
		);
		$A(el.getElementsByClassName('corclose')).each(
			function(el2) { 
				el2.onclick = function() { el.style.visibility = 'hidden'; }
			}
		);
//		WindowUtilities.centerEl(el);
		el.style.visibility = 'visible';
		return el;
	},
	
	destroyModal: function() {
		Element.remove(WindowUtilities.modalWins.pop());
		Element.remove(WindowUtilities.modalWins.pop());
	}
}

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() {
	var propX = (this.elementToDrag.style.right !== undefined && this.elementToDrag.style.right != '' && this.elementToDrag.style.right !== 'auto')
	this.propX =  propX ? 'right' : 'left';
	this.propXSign =  propX ? 1 : -1;
	var propY = (this.elementToDrag.style.bottom !== undefined && this.elementToDrag.style.bottom != '' && this.elementToDrag.style.bottom !== 'auto');
	this.propY = propY ? 'bottom' : 'top';
	this.propYSign =  propY ? 1 : -1;
   return {
    x: parseInt(this.elementToDrag.style[this.propX]),
    y: parseInt(this.elementToDrag.style[this.propY])
   };
  },
  
  drag: function(dx, dy) {
   this.value.x = this.calculatePos(this.value.x + dx * this.propXSign, this.rangeX);
   this.value.y = this.calculatePos(this.value.y + dy * this.propYSign, this.rangeY);
   this.onDrag();
  },
  
  defaultAction: function() {
   this.elementToDrag.style[this.propX] = this.value.x + 'px';
   this.elementToDrag.style[this.propY] = this.value.y + 'px';
  },
  
  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 = $A(document.getElementsByClassName('voteValue', element.parentNode)).pop();
   this.divTxt = $A(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
