﻿// функция открывает новое виртуальное окно
function OpenWindow(w,h,puth){
	var valLeft = (screen.width) ? (screen.width-w)/2 : 0;// отступ слева
	var valTop = (screen.height) ? (screen.height-h)/2 : 0;// отступ сверху
	var features = 'width='+w+',height='+h+',left='+valLeft+',top='+valTop+',';
	var ow = window.open(puth, 'name_up', features+'toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1');
	return ow;
}

// доп. функция под jQuery под определение offsetWidth
jQuery.fn.offsetWidth = function() {
	return this[0].offsetWidth;
};
jQuery.fn.YaPro = function() {
	return this.tagName;
};

// переменные и функция под tiny_mce
var openBrowserPuth = null;
var openBrowserSite = null;
var system_target_form_element = null;
var system_openBrowserFiles = null;
function openBrowser(id){//'backgroundimagebrowser','backgroundimage', 'image','table_image_browser_callback'
	system_target_form_element = id;
	if(system_openBrowserFiles && system_openBrowserFiles.document){
		system_openBrowserFiles.focus();
	}else{
		system_openBrowserFiles = OpenWindow("770","570",openBrowserPuth+"?insert=1");
	}
}

// удаляет из массива дублирующиеся значения
function array_unique(arr){
	var vic = new Object();
	for(i=0; i < arr.length; i++){ vic[arr[i]] = ""; }
	arr = new Array();
	for(i in vic){ arr[arr.length] = i; }
	return arr;
}

// функция определения значения определенной куки
function GetCookie(name){
    var cookie_pair;
    var cookie_name;
    var cookie_value;
    //--Разбиваем куку в массив
    var cookie_array = document.cookie.split('; ')
    //--Пробегаем по массиву кук
    for (var counter = 0; counter < cookie_array.length; counter++) {
            //--Разбиваю куку на имя/значение
        cookie_pair = cookie_array[counter].split('=');
        cookie_name = cookie_pair[0];
        cookie_value = cookie_pair[1];
        //--Сравниваем имя куки с тем именем, которое нужно нам
        if (cookie_name == name) {
                 //--Если нашли нужную нам куку, то возвращаем её значение
            return cookie_value;
        }
    }
    //--Если куку не нашли, возвращаем null
    return "";
}

// функция определения значения определенной куки
function SetCookie(name, value){
    document.cookie = name+'='+value+'; path=/; expires=Friday, 15-May-2015 10:45:30 GMT';
}

// проверка на удаление
var confirm_message = 'Подтверждаете удаление?';
function checkDel(){
	if(confirm(confirm_message)==true){return true;}
	return false;
}

var url = null;
var puth = null;
// удаление директории или файла
function onDelete(e, name){
	if(url && e && name && checkDel()){
		$.ajax({
			type: "POST",
			url: url,
			data: "delete="+name,
			success: function(msg){
				if(msg=="ok"){ e.parentNode.parentNode.style.display = "none"; }else{ alert(msg); }
		   }
		});
	}
}
// Инсерт ссылки
function onInsert(name){
	if(url && puth && name && window.opener && window.opener.openBrowserSite && window.opener.system_target_form_element){
		var temp_puth = window.opener.openBrowserSite + puth + name;
		var temp_e = window.opener.document.getElementById(window.opener.system_target_form_element);
		temp_e.value = temp_puth;
		if(temp_e.onchange){ temp_e.onchange(); }
		window.opener.focus();
		window.close();
	}
}


// скрытие или показ объекта
function SH(id){
	if($("#"+id).css("display")=="none"){
		$("#"+id).fadeIn("slow");
	}else{
		$("#"+id).fadeOut("slow");
	}
}

