﻿// форматирует вывод числа, аналог number_format() в PHP
function number_format(number, decimals, dec_point, thousands_sep){
  var exponent = "";
  var numberstr = number.toString ();
  var eindex = numberstr.indexOf ("e");
	var i, z;
  if(eindex > -1){
    exponent = numberstr.substring (eindex);
    number = parseFloat (numberstr.substring (0, eindex));
  }
  
  if(decimals != null){
    var temp = Math.pow (10, decimals);
    number = Math.round (number * temp) / temp;
  }
  var sign = number < 0 ? "-" : "";
  var integer = (number > 0 ? 
      Math.floor (number) : Math.abs (Math.ceil (number))).toString ();
  
  var fractional = number.toString ().substring (integer.length + sign.length);
  dec_point = dec_point != null ? dec_point : ".";
  fractional = decimals != null && decimals > 0 || fractional.length > 1 ? (dec_point + fractional.substring (1)) : "";
  if(decimals != null && decimals > 0){
    for(i = fractional.length - 1, z = decimals; i < z; ++i)
      fractional += "0";
  }
  
  thousands_sep = (thousands_sep != dec_point || fractional.length == 0) ? 
                  thousands_sep : null;
  if(thousands_sep != null && thousands_sep != ""){
		for (i = integer.length - 3; i > 0; i -= 3)
			integer = integer.substring (0 , i) + thousands_sep + integer.substring (i);
  }
  return sign + integer + fractional + exponent;
}

// ловит нажатие Enter на Input и передает его в функцию func
function keyConfirm(e, oInput, func){
	var keynum;
	var keychar;
	var numcheck;

	if(window.event){ // IE
		keynum = e.keyCode
	}
	else if(e.which){ // Netscape/Firefox/Opera
		keynum = e.which
	}
	if(keynum == 13){
		if(oInput.value)
			var foo = func(oInput);
	}
}

// возвращает код нажатой клавиши
function getKeyCode(e){
	if(window.event) // IE
		return e.keyCode;
	else if(e.which) // Netscape/Firefox/Opera
		return e.which;
}

function setOnblur(){
	var elems = document.getElementsByTagName('textarea');
	if(elems.length > 0){
		for(var i = 0; i < elems.length; i++){
			if(elems[i].getAttribute('blured') == 'blured'){
				if(elems[i].getAttribute('class_tmp') == null)
					elems[i].setAttribute('class_tmp', elems[i].getAttribute('class'));
				elems[i].className = elems[i].getAttribute('class_tmp') + ' onblur';
				elems[i].addEventListener('focus', function(){
					this.className = this.getAttribute('class_tmp') + ' onfocus';
				}, false);
				elems[i].addEventListener('blur', function(){
					this.className = this.getAttribute('class_tmp') + ' onblur';
				}, false);
			}
		}
	}
}

// дизаблит кнопку и добавляет в нее иконку ожидания
function btnDisable(oBtn){
	oBtn.disabled = 'disabled';
	var width = oBtn.clientWidth;
	oBtn.setAttribute('tmp_val', oBtn.innerHTML);
	oBtn.style.width = width;
	oBtn.innerHTML = '<center><div class="pleasewait"></div></center>';	
}

// енаблит кнопку и убирае тиконку ожидания
function btnEnable(oBtn){
	oBtn.innerHTML = oBtn.getAttribute('tmp_val');
	oBtn.disabled = '';
}

// устанавливает <option selected="selected" /> у <select></select>
function setSelectValue(oSelect, val){
	oDebug = document.getElementById('debug');
	var child = oSelect.childNodes;
	for(var i = 0; i < child.length; i++){
		if(child[i].nodeType == 1){
			if(child[i].value == val){
				child[i].setAttribute('selected', 'selected');
				child[i].style.background = "#f2f6b4";
				child[i].style.fontWeight = "bold";
			}
			else if(child[i].getAttribute('selected') == 'selected'){
				child[i].removeAttribute('selected');
				child[i].style.background = "";
				child[i].style.fontWeight = "";
			}
		}
	}
}

