var d = document;
var de = d.documentElement;
var padding = 40;
var scroll = 0; // высота скроллинга
var xSite = padding;
var clientW = 1024; // ширина окна браузера клиента
var clientH = 768; // высота окна браузера клиента
var catalogW = 558; // ширина каталога
var catalogH = 580; // высота каталога
var catalogWRate = 1; // Коэффициент соотношения высоты каталога и ширины рабочей области.
var catalogHRate = 1; // Коэффициент соотношения высоты каталога и высоты рабочей области.
var headerH = 382 + 25; // Высота шапки

$(document).ready(function(){	if ( !$('.catalog_section').hasClass('parent_a') && $.cookie('menu_20_status') != 'show') {		$('#menu_parent_20').css('display','none');
	}
	changeCatalogState();

	//Убираем обводку вокруг элементов
	$('a').click(function(){$(this).blur();});

	scroll = de.scrollTop; // длинна скрола
	clientW = windowWidth();
	clientH = windowHeight();
	xSite = Math.round (clientW/2-400);
	ySite = clientH + scroll - headerH;
	catalogWRate = catalogW/clientW;
	catalogHRate = catalogH/ySite;
	$.ajaxSetup({
		cashe: false,
		timeout: 5000
	});
	$.getJSON("/anketa.php?2", { },
		function(data) {
			if(data.show=='yes') {
				$("#anketaInvite").show("slow");
			}
	});

});
function toggleMenu ( id ) {	$('#menu_parent_'+id).slideToggle('slow', function () {		cookieName = 'menu_'+id+'_status';		cookieVal = 'show';
		if ( $('#menu_parent_'+id).css('display') == 'none' ) {
			cookieVal = 'hide';
		}
		$.cookie( cookieName, cookieVal, { expires: 1, path: cookiePath  });
	});
	return false;
}

window.onresize = function () {
	scroll = de.scrollTop; // длинна скрола
	clientW = windowWidth();
	clientH = windowHeight();
	ySite = clientH + scroll - headerH;
	catalogWRate = catalogW/clientW;
	catalogHRate = catalogH/ySite;
}

window.onscroll = function () {
	scroll = de.scrollTop; // длинна скрола
	ySite = clientH + scroll - headerH;
	catalogHRate = catalogH/ySite;
}

// Определение высоты видимой части страницы
function windowHeight() {
	return self.innerHeight || ( de && de.clientHeight ) || document.body.clientHeight;
}

// Определение ширины видимой части страницы
function windowWidth() {
	return self.innerWidth || ( de && de.clientWidth ) || document.body.clientWidth;
}

// Возвращает координаты мыши
function mousePageXY(e) {
	var x = 0, y = 0;
	if (!e) e = window.event;
	if (e.pageX || e.pageY) {
		x = e.pageX;
		y = e.pageY;
	} else if (e.clientX || e.clientY) {
		x = e.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft) - document.documentElement.clientLeft;
		y = e.clientY + (document.documentElement.scrollTop || document.body.scrollTop) - document.documentElement.clientTop;
	}
	return {
		"x":x,
		"y":y
	};
}

// Блок с отладочной информацией
function writeDebug (s) {
  $('#debugDiv').html(s);
}

function showProperties(obj) {
	var result='';
	for (var i in obj) {
		result += i + " = " + obj[i] + "\n";
	}
	return result;
}

function getId(id) {
	var tmp = document.getElementById(id);
	return tmp;
}

var ru2en = {
	ru_str : "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдеёжзийклмнопрстуфхцчшщъыьэюя",
	en_str : ['A','B','V','G','D','E','JO','ZH','Z','I','J','K','L','M','N','O','P','R','S','T', 'U','F','H','C','CH','SH','SHH','','I','','JE','JU', 'JA','a','b','v','g','d','e','jo','zh','z','i','j','k','l','m','n','o','p','r','s','t','u','f', 'h','c','ch','sh','shh','','i','','je','ju','ja'],
	translit : function(org_str) {
		var tmp_str = "";
		for(var i = 0, l = org_str.length; i < l; i++) {
			var s = org_str.charAt(i), n = this.ru_str.indexOf(s);
			if(n >= 0) {
				tmp_str += this.en_str[n];
			} else {
				tmp_str += s;
			}
		}
		return tmp_str;
	}
}

