var agent = navigator.userAgent.toLowerCase();
var major = parseInt(navigator.appVersion);
var minor = parseFloat(navigator.appVersion);

var isNN = ((agent.indexOf('mozilla') != -1) && ((agent.indexOf('spoofer') == -1) && (agent.indexOf('compatible') == -1)));
var isNN4 = (isNN && (major == 4));
var isNN6 = (isNN && (major >= 5));

var isOPERA = agent.indexOf("opera")>-1 && window.opera;
var isIE4 = (agent.indexOf("msie") != -1 && !isOPERA);

var flash_version = 0; // Версия флеш-проигрывателя
var fz=0;
if (isIE4){
	ie = 1;
	for (var i=3; i<7; i++){
		try {
			if (eval("new ActiveXObject('ShockwaveFlash.ShockwaveFlash."+i+"')")) flash_version = i;
		}
		catch (e) {}
	}
}
if ((isOPERA || isNN || isNN4 || isNN6) && (navigator.plugins)){
	for (var i=0; i<navigator.plugins.length; i++){
		if (navigator.plugins[i].name.indexOf("Flash")> -1){
			fz = parseInt(navigator.plugins[i].description.charAt(16));
			if (fz > flash_version) flash_version=fz;
		}
	}
}
	
//-------------------------------------------------------------------//
function rusoft() {
  window.open('http://www.rusoft.ru');
}

function ShowHTTP(href, display, target, style, title) {
	if (display == '') display = href;
	if (target == '') target = '_blank';
	document.writeln('<a href="'+href+'" target="'+target+'" title="'+title+'" style="'+style+'">'+display+'</a>');
}

function ShowMail(user, domain1, domain2) {
	var email = user+'&#64;'+domain1+'&#46;'+domain2;
	if (ShowMail.arguments[3]) name = ShowMail.arguments[3];
	else name = email;
	document.writeln('<a href="mailto:'+email+'">'+name+'</a>');
}

function openImage(image) {
	if (image) window.open("/popup.php?img="+image, "popupimage", "scrollbars=no, resizable=1, width=100, height=100").focus();
	return false;
}

function openPhoto(id) {
	if (id) window.open("/popupf?id="+id, "popup", "scrollbars=1, resizable=1, width=700, height=450").focus();
}

function imgOpen(imgURL,imgWidth,imgHeight,Title) {
	var imgWndw=window.open('','_blank','width='+imgWidth+',height='+
	imgHeight+',toolbar=no,menubar=no,location=no,status=no,'+
	'resizable=yes,scrollbars=no');
	var imgTitle=(Title)?Title:imgURL+": "+imgWidth+'x'+imgHeight;
	with (imgWndw.document){
		open();
		write('<ht'+'ml><he'+'ad><ti'+'tle>'+imgTitle+'</ti'+'tle>'+
		'</he'+'ad><bo'+'dy leftmargin="0" '+
		' topmargin="0" '+
		'rightmargin="0" bottommargin="0" marginwidth="0" '+
		'marginheight="0"><img src="'+imgURL+'" width="'+imgWidth+
		'" height="'+imgHeight+'" border="0" alt="'+imgTitle+
		'"></bo'+'dy></ht'+'ml>');
		close();
	}
	return false
}

function OpenPopup(src) {
	if (arguments[1]) popup_name = arguments[1];
	else popup_name = 'popup';
	if (arguments[2]) popup_width = arguments[2];
	else popup_width = 500;
	if (arguments[3]) popup_height = arguments[3];
	else popup_height = 400;
	window.open(src, popup_name, 'toolbar=no,location=no,status=no,menubar=no,resizable=yes,directories=no,scrollbars=yes,width='+popup_width+',height='+popup_height).focus();
	return false
}

function SetCookie(sName, sValue){
	document.cookie = sName + "=" + escape(sValue) + "; expires=Fri, 31 Dec 2070 23:59:59 GMT; path=/;";
}

function changeImage(id, img) {
	document.getElementById(id).src = img;
}

function insertFlash(v, fl, gif, lnk, w, h, id){
	if (flash_version >= v) {
		document.write('<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" width="' + w + '" height="' + h + '" id="flash' +  id + '" align="center"><param name="allowScriptAccess" value="sameDomain" /><param name="movie" value="' + fl + '"><param name="quality" value="high" /><param name="wmode" value="transparent" /><param name="bgcolor" value="#ffffff" /><embed src="' + fl + '" wmode="transparent" quality="high" width="' + w + '" height="' + h + '"></embed></object>');
	} else if (gif != '') {
		document.write("<a href='"+lnk+"'><img src='"+gif+"' width='" + w + "' height='" + h + "' border=0></a>");
	}
}

