/*
	(c) 2007-2008 | http://olegrorovin.spb.ru/
	Author - Oleg Korovin (mail@olegrorovin.spb.ru)
*/


var isMSIE = (document.attachEvent != null);
var isGecko = (!document.attachEvent && document.addEventListener && 1) || 0;



/////////////////////////////////////////////////////////////////////////////////////////
function $(el){
	if (typeof el == 'string') el = document.getElementById(el);
	return el || null;
}

/*****************************************************************************************/
function $$(sTagName,elNode){
	return (elNode || document).getElementsByTagName(sTagName.toUpperCase());
}


/*****************************************************************************************/
function forChilds(elNode , fAct){
	if(elNode && elNode.childNodes && elNode.childNodes.length){
		iLength = elNode.childNodes.length;
		for(var i = 0 ; i < iLength ; i++ )
			if(elNode.childNodes[i] && elNode.childNodes[i].nodeType == 1)
				fAct(elNode.childNodes[i] , i);
	}
}




/////////////////////////////////////////////////////////////////////////////////////////
function reloadWindow(){
	window.location = window.location.href.split('#')[0] + '';
}

/*****************************************************************************************/
function getUrl(sUrl){
	sUrl = (sUrl || window.location.href) + '';
	sUrl = sUrl.split('#')[0] + '';

	if( sUrl.indexOf('http://') != -1)
		sUrl = sUrl.substr(7);
	sUrl = sUrl.substr( sUrl.indexOf('/') );
	return sUrl;
}

/*****************************************************************************************/
	function sendRequest(sUrl,oVals,iTimeLimit,fFunc){
		if(! JsHttpRequest ) return;

		var req = new JsHttpRequest();
		var tId = setTimeout( function(){ req.abort(); } , iTimeLimit * 1000 );

		req.onreadystatechange = function() {
			if (req.readyState == 4) {
            clearTimeout(tId);
				if(fFunc) fFunc( typeof req.responseJS == 'object' ? req.responseJS : null , req.responseText);
			}
		}

		req.open(null, sUrl, true);
		req.send(oVals);
	}








/////////////////////////////////////////////////////////////////////////////////////////
var Events = {

	obj		: null,

 /***************************************/
	init	: function(event){
		this.obj = event || window.event;
		return this.obj;
	},

 /***************************************/
	exec	: function(elThis,fFunc,elNode){
		var oEvThis = this;

		return function(e){
			var oThis = this;
			oEvThis.init(e);
			return	fFunc.apply(elThis,[e,(elNode || oThis)]);
		};
	},

 /***************************************/
	onload	: function(fFunc){
		this.add(window,'load',fFunc);
	},

 /***************************************/
	add		: function(elNode, sEvent, fFunc){
		if(isGecko){
			elNode.addEventListener(sEvent, fFunc, true);
		}
		else{
			elNode.attachEvent('on' + sEvent, fFunc);
		}
	},

 /***************************************/
	remove	: function(elNode, sEvent, fFunc){
		if(isGecko){
			elNode.removeEventListener(sEvent, fFunc, true);
		}
		else{
			elNode.detachEvent('on' + sEvent, fFunc);
		}
	},

 /***************************************/
	stop		: function(event){
		var evt = event || window.event;
		if(evt.preventDefault) evt.preventDefault();
		if(evt.stopPropagation) evt.stopPropagation();
		evt.cancelBubble = true;
		evt.returnValue = false;
		return false;
	},

 /***************************************/
	stopBubble	: function(event){
		var evt = event || window.event;
		if(evt.preventDefault){
			evt.stopPropagation();
		}
		else{
			evt.cancelBubble = true;
		}
	},

 /***************************************/
	target	: function(event){
		var evt = event || window.event;
		return (evt.target || evt.srcElement);
	},

 /***************************************/
	key	: function(event){
		var evt = event || window.event;
		return (evt.type == 'keypress' && evt.charCode ? evt.charCode : evt.keyCode);
	},

 /***************************************/
	within	: function(event,elNode){
		var evt = event || window.event;
		var elTarg = evt.target || evt.srcElement;

		while(elTarg){
			if(elTarg == elNode){
				return true;
			}
			elTarg = elTarg.parentNode;
		}
		return false;
	},

 /***************************************/
	type	: function(event){
		var evt = event || window.event;
		return evt.type;
	},

 /***************************************/
	after	: function(event,fFunc){
		this.stop(event);
		setTimeout(function(){fFunc()},10);
		return false;
	}
};






