// функция открывает новое виртуальное окно
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();
	}
}


// скрытие или показ объекта
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();