function get_current_day() {
	var cur_date = new Date();
	return cur_date.getDate();
}

function get_current_month() {
	var mon = new Array('января', 'февраля', 'марта', 'апреля', 'мая', 'июня', 'июля', 'августа', 'сентября', 'октября', 'ноября', 'декабря');
	var cur_date = new Date();
	return mon[cur_date.getMonth()];
}

function get_current_week_day() {
	var day = new Array('воскресенье', 'понедельник', 'вторник', 'среда', 'четверг', 'пятница', 'суббота');
	var cur_date = new Date();
	return day[cur_date.getDay()];
}

// --------------------------------------------------
// ---- Отображение галереи на странице объекта -----
// --------------------------------------------------
var i=0;
var timer;
// --- Клик на кнопку Вперед/Назад
function showGallery(count, mode, rotate){
	i = parseInt(i) + parseInt(mode);
	if (rotate) {
		if (i>=count) i=0;
		if (i<0) i=count-1;
	} else {
		if (i>=count) i=count-1;
		if (i<0) i=0;
	}
	if (i>=0 && (i-1)<count) {
		if (document.getElementById('object_image') && par[i]) {
			document.getElementById('object_image').innerHTML = par[i];	
			document.getElementById('object_alt').innerHTML = alt[i];
		}
	}

	changeImageArrows(count);
	return false;
}
function changeImageArrows(count){
	if (i==0) document.getElementById('link_prev').innerHTML = '<span class="ol_previous" style="background: none">Предыдущая</span>';
	else document.getElementById('link_prev').innerHTML = '<a href="javascript:" class="ol_previous" onclick="showGallery(' + count + ',-1); return false;" id="prev">Предыдущая</a>';	

	if ((i+1)>=count) document.getElementById('link_next').innerHTML = '<span class="ol_next" style="background: none">Следующая</span>';	
	else document.getElementById('link_next').innerHTML = '<a href="javascript:" onclick="showGallery(' + count + ',1); return false;" class="ol_next" id="next">Следующая</a>';
}
// --- Клие на превью
function SelectImage(type, image, bigimage, width, height, num, count){
	if (this.timer) stopGallery();
	showGallery(count, num-this.i, false);
}
// --- Клик на кнопку Play
function playGallery(count, timeout){
	// Надо вызывать функцию showGallery с какой-то задержкой
	this.timer = window.setInterval("showGallery("+count+", 1, true)", timeout);
	document.getElementById('play').src = '/images/controls_stop_active.gif';
	document.getElementById('play_link').onclick = function(){stopGallery(count); return false;};
}
// --- Клик на кнопку Stop
function stopGallery(count){
	window.clearInterval(this.timer);
	document.getElementById('play').src = '/images/controls_play_active.gif';
	document.getElementById('play_link').onclick = function(){playGallery(count); return false;};
}

function ShowMiddleImage(imagepath, largeimagepath, alt, page, pos) {
	this.i = pos;
	document.getElementById('object_alt').innerHTML = alt;
	var image = '';
	if (largeimagepath) {
		image += '<a href="' + largeimagepath + '" onclick="openImage(\'' + largeimagepath + '\'); return false">';
	}
	image += '<img src="' + imagepath + '" border="0">';
	if (largeimagepath) {
		image += '</a>';
	}
	document.getElementById('object_image').innerHTML = image;
	document.getElementById('return_link').onclick = function() {ShowSmallImage(page); return false};
	document.getElementById('small_photo_div'+page).style.display = 'none';
	document.getElementById('middle_photo_div').style.display = 'block';
}

function ShowSmallImage(page) {
	document.getElementById('small_photo_div'+page).style.display = 'block';
	document.getElementById('middle_photo_div').style.display = 'none';
}

var _page = 0;
// Переход на заданную страницу галереи
function gotoPage(page) {
	document.getElementById('small_photo_div'+page).style.display = 'block';
	document.getElementById('small_photo_div'+_page).style.display = 'none';
	_page = page;
}
// --------------------------------------------------
// При сабмите не передаем пустые значения
function clearEmptyFields(form) {
	var len = form.elements.length; 
	for (var i=0; i<len; i++) {
		var oChild = form.elements[i];
		try {
			if (
				oChild.tagName == 'INPUT' ||
				oChild.tagName == 'TEXTAREA' ||
				oChild.tagName == 'SELECT'
			) {
				if (oChild.value == '') {
					oChild.disabled = true;
				}
			}
		} catch (e) {}
	}
	return false;
}