///////////////////////////////////////////////////////////////////////////////////////////////
var Styles = {

 /***************************************************************************/
	push : function(obj, styles) {
		for(var i in styles) {
			obj["_style"+ i] = obj.style[i] || "";
			obj.style[i] = styles[i];
		}
	},

 /***************************************************************************/
	pop : function(obj, styles) {
		for(var i = 0; i < styles.length; i++)
			obj.style[styles[i]] = obj["_style"+ styles[i]];
	},

 /***************************************************************************/
	get : function(obj, style, _int, intradix) {
		var dv = document.defaultView;
		if (dv && dv.getComputedStyle) {
		var value = dv.getComputedStyle(obj, '').getPropertyValue(style.replace(/[A-Z]/g,
				function(match, _char) {
					return "-" + match.toLowerCase();
				} )
			);
		} else if (obj.currentStyle)
			var value = obj.currentStyle[style];
		else
			var value = obj.style[style] || "";
		return _int ? (parseInt(value, intradix || 10) || 0) : value;
	},

 /***************************************************************************/
	getPureWidth : function(obj) {
		var gs = this.get;
		return obj.offsetWidth - gs(obj, "borderLeftWidth", 1) - gs(obj, "paddingLeft", 1) - gs(obj, "paddingRight", 1) - gs(obj, "borderRightWidth", 1);
	},


 /***************************************************************************/
	matchClass : function(oElement,sClassName){
		return oElement && oElement.className && oElement.className.match(new RegExp('(^|\\s+)' + sClassName + '($|\\s+)'));
	},

 /***************************************************************************/
	addClass : function(oElement,sClassName){
		if( oElement && !this.matchClass(oElement, sClassName) ){
			oElement.className += ' ' + sClassName;
		}
	},

 /***************************************************************************/
	removeClass : function(oElement,sClassName){
		if( oElement && oElement.className ){
			oElement.className = oElement.className.replace(new RegExp('(.*)(^|\\s+)(' + sClassName + ')($|\\s+)(.*)'), '$1$4$5').replace(/(^)\s/, '$1');
		}
	},

 /***************************************************************************/
	setClass : function(oElement,sClassName,bAdd){
		if(bAdd)
			this.addClass(oElement,sClassName);
		else
			this.removeClass(oElement,sClassName);
	},

 /***************************************************************************/
	opacity : function(elNode,iValue){
		if(elNode.runtimeStyle) {
			elNode.runtimeStyle.filter = 'Alpha(opacity=' + iValue + ')';
		}
		else {
			elNode.style.opacity = iValue / 100;
		}
	},

 /***************************************************************************/
	invis : function(elNode){
		elNode.style.visibility = 'hidden';
	},

 /***************************************************************************/
	vis : function(elNode){
		elNode.style.visibility = 'visible';
	},

 /***************************************************************************/
	show : function(elNode){
		elNode.style.display = '';
	},

 /***************************************************************************/
	hide : function(elNode){
		elNode.style.display = 'none';
	}

}



