var ua = navigator.userAgent.toLowerCase();
// Определим Internet Explorer
var isIE = (ua.indexOf("msie") != -1 && ua.indexOf("opera") == -1 && ua.indexOf("webtv") == -1);
// Opera
var isOpera = (ua.indexOf("opera") != -1);
// Gecko = Mozilla + Firefox + Netscape
var isGecko = (ua.indexOf("gecko") != -1);
// Safari, используется в MAC OS
var isSafari = (ua.indexOf("safari") != -1);
// Konqueror, используется в UNIX-системах
var isKonqueror = (ua.indexOf("konqueror") != -1);

/**
 * ОКНА
 */
var win = null;
function CenterWindow(myurl, myname, w, h, scroll, status) {
	if(win == '[object]') win.close();
	status = 1;
	
	if (screen.width <= w + 20) {
		// размер выдаваемого окна больше чем размер экрана пользователя
		scroll = 1;
		w = screen.width - 20;
	}
	
	if (screen.height <= h + 50) {
		// размер выдаваемого окна больше чем размер экрана пользователя
		scroll = 1;
		h = screen.height - 50;
	}
	
	
	// -10 и -50 - поправка для скроллинга и для нижней полосы с меню "Старт"
	LeftPosition = (screen.width) ? (screen.width-w - 10)/2: 0;
	TopPosition = (screen.height) ? (screen.height-h - 50)/2 : 0;
	settings = 'height='+h+',width='+w+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scroll+',toolbar=0,location=0,resizeable=0,menubar=0,directories=0,dependent=1,status='+status;
	win = window.open(myurl,myname,settings)
	return win;
}
function showDialog(myurl, null_reserved, w, h) {
	window.showModalDialog(myurl, window, "dialogHeight:"+h+"px; dialogWidth:"+w+"px; edge: Raised; center: Yes; help: No; resizable: No; status: No; scroll: 0; ");
}
// Центрирует диалоговое окно
function centerDialog() {
	var height = document.body.scrollHeight + 55;
	window.dialogHeight = height + 'px';
	var l = 
	window.dialogLeft = ((screen.width - parseInt(window.dialogWidth)) / 2) + 'px';
	window.dialogTop = ((screen.height - parseInt(window.dialogHeight)) / 2) + 'px';
	
}
function showImage(url) {
	if (win == '[object]') win.close();
	LeftPosition = (screen.width) ? (screen.width-640 - 10)/2: 0;
	TopPosition = (screen.height) ? (screen.height-480 - 50)/2 : 0;
	win = window.open('/tools/cms/site/image6.php?url='+url,'image','height=480,width=640,top='+TopPosition+',left='+LeftPosition+',scrollbars=1,toolbar=0,location=0,menubar=0,directories=0,dependent=1,status=1')
}
function resizeImageDialog(img) {
	var img = document.getElementById(img);
	var w = img.width + 50;
	var h = img.height + 100;
	resizeDialog(w,h);
}
function resizeDialog(w,h) {
	var mv = 80;
	var mh = 50;
	w = (screen.width <= w + mh) ? screen.width - mh : w;
	h = (screen.height <= h + mv) ? screen.height - mv : h;
	w = (w < 100) ? 100 : w;
	h = (h < 100) ? 100 : h;
	
	LeftPosition = (screen.width) ? (screen.width - w) / 2: 0;
	TopPosition = (screen.height) ? (screen.height - h) / 2 : 0;
	window.resizeTo(w,h);
	window.moveTo(LeftPosition,TopPosition);
}
// Определяет внутреннюю ширину и высоту окна браузера
function windowWidth() {
 return (window.innerWidth)?window.innerWidth:((document.all)?document.body.offsetWidth:null);
}
function windowHeight() {
	return (window.innerHeight)?window.innerHeight:((document.all)?document.body.offsetHeight:null);
}

/**
* По нажатию кнопки Esc - закрывает окно,
* по нажатию кнопки Enter - подписывает форму с именем=Form
* Использование : <BODY  onKeyPress="EnterEsc(event);">
*/
function EnterEsc(evt) {
	var charCode = (evt.which) ? evt.which : event.keyCode
	if (charCode == 13 && document.Form == '[object]') {
		document.Form.submit();
	} else if (charCode == 27) {
		window.close();
	} else {
		return true;
	}
}

/**
* По нажатию кнопки Esc - закрывает окно
* Кнопку Enter - не отрабатываем, в модальных
* окнах он пытается засабмитить форму в новом окне
*/
function Esc(evt) {
	var charCode = (evt.which) ? evt.which : event.keyCode
	if (charCode == 27) {
		window.close();
	} else {
		return true;
	}
}