// event - onmouseover, onchange etc.
function addEvent2Checkboxes(name, func, event){
	var tmp, attr, pos, before;
	var chks = document.getElementsByName(name);
	if(chks.length > 0)
		for(var i = 0; i < chks.length; i++){
			tmp = chks[i];
			if(tmp.hasAttribute(event)){
				attr = tmp.getAttribute(event);
				pos = attr.indexOf('return false;');
				if(pos != -1){
					before = attr.substring(0, pos-1);
					tmp.setAttribute(event, before + ' ' + func + ' return false;');
				} else {
					//alert(attr + ' ' + func + ' return false;');
					tmp.setAttribute(event, attr + ' ' + func + ' return false;');
					//alert(tmp.getAttribute('onclick') + ' ' + pos);
				}
			} else {
				tmp.setAttribute(event, func + ' return false;');
			}
		}
}

function setCheckboxes(name, state){
	var chks = document.getElementsByName(name);
	if(chks.length > 0)
		for(var i = 0; i < chks.length; i++){
			chks[i].checked = state;
		}
}

// add event (multybrowsing)
function addEvent(obj, handler, event){
	if(window.addEventListener) // Mozilla, Netscape, Firefox
		obj.addEventListener(event, handler, false);
	else {// IE
		var ev = (event.indexOf('on') == -1?'on':'') + event;
		obj.attachEvent((ev?ev:event), handler);
	}
}

// return object, where fires event
function getEventObject(event){
	return event.srcElement || event.target;
}