///////////////////////////////////////////////////////////////////////////////////////////////
var Cookie = {

 /***************************************************************************/
	get : function(sName){
		if(document.cookie){
			var c = document.cookie.match(new RegExp( escape(sName)+'=([^;]+)' , 'i'));
			if(c) return unescape( c[1] );
		}
		return '';
	},

 /***************************************************************************/
	set : function(sName,sValue,iExpireDays){
		var dExpDate = null;
		if( (iExpireDays = iExpireDays * 1) > 0 ){
			dExpDate = new Date();
			dExpDate = new Date( dExpDate.getFullYear() , dExpDate.getMonth(), dExpDate.getDate() + iExpireDays);
		}

		document.cookie = escape(sName) + '=' + escape(sValue || '') + (dExpDate ? '; expires=' + dExpDate.toGMTString() : '') + '; path=/';
	}
}




//////////////////////////////////////////////////////////////////////////////////////////////
function PeriodicalExecuter(callback, frequency) {
	this.callback = callback;
	this.frequency = frequency;
	this.currentlyExecuting = false;
	this.timer = null;

	this.registerCallback();
}

PeriodicalExecuter.prototype = {

 /***************************************************************************/
	registerCallback: function() {
		this.timer = setInterval(this.onTimerEvent(this), this.frequency * 1000);
	},

 /***************************************************************************/
	execute: function() {
		this.callback(this);
	},

 /***************************************************************************/
	stop: function() {
		if (!this.timer) return;
		clearInterval(this.timer);
		this.timer = null;
	},

 /***************************************************************************/
	onTimerEvent: function(_this) {
		return function(){
			if(!_this.currentlyExecuting){
		      try{
					_this.currentlyExecuting = true;
					_this.execute();
				}
				finally{
					_this.currentlyExecuting = false;
				}
			}
		}
	}
}




//////////////////////////////////////////////////////////////////////////////////////////////
function trim(sText){
	var sBeginExpr = /^\s+/;
	var sEndExpr = /\s+$/;

	sText = sText.replace( sBeginExpr , '');
	sText = sText.replace( sEndExpr , '');

	return sText;
}