// раскраска по строкам
function mouseMovements(id) {
	var bgn=0;
	color_onmouseover = "ClassOnMouseOver";
	color_onclick = "ClassOnClick";
	if(typeof(id)=="string" && document.getElementById(id)){
		var tr = document.getElementById(id).getElementsByTagName('TR');
	}else if(typeof(id)=="object"){
		var tr = id.getElementsByTagName('TR');
	}else{
		return false;
	}
	for(i=0;i<tr.length;i++){
		if(tr[i].className==''){
			class_color = (bgn%2)?'LightBlue':'LightGrey'; bgn++;
			tr[i].className = class_color;
			
			(function(o_color) { 
				tr[i].onmouseover = function(){
					if(this.className != color_onclick){this.className = color_onmouseover;}
				} 
			})(class_color);
			
			(function(o_color) { 
				tr[i].onmouseout = function(){
					   if(this.className != color_onclick){this.className = o_color;}
				} 
			})(class_color);
			
			(function(o_color) { // передаем значение переменной class_color, как значение переменной o_color
				tr[i].onmousedown = function(){
					if(this.className!=color_onclick){this.className = color_onclick;}
					else{this.className = o_color;}
					} 
			})(class_color);
		}
	}
}

// применение mouseMovements ко всем дочерним таблицам класса classname
function mouseMovementsClass(classname){
	var t = document.getElementsByTagName("TABLE");
	for(var i=0; i<t.length; i++){
		if(t[i].className==classname){
			mouseMovements(t[i]);
		}
	}
}

// Специальная функция-хак под IE 7 и выше, которая помогает снять выделение с flash - объектов
function SystemWrite(str){
	document.write(str);
}

// определение позиции элемента
function PosElement(e){
	if(typeof(e) != "object") { e = document.getElementById(e); }
	var ww = e.offsetWidth, hh = e.offsetHeight;
	for (var xx = 0,yy = 0; e != null; xx += e.offsetLeft,yy += e.offsetTop,e = e.offsetParent);
	return {Left:xx, Top:yy, Right:xx + ww, Bottom:yy + hh}// левый, верхний, правый, нижний
}

// обрезает пробелы в начале и в конце строки
function trim(s){
	while (s.substring(0,1) == ' ') {
		s = s.substring(1,s.length);
	}
	while (s.substring(s.length-1,s.length) == ' ') {
		s = s.substring(0,s.length-1);
	}
	return s;
}

// Проверка полей
function CheckField(form, type_check, name_field, message){// Примечание: регулярки отдают true если срабатывает условие, и null в обратном случае
	
	// регулярка на мыло
	var e = /^([\w\.\-]+)@([a-z0-9\-]+)\.([a-z0-9\-\.]+)$/i;// условие: обязательное сопостовление указанной регулярке
	
	// регулярка на цирфру
	var i = /[0-9\-\(\)\s]+/i;// условие: обязательное присутствие хотябы 1 цифры
	
	// регулярка на букву
	var t = /[a-zа-я\-\.\s]+/i;//--условие: присутствие хотябы 1 буквы
	
	// регулярка на пробел
	var b = /\s+/;//--условие: присутсвие хотябы 1 пробела, включая space, tab, form feed, line feed. Эквивалентно [ \f\n\r\t\v].
	
	obj = form[name_field];
	
	if(obj!=null && typeof(obj)!='undefined'){
		
		obj_value = trim(obj.value);
		
		if(obj_value.match(eval(type_check))==null || obj_value==''){
			
			obj.value = obj_value;
			obj.style.border="#FF0000 1px solid";
			obj.focus();
			return "- Вы не указали "+message+". Исправьте, пожалуйста!\n";
			
		}else{
			
			obj.value = obj_value;
			obj.style.border='#cccccc 1px solid';
			return "";
			
		}
		
	}else{
		alert("- Поле с name: "+name_field+" не найдено\n");
		return "?";
	}
}