// http://www.artlebedev.ru/tools/technogrette/js/validate_xml_value/
// correct: http://forum.hitech.by/topic148.html
function xmlValidate( sValue ){
	if( sValue ){
			// вырезаем инструкции
			sValue = sValue.replace( /<\?.*\?>/g, '' );
			// вырезаем doctype
			sValue = sValue.replace( /<\!DOCTYPE.*?>/g, '' );
			// вырезаем коменты и CDATA
			var rTags = /(<!--.*?-->|<\!\[CDATA\[.*?\]\]>)/g;
			while( sValue.search( rTags ) >= 0 ){
					sValue = sValue.replace( rTags, '' );
			}
			// вырезаем одинарные тэги
			sValue = sValue.replace( /<[-\w:]+(\s+[-\w:]+\s*=\s*"[^<>]*?")*\s*\/>([^<]*)/gi, '' );
			// вырезаем двойные тэги
			var rTags = /<([-\w:]+)(\s+[-\w:]+\s*=\s*"[^<>]*?")*\s*>[^<>]*?<\/\1>([^<]*)/g;
			while( sValue.search( rTags ) >= 0 ){
					sValue = sValue.replace( rTags, '' );
			}
			if( sValue.search( /[<>]/ ) >= 0 || sValue.search( /&(?!(\w+;|#\d+;))/ ) >= 0 ){
					//alert( sValue )// можно показать sValue;
					return false;
			}
			return true;
	}else{
			return true;
	}
}

// предзагрузка картинок. жрет массив с путями
function preloadImgs(imgs){
	var pre;
	for(var i = 0; i < imgs.length; i++){
		pre = new Image();
		pre.src = imgs[i];
	}
}

function getElementsByNameIE(tag, name){
	var elem = document.getElementsByTagName(tag);
	var arr = new Array();
	for(i = 0, iarr = 0; i < elem.length; i++){
		att = elem[i].getAttribute("name");
		if(att == name){
			arr[iarr] = elem[i];
			iarr++;
		}
	}
	return arr;
}

function getCookie(name){
	var cook = document.cookie;
	var pos = cook.indexOf(name + '=');
	if(pos == -1){
		return null;
	} else {
		var pos2 = cook.indexOf(';', pos);
		if(pos2 == -1)
			return unescape(cook.substring(pos + name.length + 1));
		else 
			return unescape(cook.substring(pos + name.length + 1, pos2));
	}
}

function setCookie(name, value, path, domain, expires, secure){
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime(today.getTime());

	/*
	if the expires variable is set, make the correct 
	expires time, the current script below will set 
	it for x number of days, to make it for hours, 
	delete * 24, for minutes, delete * 60 * 24
	*/
	if(expires){
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );

	document.cookie = name + "=" +escape( value ) +
		( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
		( ( path ) ? ";path=" + path : "" ) + 
		( ( domain ) ? ";domain=" + domain : "" ) +
		( ( secure ) ? ";secure" : "" );
}

function trim(str) {
  if (!str) return "";
  return str.replace(/^\s+/, "").replace(/\s+$/, "");
}

function getElementsByClass(searchClass,node,tag) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;

	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	for (i = 0, j = 0; i < elsLen; i++) {
		 if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}

// start smooth fadeIn of object "o"
function setFadeIn(o, interval, stepOpacity){
	if(stepOpacity === undefined) var stepOpacity = 10;
	var maxOpacity = 100;
	var browser = (window.addEventListener?'normal':'ie');
	if(browser != 'ie'){// naxer ie
		var fadeIn = function(){
			var opacity = (browser == 'ie'?o.filters.alpha.opacity:Number(o.style.opacity) * 100);
			if(isNaN(opacity) || opacity === undefined || opacity === null) opacity = 0;
			if(opacity >= maxOpacity){
				window.clearInterval(o.getAttribute('fadeInIntervalId'));
			} else{
				if(browser == 'ie')
					o.style.filter = 'alpha(opacity='+(opacity + stepOpacity)+")";
				else
					o.style.opacity = (opacity + stepOpacity) / 100;
			}
		}
		var fadeInIntervalId = window.setInterval(fadeIn, interval);
		o.setAttribute('fadeInIntervalId', fadeInIntervalId);
		return fadeInIntervalId;
	}
}

// start smooth fadeOut of object "o"
function setFadeOut(o, interval, funcOnFadeComplete, stepOpacity){
	if(stepOpacity === undefined) var stepOpacity = 10;
	var startOpacity = 100;
	var browser = (window.addEventListener?'normal':'ie');
	try{
		if(browser == 'ie')
			o.style.filter = 'alpha(opacity='+startOpacity+")";
		else
			o.style.opacity = startOpacity / 100;
		var fadeOut = function(){
			var opacity = (browser == 'ie'?o.filters.alpha.opacity:Number(o.style.opacity) * 100);
			if(isNaN(opacity) || opacity === undefined) opacity = 100;
			if(opacity <= 0){
				window.clearInterval(o.getAttribute('fadeOutIntervalId'));
				funcOnFadeComplete();
			} else {
				if(browser == 'ie')
					o.style.filter = 'alpha(opacity='+(opacity - stepOpacity)+")";
				else
					o.style.opacity = (opacity - stepOpacity) / 100;
			}
		}
		var fadeOutIntervalId = window.setInterval(fadeOut, interval);
		o.setAttribute('fadeOutIntervalId', fadeOutIntervalId);
	}
	catch(e){
		alert(e);
	}
	return fadeOutIntervalId;
}

// cancel event, multybrowsing
function cancelDefaultEvent(e){
	if(e.preventDefault)
		e.preventDefault();
	else
		e.returnValue= false;
	return false;
}

function getPageScroll(){
	/* scrollLeft: The distance between the horizontal scrollbar 
		with the left edge of the frame.
		scrollTop:  The distance between the vertical scrollbar
		with the top edge of the frame. 

		Get the scroll value from different browsers.
		Determine the browser type first. 
		And then get the value from the particular property.*/
	var scrollLeft, scrollTop;

	if(window.pageXOffset)
		scrollLeft = window.pageXOffset 
	else if(document.documentElement && document.documentElement.scrollLeft)
		scrollLeft = document.documentElement.scrollLeft; 
	else if(document.body)
		scrollLeft = document.body.scrollLeft; 

	if(window.pageYOffset)
		scrollTop = window.pageYOffset 
	else if(document.documentElement && document.documentElement.scrollTop)
		scrollTop = document.documentElement.scrollTop; 
	else if(document.body)
		scrollTop = document.body.scrollTop; 

	return {"left":scrollLeft, "top":scrollTop};
}

function getVisibleArea(){
	var windowWidth, windowHeight;
	if(window.innerWidth)// Safari, Opera, FF
		windowWidth = window.innerWidth;
	else if(document.documentElement && document.documentElement.clientWidth)// IE
		windowWidth = document.documentElement.clientWidth;
	else if(document.body)
		windowWidth = document.body.offsetWidth;
	
	if(window.innerHeight)
		windowHeight = window.innerHeight;
	else if(document.documentElement && document.documentElement.clientHeight)
		windowHeight = document.documentElement.clientHeight;
	else if(document.body)
		windowHeight = document.body.clientHeight;
	return {"width":windowWidth, "height":windowHeight};
}

// type = [error|success]
function showProcessingMsg(text, type, coords){
	if(type === undefined || !type)	type = 'success';
	if(coords === undefined || !coords)	coords = {x:200,y:200};
	if(type == 'success')	var style = "background: yellow; color: black; border: 1px solid #999999;";
	else if(type == 'error') var style = "background: #FFAFAF; color: black; border: 1px solid #8F1111;";
	var msgDiv = document.createElement('div');
	var pageScroll = getPageScroll();
	msgDiv.setAttribute('style', "position: absolute; top: "+(coords.y+pageScroll.top)+'px'+"; left: "+(coords.x+pageScroll.left)+'px'+"; width: 200px; height: 50px; padding: 6px; "+style);
	var oMsgDiv = document.body.appendChild(msgDiv);
	oMsgDiv.innerHTML = text;
	window.setTimeout(closeProcessingMsg, (type == 'error'?100000:10000), oMsgDiv);
}

function closeProcessingMsg(oMsgDiv){
	document.body.removeChild(oMsgDiv);
}

// get absolute coords for element el
function getAbsolutePos(el){
	var r = { x: el.offsetLeft, y: el.offsetTop };
	if (el.offsetParent){
		var tmp = getAbsolutePos(el.offsetParent);
		r.x += tmp.x;
		r.y += tmp.y;
	}
	return r;
}

// show debugging window in browser page
function debug(params){
	var html = params.html; // content to add to debug window
	var clean = params.clean; // [true] - clean innerHTML
	var cr = params.cr; // [true] - CR, new line
	
	var oDebug = document.getElementById('x-debug');
	if(oDebug === undefined || !oDebug){
		var visArea = getVisibleArea();
		oDebug = document.createElement('div');
		oDebug.id = 'x-debug';
		oDebug.style.position = 'fixed';
		oDebug.style.top = '100px';
		oDebug.style.right = '50px';
		oDebug.style.width = '300px';
		oDebug.style.height = (visArea.height - 200)+'px';
		oDebug.style.backgroundColor = '#FFEE9F';
		oDebug.style.border = '1px solid #8F7911';
		oDebug.style.overflow = 'scroll';
		oDebug = document.body.appendChild(oDebug);
	}
	if(typeof params == 'string' || typeof params == 'number' || (typeof params == 'object' && params.html === undefined)){
		html = String(params);
		if(oDebug.innerHTML != '') cr = true;
	}	else if(typeof params == 'object'){
		html = params.html;
		clean = params.clean;
	}
	if(clean !== undefined && clean === true) oDebug.innerHTML = '';
	oDebug.innerHTML += (cr?'<br />':'')+(html);
}

function jumpTo(id){
	var obj = document.getElementById(id);
	if(typeof obj == 'object'){
		var scroll_val = getAbsolutePos(obj);
		var scroll = getPageScroll();
		scrollInterval = window.setInterval('jumpToAction({scroll_val: '+(scroll_val.y)+', start_scroll: '+(scroll.top)+', step: 20, speed: 4})', 30);
	}
}

function jumpToAction(config){
	var scroll = getPageScroll();
	var step = config.step;
	if((scroll.top > config.start_scroll + 0) && (scroll.top + config.step < config.scroll_val - 100)) step = config.step * config.speed;
	if(scroll.top + step >= config.scroll_val){
		window.clearInterval(scrollInterval);
		scrollInterval = '';
	}
	window.scrollTo(0, scroll.top + step);
}


// *********************************************************************************************************************

// fix absent method Date.now() in Safari
if(!Date.now){
	Date.now = function(){
		return (new Date()).getTime();
	};
}

// set browser variable
var browser = (window.addEventListener?'normal':'ie');

//Помечает чекрыжик, находящийся в первой ячейке строки при клике по ячейке таблицы
//Пока-что сложил сюда - незнаю где это хранить правильнее
function markIt(o){
	if(!window.aclick){
		var chk = o.parentNode.firstChild.firstChild;
		if(chk.checked == true){
			o.parentNode.style.backgroundColor = '';
		}else{
			o.parentNode.style.backgroundColor = '#FFBBBB';
		}
		chk.checked = !chk.checked;
	}else{
		delete aclick;
	}
}