/***************************************************************************/
function isEmail(sEmail){
	return (
		sEmail &&
		sEmail.indexOf('@') > 0 &&
		sEmail.toLowerCase().match(/^(?:[-a-z\d\+\*\/\?!{}`~_%&'=^$#]+(?:\.[-a-z\d\+\*\/\?!{}`~_%&'=^$#]+)*)@(?:[-a-z\d_]+\.){1,60}[a-z]{2,6}$/)
	) ? true : false;
}


/***************************************************************************/
function splitNumber(sNumber , sSplitter){
	sNumber = Math.ceil( sNumber * 1 || 0 ) + '';
	if( !sSplitter ) sSplitter = ' ';
	var
		iPos = sNumber.length - 3,
		sRez = '';

	while( iPos > 0 ){
		sRez = sSplitter + sNumber.substr(iPos,3) + sRez;
		iPos -= 3;
	}
	sRez = sNumber.substr(0,iPos + 3) + sRez;
	return sRez;
}


/***************************************************************************/
function numberWord(iNumber , s1, s2, s3){
	if( iNumber * 1 ){
		iNumber = iNumber % 100;
		if( iNumber < 10 || 20 < iNumber ){
			iNumber = iNumber % 10;
			if( iNumber == 1 ) return s1;
			if( 2 <= iNumber && iNumber <= 4) return s2;
		}
	}
	return s3;
}


/***************************************************************************/
var TextLengthChecker = {

 /***************************************************************************/
	init : function(elThis, iMaxLength, elMessage){
		elThis = $(elThis);
		elMessage = $(elMessage);
		iMaxLength = iMaxLength * 1 || 0;

		if(!elThis || !elMessage || !iMaxLength || elThis.iMaxTextLength) return;

		var oThis = this;

		elThis.iMaxTextLength = iMaxLength;
		elThis.elMaxLengthMessage = elMessage;

		_checkRemains();

		Events.add(elThis, 'keyup', _checkRemains);
		Events.add(elThis, 'mouseup', _checkRemains);
		Events.add(elThis, 'blur', _checkRemains);
		Events.add(elThis, 'change', _checkRemains);
		Events.add(elThis, 'focus', _checkRemains);

		/***************************************/
			function _checkRemains(e){
				oThis.remains(elThis, iMaxLength, elMessage)
			};
	},

 /***************************************************************************/
	remains : function(elThis, iMaxLength, elMessage){
		elThis = $(elThis);

		var
			oThis = this,
			iLength = elThis.value.length,
			sMessage = '',
			iDiff = 0;

		if(elThis.iLastLength == iLength) return;

		elThis.iLastLength = iLength;

		if (iLength > iMaxLength) {
			iDiff = iLength - iMaxLength;
			sMessage = 'Превышено на ';
			Styles.setClass(elThis,'error',1);
		} else {
			iDiff = iMaxLength - iLength;
			sMessage = 'Осталось ';
			Styles.setClass(elThis,'error',0);
		}

		sMessage += iDiff + ' знак' + numberWord(iDiff , '', 'а', 'ов');

		elMessage.innerHTML = sMessage;
	}
};









//////////////////////////////////////////////////////////////////////////////////////////////
function elementOffset(element){
    var valueT = 0, valueL = 0;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;
      element = element.offsetParent;
    } while (element);
    return {x : valueL, y : valueT};
}

/***************************************************************************/
function mousePos(event){
	var oClick = {};
	if (event){
		oClick.x = event.clientX + scrollLeft();
		oClick.y = event.clientY + scrollTop();
	}
	else{
		oClick.x = window.event.clientX + scrollLeft();
		oClick.y = window.event.clientY + scrollTop();
	}
	return oClick;
}

/***************************************************************************/
function scrollTop(){
		return window.pageYOffset
			|| document.documentElement.scrollTop
			|| document.body.scrollTop
			|| 0;
}

/***************************************************************************/
function scrollLeft(){
		return window.pageXOffset
			|| document.documentElement.scrollLeft
			|| document.body.scrollLeft
			|| 0;
}


/***************************************************************************/
var findX = function(obj) {
  var curleft = 0;
  if (obj.offsetParent) {
    while (obj.offsetParent) {
      curleft += obj.offsetLeft
      obj = obj.offsetParent;
    }
  }
  else if (obj.x)
    curleft += obj.x;
  return curleft;
}

/***************************************************************************/
var findY = function(obj) {
  var curtop = 0;
  if(obj.offsetParent) {
    while (obj.offsetParent) {
      curtop += obj.offsetTop
      obj = obj.offsetParent;
    }
  }
  else if (obj.y)
    curtop += obj.y;
  return curtop;
}

/***************************************************************************/
var mousePosX = function(e) {
  var posx = 0;
  if (!e) var e = window.event;
  if (e.pageX)
    posx = e.pageX;
  else if (e.clientX && document.body.scrollLeft)
    posx = e.clientX + document.body.scrollLeft;
  else if (e.clientX && document.documentElement.scrollLeft)
    posx = e.clientX + document.documentElement.scrollLeft;
  else if (e.clientX)
    posx = e.clientX;
  return posx;
}

/***************************************************************************/
var mousePosY = function(e) {
  var posy = 0;
  if (!e) var e = window.event;
  if (e.pageY)
    posy = e.pageY;
  else if (e.clientY && document.body.scrollTop)
    posy = e.clientY + document.body.scrollTop;
  else if (e.clientY && document.documentElement.scrollTop)
    posy = e.clientY + document.documentElement.scrollTop;
  else if (e.clientY)
    posy = e.clientY;
  return posy;
}













//////////////////////////////////////////////////////////////////////////////////////////////
var winPopup = {
	fOnShow			: null,
	fOnClose			: null,
	elOnClickOut	: null,

 /***************************************************************************/
	show				: function(event, fShow, fClose, elClickOut){
		this.close(event);

		this.fOnShow = fShow;
		this.fOnShow(event);

		this.fOnClose = fClose;
		this.elOnClickOut = elClickOut;

		Events.add(document , 'keydown', winPopup.checkEsc);
		if(this.elOnClickOut)
			Events.add(document , 'mousedown', winPopup.checkMouseDown);
	},

 /***************************************************************************/
	checkEsc			: function(event){
		if(Events.key(event) == 27){
			winPopup.close(event);
			return Events.stop(event);
		}
	},


 /***************************************************************************/
	checkMouseDown	: function(event){
		if( winPopup.elOnClickOut ){

			if( !Events.within(event, winPopup.elOnClickOut) ){
				winPopup.close(event);
				return Events.stop(event);
			}
		}
	},

 /***************************************************************************/
	close				: function(event){
		var bDonStop = false;
		if(this.fOnClose){
			bDonStop = this.fOnClose(event);
		}
		if(!bDonStop){
			this.fOnShow = null;
			this.fOnClose = null;
			this.elOnClickOut = null;
			Events.remove(document , 'keydown', winPopup.checkEsc);
			Events.remove(document , 'mousedown', winPopup.checkMouseDown);
		}
	}
}



//////////////////////////////////////////////////////////////////////////////////////////////
var ShowModal = function ( url, w, h ){
	var name = 'Modal' + Math.floor( Math.random()*1000 )
	var width = w ? w : 600
	var height = h ? h : screen.height - 300

	var left = Math.round( (screen.width-width)/2 )
	var top =  Math.round( (screen.height-height)/2 ) - 35

	var options = 'status=yes,menubar=no,toolbar=no'
	options += ',resizable=yes,scrollbars=yes,location=no'
	options += ',width='  + width
	options += ',height=' + height
	options += ',left='   + left
	options += ',top='    + top

	var win = window.open( url, name, options )
	win.focus()

	return win
};






//////////////////////////////////////////////////////////////////////////////////////////////
function checkForm(elForm,sErrorText){
		var
			mInp = elForm.elements,
			bSend = true,
			bMail = false,
			sVal = false,
			oValues = {};

		sErrorText = (sErrorText == null ? 'Заполните поле' : sErrorText) + '';

		for(var i=0, l=mInp.length ; i < l ; i++ ){
			var sTag = mInp[i].tagName.toLowerCase();
 			if(
				sTag == 'textarea' ||
				(sTag == 'input' && mInp[i].type == 'text')
			){
				bMail = ( mInp[i].name == 'mail' );
				sVal = trim( mInp[i].value );

				if(
					!Styles.matchClass( mInp[i], 'unreq' )
					|| (bMail && sVal)
				){
					if(
						checkError(mInp[i]) ||
						!sVal ||
						(bMail && !isEmail(sVal) )
					){
						bSend = false;
						setError( mInp[i] );
						if( !sVal ){
							mInp[i].value = sErrorText;
							mInp[i].bErrorText = true;
						}

						mInp[i].onfocus = function(event){
							var elNode = Events.target(event);
							elNode.onfocus = null;
							removeError( elNode );
							//if(elNode.value == sErrorText) elNode.value = '';
							if(elNode.bErrorText){
								elNode.value = '';
								elNode.bErrorText = null;
							}
						}
					}
				}
			}
		}

		return bSend;

		/***************************************/
			function _error(elNode,bError){
				Styles.setClass(elNode,'error',bError);
				if(elNode.parentNode.tagName.toLowerCase() == 'label'){
					Styles.setClass(elNode.parentNode,'error',bError);
				}
				elNode.bIsError = bError;
			};
			function setError(elNode){_error(elNode,1);};
			function removeError(elNode){_error(elNode,0);};
			function checkError(elNode){return (elNode.bIsError || Styles.matchClass(elNode,'error') || Styles.matchClass(elNode,'unfilled') || false)};
			//function removeError(elNode){Styles.setClass(elNode,'error',0);};
			//function checkError(elNode){return Styles.matchClass(elNode,'error');};
};

/**/