/**
 * КУКИ
 */
function setCookie(cookieName,cookieValue,nDays) {
	var today = new Date();
	var expire = new Date();
	if (nDays==null || nDays==0) nDays=1;
	expire.setTime(today.getTime() + 3600000*24*nDays);
	document.cookie = cookieName+"="+escape(cookieValue)+ ";expires="+expire.toGMTString();
}
function getCookie(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));
}
function delCookie(name) {
  document.cookie = name+"=; expires=Fri, 31 Dec 1999 23:59:59 GMT;";
}


/**
 * ЭЛЕМЕНТЫ ФОРМ
 */
// В форме SELECT MULTIPLE 1. выбирает все 2. снимает со всех выделение 3. инвертирует выделение
function select_options(id, value) {
	var select_id = document.getElementById(id);
	for(i=0; i < select_id.options.length; i++) {
		if (value == 'invert') {
			select_id.options[i].selected = (select_id.options[i].selected) ? false : true;
		} else {
			select_id.options[i].selected = value;
		}
	}
}
// Выбирает опцию поля SELECT, останавливается на первой опции
function select_option(id, value) {
	var elem = document.getElementById(id);
	for(var i=0;i<elem.options.length;i++) {
		if(elem.options[i].value == value) {
			elem.options[i].selected = true;
			return;
		}
	}
}
// при загрузке страницы устанавливает курсор пользователя на первый
// попавшийся текстовый элемент формы
function FormFocus() {
	var obj = document.getElementById('Form');
	if(!obj) return; // На странице нет форм
	for(var i = 0; i < obj.elements.length; i++) {
		if (obj.elements[i].type == 'text' && obj.elements[i].disabled == false) {
			obj.elements[i].focus();
			return;
		}
	}
}
/**
 * Устанавливаем галочки на checkbox с указанным именем (name).
 * Если второй параметр (state) = null, то состояние сохраняется 
 * в памяти массива check_element_status.
 */
var check_element_status = new Array();
function checkCheckbox(name, state) {
	var input_obj = document.getElementsByTagName('INPUT');
	var first_state = true;
	
	if (state == null && check_element_status[ name ] == undefined) {
		// Если на первом элементе стоит флаг то убираем значения, если нет - то ставим
		for(var i=0;i<input_obj.length;i++) {
			if (input_obj[i].type!='checkbox') continue;
			if (input_obj[i].name.substr(0, name.length) == name) {
				first_state = input_obj[i].checked;
				break;
			}
		}
		if (first_state == true) {
			check_element_status[ name ] = false;
			state = false;
		} else {
			check_element_status[ name ] = true;
			state = true;
		}
	} else if (state == null && check_element_status[ name ] == true) {
		check_element_status[ name ] = false;
		state = false;
	} else if (state == null && check_element_status[ name ] == false) {
		check_element_status[ name ] = true;
		state = true;
	}
	
	for(var i=0;i<input_obj.length;i++) {
		if (input_obj[i].type!='checkbox') {
			continue;
		}
		if (input_obj[i].name.substr(0, name.length) == name) {
			input_obj[i].checked=state;
		}
	}
}
// Активирует radio кнопки, у которых определённое значение
function selectRadio(name, value) {
	var input_obj = document.getElementsByTagName('INPUT');
	
	for(var i=0;i<input_obj.length;i++) {
		if (input_obj[i].type!='radio') {
			continue;
		}
		if (input_obj[i].name.substr(0, name.length) == name && input_obj[i].value == value) {
			input_obj[i].checked=true;
		}
	}
}
// Позволяет вставлять в поле input только цифры Использование :  onKeyPress="return digitsOnly(event);"
function digitsOnly(evt) {
	var charCode = (evt.which) ? evt.which : event.keyCode
	return ((charCode > 47 && charCode < 58) || charCode == 13) ? true : false;
}
// Позволяет в полях file выбирать только файлы картинок JPG, PNG, GIF Использование : onChange="imagesOnly(this);"
function imagesOnly(file_element) {
	var imgRegExp = /\.(jpg)|(gif)|(png)$/i;
	if(null == file_element.value.match(imgRegExp)) {
		file_element.select()
		alert ("Internet Explorer не поддерживает данный тип файлов")
	}
}
/**
* Ограничивает поля input type="text" и textarea по количеству символов
* и показывает визуально сколько символов введено
* Использоавние :onKeyDown="return countTextField(this, event, 255, 300);"
* @param text_limit - ограничение по количеству символов
* @param bar_length - длинна строки, которая отображает кол-во введенных символов
*/
function countTextField(obj, evt, text_limit) {
	var charCode = (evt.which) ? evt.which : event.keyCode
	var bar_size = obj.scrollWidth;
	var bar_width = Math.floor(bar_size * obj.value.length / text_limit);
	
	document.getElementById(obj.id + "_ctf").style.display = "inline";
	document.getElementById(obj.id + "_ctf_bar").style.width = bar_size;
	
	document.forms["Form"].elements[obj.id + "_ctf_counter"].value = obj.value.length + '/' + text_limit;
	document.getElementById(obj.id + "_ctf_filler").style.width = bar_width;
	document.getElementById(obj.id + "_ctf_counter_div").style.left = (bar_width < bar_size) ? bar_width - 15: bar_size - 15;
	
	return (obj.value.length > text_limit && (charCode > 47 || charCode == 13 || charCode == 32)) ? false : true;
}