function downloadPage(url, param, id, afterResponse) {
	var	message = '<div style="margin: 0px auto; text-align: center; padding-top: 50%;"><img src="'+ uRoot +'images/loading.gif" alt="Загрузка" style="margin: 0px auto;"/></div>';
	if(getId(id)) {
		getId(id).innerHTML = message;
		var req ;
		if (window.XMLHttpRequest) req = new XMLHttpRequest();
		else if (window.ActiveXObject) req = new ActiveXObject("Microsoft.XMLHTTP");
		if (req) {
			req.onreadystatechange = function() {
				if (req.readyState == 4) {
					if (req.status == 200) {
						if(getId(id)) {
							getId(id).innerHTML = req.responseText; //unescape(req.responseText);
							if (id == 'managerInfo') {
								getId(id).style.height = 'auto';
							}
							if(afterResponse!=undefined) eval(afterResponse);
						}
					} else
						alert (req.status);
				}
			}
			req.open('POST', url + ( (navigator.userAgent.indexOf('Opera 8')>=0 || navigator.userAgent.indexOf('Opera/8')>=0) ? '?'+param : ''), true);
			try {
				req.setRequestHeader('Accept-Charset', 'windows-1251');
				req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=windows-1251');
			} catch (er) {}
			req.send(param);
		}
	} else
		alert('Ошибка. Перезагрузите страницу.');
}


function getManagerInfo (id) {
	mi = d.getElementById('managerInfo');
	h = mi.offsetHeight;
	mi.style.height = h + 20 +  'px';
	downloadPage(uRoot+'kernel/manager_info.php','mid='+id+'&print_headers=1','managerInfo');
}

function getPreview(id) {
	getId(id).style.display='none';
	getId(id+'previewDiv').style.display='';
	$('#'+id+'editorPanel > input').attr({'disabled':'disabled'});
	getId(id+'previewDiv').innerHTML = nl2br(getId(id).value);
}

function getEditor(id) {
	getId(id).style.display='';
	getId(id+'previewDiv').style.display='none';
	$('#'+id+'editorPanel > input').attr({'disabled':''});
	//getId('test2').innerHTML = getId('test').value;
}

function trim(s) {
	return rtrim(ltrim(s));
}

function ltrim(s) {
	return s.replace(/^\s+/, '');
}

function rtrim(s) {
	return s.replace(/\s+$/, '');
}

function nl2br (str, is_xhtml) {
	breakTag = '<br />';
	if (typeof is_xhtml != 'undefined' && !is_xhtml) {
		breakTag = '<br>';
	}
	return (str + '').replace(/([^>]?)\n/g, '$1'+ breakTag +'\n');
}

function strip_tags(str, allowed_tags) {
	var key = '', tag = '', allowed = false;
	var matches = allowed_array = [];
	var replacer = function(search, replace, str) {
		return str.split(search).join(replace);
	};
	if (allowed_tags) {
		allowed_array = allowed_tags.match(/([a-zA-Z]+)/gi);
	}
	str += '';
	matches = str.match(/(<\/?[^>]+>)/gi);
	for (key in matches) {
		if (isNaN(key)) {
			// IE7 Hack
			continue;
		}
		html = matches[key].toString();
		allowed = false;
		for (k in allowed_array) {
			allowed_tag = allowed_array[k];
			i = -1;
			if (i != 0) {
				i = html.toLowerCase().indexOf('<'+allowed_tag+'>');
			}
			if (i != 0) {
				i = html.toLowerCase().indexOf('<'+allowed_tag+' ');
			}
			if (i != 0) {
				i = html.toLowerCase().indexOf('</'+allowed_tag) ;
			}
			if (i == 0) {
				allowed = true;
				break;
			}
		}

		if (!allowed) {
			str = replacer(html, "", str);
		}
	}
	return str;
}