// detect браузера
function browsers(){
	this.ver   = navigator.appVersion.toLowerCase();
	this.agent = ''+navigator.userAgent.toLowerCase();
	this.dom   = document.getElementById ? 1 : 0;
	this.opera = (this.agent.indexOf("opera")>-1 && this.dom) ? 1 : 0;
	this.ie    = (this.ver.indexOf("msie") > -1 && this.dom && !this.opera) ? 1 : 0;
	this.macOS = this.agent.indexOf("mac") > -1;
	this.mac   = (this.macOS && parseInt(this.ver) >= 7) ? 1 : 0;
	this.moz   = (this.agent.indexOf("gecko")>-1)
	this.ns6   = (this.dom && this.agent.indexOf("netscape")>-1 && parseInt(this.ver) >= 5) ? 1 : 0;
	//this.safari = (hnav.search(/macintosh/gmi)!=-1&&hnav.search(/safari/gmi)!=-1);
	//this.opera7 = (this.opera && parseInt(navigator.appVersion) >= 7);
	return this;
}
browser = new browsers();
// функция сортировки строк таблицы - onclick="sortTableTR(document.getElementById('sortTableTR'));"
function sortTableTR(el){
	var col_sort = el.innerHTML;
	var tr = el.parentNode;
	var table = tr.parentNode;
	var td, arrow, col_sort_num;
	
	for (var i=0; (td = tr.getElementsByTagName("td").item(i)); i++){
   		if(td.innerHTML == col_sort){
            col_sort_num = i; 
            if (td.prevsort == "y"){
                //arrow = td.firstChild;
                el.up = Number(!el.up);
            }else{
                td.prevsort = "y";
                //arrow = td.insertBefore(document.createElement("span"),td.firstChild);
                el.up = 0;
            }
            //arrow.innerHTML = el.up?"↑ ":"↓ ";
        }else{
            if (td.prevsort == "y"){
                td.prevsort = "n";
                if (td.firstChild){ td.removeChild(td.firstChild); }
            }
        }
    }
	
	var a = new Array();
	
    for(i=1; i < table.rows.length; i++){
	 	a[i-1] = new Array();
	 	a[i-1][0]=table.rows[i].getElementsByTagName("td").item(col_sort_num).innerText;
		a[i-1][1]=table.rows[i];
	}
	
	a.sort();
	if(el.up) a.reverse();	 
	
	for(i=0; i < a.length; i++)
	table.appendChild(a[i][1]);
}
// Функции вывода описания ввода, пример: onFocus="foc(this)" onBlur="blu(this)" value="описание"
function foc(o){
	if(o.alt=='' || typeof(o.alt)=='undefined'){ o.alt=o.value; }
	if(o.value==o.alt){ o.value=''; }
}
function blu(o){
	if(o.value==''){o.value=o.alt;}
}
// [ путь к странице
var timePuth = null;
var PathMenu = null;
var bodyPagePathMenu  = document.getElementsByTagName((document.compatMode && document.compatMode == "CSS1Compat") ? "HTML" : "BODY")[0];
function SHPathTime(){// скрываем через 0,1 секунды
	timePuth = setTimeout("SHPathMenu()",100);
}
function SHPathHide(t){// скрываем через 0,1 секунды
	t.style.visibility = "hidden";
	t.style.top = "-10000px";// выставляем координату Y
	t.style.left = "-10000px";// выставляем координату Х
	var div = t.getElementsByTagName("DIV");// div[0] - внутренняя часть выпадающего меню
	div[0].style.width = "auto";
	div[0].style.height = "auto";
}
function SHPathMenu(e, id){
	
	if(typeof(e)=="object" && typeof(id)=="string"){// показываем
		
		var t = document.getElementById(id);// меню
		var ka = PosElement(e);// координаты элемента a
		if(t && ka){
			
			clearInterval(timePuth);
			
			if(PathMenu && typeof(PathMenu)=="object" && PathMenu!=t){// скрываем открытое меню, чтобы далее открыть новое меню
				SHPathHide(PathMenu);
			}
			
			t.style.visibility = "visible";// показываем элемент
			t.style.top = ka.Bottom+"px";// выставляем координату Y
			t.style.left = (ka.Left-5)+"px";// выставляем координату Х-5
			
			// находим максимально-допустимую выосту
			var div = t.getElementsByTagName("DIV");// div[0] - внутренняя часть выпадающего меню
			var w_height = window.innerHeight ? window.innerHeight+window.pageYOffset : bodyPagePathMenu.clientHeight+bodyPagePathMenu.scrollTop;
			var maxHeight = (w_height - ka.Bottom - 40);// 40 = 12(сверху)+10(снизу)+18(возможный скролл снизу)
			if(div[0].offsetHeight>maxHeight){
				div[0].style.height = maxHeight+"px";
				div[0].style.width = (div[0].offsetWidth + 40)+"px";
			}
			
			PathMenu = t;// назначаем временной переменной ссылку на объект
		}
		
	}else if(typeof(e)=="string" && e=="stop"){// останавливаем скрытие меню
		
		clearInterval(timePuth);
		
	}else{// скрываем меню
		
		if(PathMenu && typeof(PathMenu)=="object"){
			SHPathHide(PathMenu);
		}
	}
}
// путь к странице ]