// Выбирает опцию поля SELECT, останавливается на первой опции
function selectOption(id, value) {
	var elem = document.getElementById(id);
	for(var i=0;i<elem.options.length;i++) {
		if(elem.options[i].value == value) {
			elem.options[i].selected = true;
			return;
		}
	}
}






/**
 * Слои
 */

// Ставит слой в центр экрана или в центр элемента center_of_element
function centerDiv(layer, center_of_element) {
	center_of_element = 'toursearch_form';
	if (byId(center_of_element) && byId(layer)) {
		var pos = position(byId(center_of_element));
		var w1 = byId(center_of_element).clientWidth;
		var h1 = byId(center_of_element).clientHeight;
		var w2 = byId(layer).clientWidth;
		var h2 = byId(layer).clientHeight;
		var left = pos.x + (w1 - w2)/2;
		var top = pos.y + (h1 - h2)/2;
		byId(layer).style.left = (left >= 0) ? Math.ceil(left) : 0;
		byId(layer).style.top =  (top >= 0) ? Math.ceil(top) : 0;
	} else if (byId(layer)) {
		var left = (windowWidth()-byId(layer).clientWidth)/2;
		var top = (windowHeight()-byId(layer).clientHeight)/2 + document.body.scrollTop;
		byId(layer).style.left = (left >= 0) ? left : 0;
		byId(layer).style.top =  (top >= 0) ? top : 0;
	}
}

/**
 * Разное
 */
// Алиас для функции document.getElementById()
function byId(id) {
	return document.getElementById(id);
}
// Определение положения элемента на странице
function position(el)	{ 
	var p = { x: el.offsetLeft, y: el.offsetTop };
	while (el.offsetParent)	{
		el = el.offsetParent;
		p.x += el.offsetLeft;
		p.y += el.offsetTop;
		if (el != document.body && el != document.documentElement) {
			p.x -= el.scrollLeft;
			p.y -= el.scrollTop;
		}
	}
	return p;
}

function var_dump(d,l) {
    if (l == null) l = 1;
    var s = '';
    if (typeof(d) == "object") {
        s += typeof(d) + " {\n";
        for (var k in d) {
            for (var i=0; i<l; i++) s += "  ";
            s += k+": " + var_dump(d[k],l+1);
        }
        for (var i=0; i<l-1; i++) s += "  ";
        s += "}\n"
    } else {
        s += "" + d + "\n";
    }
    return s;
}
/**
* Блокировка нажатия правой кнопки мышки
* Использование BODY|INPUT onContextMenu="return contextMenu();"
*/
function contextMenu() {
	event.cancelBubble = true;
	return false;
}
// Подтверждение нажатия ссылки
function confirmLink(what) {
    return confirm(what);
}

/**
 * inline Редактор текста
 */
(iEditor = {
	activate : function(id) {
		if (isIE || isOpera) {
			frames[id].document.designMode = "On";
			frames[id].focus();
		} else if (isGecko) {
			document.getElementById(id).contentDocument.designMode = "on";
		}
	},
	activateAll : function() {
		var obj = document.getElementsByTagName('iframe');
		for(i=0;i<obj.length;i++) {
			this.activate(obj[i].id);
		}
	},
	beforeSave : function (form_id) {
		var obj = document.getElementsByTagName('iframe');
		for(i=0;i<obj.length;i++) {
			var inp = document.createElement('input');
			inp.type='hidden';
			inp.name=obj[i].id;
			if (isIE || isOpera) {
				inp.value=frames[ obj[i].id ].document.body.innerHTML
			} else if (isGecko) {
				inp.value=obj[i].contentDocument.body.innerHTML
			}
			document.getElementById(form_id).appendChild(inp);
		}
	}
}
);