function confirmFeedback () {
	if (trim($('#mailMail').val())=='' && trim($('#mailPhone').val())=='' ) {
		jConfirm('Вы не указали ни одного источника (Email, Телефон) по которому с Вами можно будет связаться по итогу обработки Вашего обращения. Вы хотите продолжить отправку сообщения?', 'Подтверждение', function(r) {
			if (r) $('#feedbackForm').submit();
		});
	} else
		$('#feedbackForm').submit();
}


// Для формы раздела "Каталог Ш.-Форм"
function showOther () {
	var d = document;
	var p = d.getElementById('production')
	var ot = d.getElementById('otherTitle');
	var oi = d.getElementById('otherInput')
	if (p.value == '0') {
		ot.style.display='table';
		oi.style.display='table';
	} else {
		ot.style.display='none';
		oi.style.display='none';
	}
}

function openImagePopup (imgPath, title) {
	//var win = window.open('','preview', 'width=50,height=50,left=0,top=0,screenX=0,screenY=0,resizable=1,scrollbar=1,status=0');
	var win = window.open('','preview', 'width=50,height=50,menubar=yes,resizable=yes,scrollbar=yes,status=yes,toolbar=yes');
	var winDoc = win.document;
	if (title == undefined) var title = 'Просмотр изображения';
	title += ' &mdash; Типография &laquo;Астер&raquo;';
	var alt = 'Кликните для того что бы закрыть окно';
	var content = '<html><head><title>123' + title + '</title>' +
	'<style>body{overflow: hidden;margin:0;}img{border:0;}</style>' +
	'</head><body><a href="javascript:self.close()" title="' + alt + '">' +
	'<img alt="' + alt + '" id="image" src="' + imgPath + '" /></a></body></html>'
	win.document.write(content);
	winDoc.body.onload = function() {
		var obj = winDoc.getElementById('image');
		var w = obj.width, h = obj.height;
		var iHeight= document.body.clientHeight, iWidth = self.innerWidth;
		var left = (self.opera ? iWidth : screen.availWidth)/2 - w/2;
		var top = (self.opera ? iHeight : screen.availHeight)/2 - h/2;
		win.resizeTo(w+10, h+26);
		win.moveTo(left, top);
	}
	win.onload = winDoc.body.onload; // для Mozilla
	// Важное замечание: всплывающее окно не будет работать без кода ниже.
	win.document.close();
	win.focus();
}


// Каталог плавающий сам по себе
changeCatalogState = function () {
	// Настройки каталога
	var speedX = 100; // скорость движения
	var speedY = 100; // скорость движения
	// Не изменять
	var stopCatalogMove = false;
	var catalog = $('#catalogTable');
	var viewPort = $('#catalogDivD');
	var position = catalog.position();
	var slideX = position.left;
	var slideY = position.top;
	moveX = function () {        if ( !stopCatalogMove ) {
			if ( slideX < ( viewPort.innerWidth() - catalog.innerWidth() ) ) {
				forward = 1;
			} else if ( slideX >= position.left ) {
				forward = -1;
			}
	       	slideX += forward;
	        catalog.css ({ 'left' : slideX + 'px' })
		}
		setTimeout( moveX, parseInt(1000/speedX) );
	};
	moveY = function () {
        if ( !stopCatalogMove ) {
			if ( slideY < ( viewPort.innerHeight() - catalog.innerHeight() ) ) {
				up = 1;
			} else if ( slideY >= position.top ) {
				up = -1;
			}
	       	slideY += up;
	        catalog.css ({ 'top' : slideY + 'px' })
        }
        setTimeout( moveY, parseInt(1000/speedY) );
	};
	catalog.hover( function(){stopCatalogMove=true;}, function(){stopCatalogMove=false;} );
	moveX();
	//moveY();
}