function resetForm(form) {
	form.reset();
	try{
		/* Очистка метро */
		for (var i in metro_center) {
			select_line(metro_center[i], 'none');
		}
		for (var i in metro_region_top) {
			select_line(metro_region_top[i], 'none');
		}
		for (var i in metro_region_bottom) {
			select_line(metro_region_bottom[i], 'none');
		}
		for (i=0; i<20; i++) {
			try{
				document.getElementById('img_line_down'+i).style.display = 'none';
			} catch (e) {}
			try{
				document.getElementById('img_line_up'+i).style.display = 'none';
			} catch (e) {}
			try{
				document.getElementById('img_line'+i).style.display = 'none';
			} catch (e) {}
		}
		/* Очистка направлений */
		for (i=0; i<30; i++) {
			try {
				deselectDirection(i);
			} catch (e) {}
		}
	} catch (e) {alert(e.description);}
}

var max_count = 200;
function calculateSymbols(textarea, span_id, count) {
	message_text    = textarea.value;
	realLength      = 0;
	storeLength     = 0;
	storeRealLength = 0;

	for (i=0; message_text.length>i; i++) {
		if (max_count>=realLength) {
			storeRealLength = realLength;
			storeLength = i;
		}
		if(message_text.substring(i,i+1) != "\x0d") {
			realLength++;
		}
	}

	if (realLength>max_count) {
		realLength = storeRealLength;
		textarea.value = message_text.substring(0,storeLength);
	}

	document.getElementById(span_id).innerHTML = max_count-realLength;
}

// пропорциональное уменьшение размеров картинок превью
function imgResize(id)
{
    var image = document.getElementById(id);

    var width = image.width;
    var height = image.height;
    var prop = image.height/image.width;
    
    var size = 135;

    if (width > size || height > size)
    {
        height = prop*size;
        width = size;
        
        if (height > size)
        {
            height = size;
            width = size/prop;
        }
	}
    image.width = width;
    image.height = height;
}

var f = 0;
function about_bill(id) {
	if (f != 1) 
		if (isNN6) location.href = "/cabinet/bills/?bill_id="+id;
		else document.location.href = "/cabinet/bills/?bill_id="+id;
	f = 0;
	return false;
}

function delete_bill(id){
	if (confirm('Удаление счета № '+id+'. Вы уверены?') == true) {
		if (isNN6) location.href = "/cabinet/bills/?act=delete&bill_id="+id;
		else document.location.href = "/cabinet/bills/?act=delete&bill_id="+id;
	}
	f = 1;
	return false;
}

function showDropBlock(id) {
    var block = document.getElementById(id);
    block.style.display = block.style.display == 'block' ? 'none' : 'block';
    if (isIE4 && document.getElementById('hide_block')) document.getElementById('hide_block').style.display = block.style.display == 'block' ? 'none' : 'block';
}

function changeClientType(type) {
    var fields_fiz = new Array('fio', 'phone', 'email', 'addr');
    var fields_jur = new Array('fio2', 'comp_name', 'comp_fname', 'comp_inn', 'comp_kpp', 'comp_zip', 'comp_addr', 'comp_paddr', 'comp_phone', 'comp_fax', 'comp_email', 'comp_bank', 'comp_bik', 'comp_ks', 'comp_rs');
    if (type == 'fiz') {
        ShowRows(fields_fiz, 1);
        ShowRows(fields_jur, 0);
    }
    else {
        ShowRows(fields_fiz, 0);
        ShowRows(fields_jur, 1);
    }
}

function ShowRows(fields, show) {
    for (var i=0; i < fields.length; i++) {
        var row = document.getElementById('row_' + fields[i]);
        row.style.display = show ? (isIE4 ? 'block' : 'table-row') : 'none';
    }
}

function ___getPageSize() {
	var xScroll, yScroll;
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = window.innerWidth + window.scrollMaxX;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth; 
		} else {
			windowWidth = self.innerWidth;
		}
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}
	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = xScroll;		
	} else {
		pageWidth = windowWidth;
	}
	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
	return arrayPageSize;
};
/**
 / THIRD FUNCTION
 * getPageScroll() by quirksmode.com
 *
 * @return Array Return an array with x,y page scroll values.
 */
function ___getPageScroll() {
	var xScroll, yScroll;
	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
		xScroll = self.pageXOffset;
	} else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
		xScroll = document.documentElement.scrollLeft;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
		xScroll = document.body.scrollLeft;	
	}
	arrayPageScroll = new Array(xScroll,yScroll);
	return arrayPageScroll;
};