var mouseX; 
var mouseY;

$().mousemove( function(e) {
	mouseX = e.pageX;
	mouseY = e.pageY;
//	alert(1);

});

$(document).ready(function(){
    $('#minWidth a').each(function(){
        if(this.href) {
	        if(!this.href.match(/^\/.+/gi) && !this.href.match(/21\.by/gi) && !this.href.match(/21by/gi) && !this.href.match(/javascript/gi)) {
	            $(this).addClass('external');
	        }
        }
    });
});
var sLoadSPid = function(s, id, md, first){
	child = $('#' + id);
	child.attr('value', 0);	
	if (s.value == 0){
		child.hide();
		return;
	}
		
	s.disabled = true;

	var data = {ajax:1, hm:400, cmd:'get', pid:s.value};
	if (!first) {
		first = '-список-';
	}	
	if (md) {
		data.md = md;
	}

	$.ajax({
		type : "POST",
		url : sCUR_HTTP, 
		dataType : "json",
		s : s,
		child : child,
		data : data,
		first : first,
		success : function(a){
			var s2 = this.child.find('select:first'), i = 0;
			s2.find('option').remove();
			for (var v in a.data) {
				if (a.data[v].id == 0){
					a.data[v].name = this.first;
				}
				s2.append('<option value="'+a.data[v].id+'">'+a.data[v].name+'</option>');
				i++;
			}

			if (i > 2){
				this.child.show();
			}else{
				this.child.hide();
			}
			
			s.disabled = false;
		}
 });
}

var sRecommendItem = function(obj){
	var l = $(obj);
	$.ajax({
		type : "POST",
		url : obj.href, 
		dataType : "json",
		data : {ajax:1, cmd:'recommend'},
		success : function(a){
			l.html(a.cmd_messages[0]);
		}
 });
}

var sCommentsSubscribe = function(obj, url){
	var 
		f = $(obj),
		b = $('input:submit', f);
		i = $('input:text', f);
		b.attr('disabled', 'disabled');
		
	$.ajax({
		type : "POST",
		url : url, 
		dataType : "json",
		data : {ajax:1, cmd:'subscribe', email: i.attr('value')},
		b : b,
		success : function(a){
			this.b.attr('disabled', '');
			
			if (a.cmd_errors){
				alert(a.cmd_errors);
			}else{
				alert(a.cmd_messages);
			}
		}
 });
}

var sSubscribe = function(obj, url){
	var 
		f = $(obj),
		b = $('input:submit', f);
		i = $('input:text', f);
		n = $('select:frec', f);
		o = $('input:hidden', f);
		b.attr('disabled', 'disabled');
		
	$.ajax({
	
		type : "POST",
		url : url, 
		dataType : "json",
		data : {ajax:1, cmd:'subscribe', email: i.attr('value'), query: o.attr('value'), frec: n.attr('value') },
		b : b,
		success : function(a){
			this.b.attr('disabled', '');
			
			if (a.cmd_errors){
				alert(a.cmd_errors);
			}else{
				alert(a.cmd_messages);
			}
		}
 });
}

/*
 *	жалоба
 */
var sComplain = function(obj, hnd, pid){
	if (!confirm('Вы действительно хотите пожаловаться?')){
		return;
	}
	
	var l = $(obj);
	$.ajax({
		type : "POST",
		url : sCUR_HTTP, 
		dataType : "json",
		data : {
			ajax : 1,	
			hm : 112,
			hnd : hnd,
			pid : pid,
			cmd : 'process'
		},
		success : function(a){
			l.html(a.cmd_messages[0]);
		}
 });
}
/*
 *	окно авторизации
 */
var sLoginForm = {
	background : false,
	
	open : function(){
		this.background = $('<div class="window-background"></div>');
		this.background.appendTo('body');
		this.background.height($('body').height());
		$('#sCommentLoginForm').css({display:''});
	},
	
	close : function(){
		this.background.remove();
		$('#sCommentLoginForm').css({display:'none'});
	}
}

/*
 *	Преключатель типа поиска
 */
var sSelectedSearch = false;

var sSelectSearch = function (a){
	var selects = ['','web','img','news','belarus'];
	var but = document.getElementById('sSearchSelector'+a);
	var field = document.getElementById('sSearchSelect');
	
	if (sSelectedSearch.className == 'selected-' + a){
		return false;
	}
	
	but.className = 'selected-' + a;
	field.value = selects[a];

	if (sSelectedSearch){
		sSelectedSearch.className = '';
	}
        if (a==3) {
            $('#inNews').show();
            $('#compare').hide();
        } else {
            $('#inNews').hide();
            $('#compare').show();
        }
        /*
	if(a != 4){
		document.getElementById('sSearchSelector4').className = '';
	}
        */
	
	if(a != 3){
		document.getElementById('sSearchSelector3').className = '';
	}
	
	sSelectedSearch = but;
	return false;
}

/*
 *	Устанавливает ширину поля поиска
 */
var sSetSearchFieldSize = function(){

	var w = document.documentElement.clientWidth;
/*	
	logoWidth = $('#sLogoBox').width();
	if (!logoWidth) return;
*/
	logoWidth = 350;
	
	if (w < 1024){
		w = 1024;
	} else if (w > 1280){
		w = 1280;		
	}
//alert(1);
	$('#sSearchBox').css({width : (w - (logoWidth+220)) + 'px'});
	$('#sSearchField').css({width : (w - (logoWidth+330)) + 'px'});
}

$(function(){
	sSetSearchFieldSize();
	$(window).bind('resize', sSetSearchFieldSize)
});


/*
 *	Всплывающие анонсы для новостей
 */
var sShowNewsAnons = function(obj, id, articles){
	
	obj.id = id;
	obj.show = true;
	obj.timeout =	setTimeout(function(){
		$.ajax({
			type : "POST", 
			url : sCUR_HTTP, 
			dataType : "json",
			obj : obj,
			data : {
				hm : 100,
				ajax : 1,
				cmd : 'getTlp',
				id : id
			},
			success : function(a){
				var
					box = $('#sNewsTlpBox'),
					cnt = $('.tlp-i', box),
					sWidth = document.documentElement.clientWidth - 430;
					
				if (this.obj.show === false){
					return;
				}
				
				if (!a.data){
					return;
				}
				
				cnt.empty();

				box.css({
					display : '',
					top : (mouseY + 26),
					left : (((mouseX > sWidth) ? sWidth : mouseX) + 7)
				});
				
				if (a.data.img){
					cnt.append('<img src="' + a.data.img + '" width="94" alt="" class="img-left" />');
				}
				
				cnt.append(a.data.anons + '<div class="clear"></div>');

				$(this.obj).mousemove(function(e){
					var 
						sWidth = document.documentElement.clientWidth - 430,
						mouseX = (e.pageX > sWidth) ? sWidth : e.pageX;

					$('#sNewsTlpBox').css({
						top : (e.pageY + 26), 
						left : (mouseX + 7)
					});
				});
			}
	 });
	},'700');
}

var sHideNewsAnons = function(obj){
	obj.show = false;

	if (obj.timeout){
		clearTimeout(obj.timeout);
	}

	$(obj).mousemove(function(){});
	
	$('#sNewsTlpBox').css({display : 'none'});
}

var setPriod = function (type, obj){
	var s = $(obj), p = s.parent().parent();	
//	selectors
	$('span', s.parent()).attr('class','');
	
	s.attr('class','selected');	
	$('ul', p).css({'display' : 'none'});
	$('.selectors', p).after($('#sNewsList' + type));
	$('#sNewsList' + type).css({'display' : ''});	
}

/*
 *	Переключатель сортировки в карточке новостей
 */
var setOrder = function(type, obj){
	var s = $(obj);
	$('span', s.parent()).attr('class','');
	
	$.cookie('newsitemorder', type, { expires: 2000, path: '/', domain: '.' + sHOST, secure: false });		
	
	if (type == 'last'){
		$('#sNewsListPop').css({'display' : 'none'});
		$('#sNewsListLast').css({'display' : ''});
	}else{
		$('#sNewsListPop').css({'display' : ''});
		$('#sNewsListLast').css({'display' : 'none'});
	}
	
	s.attr('class','selected');
}

/*
 *	Управление всплювающим блочком "еще"
 */
var sShowMoreTools = function(obj, id, padLeft){
	var 
		lnk = $(obj),
		box = $('#sMoreTools' + id),
		pos = lnk.sAbsPosition(),
		left = pos.left + lnk.width(),
		top = pos.top;

	sHideMoreTools();

	left -= (padLeft) ? padLeft : 366;
	top -= 4;

	$('a', box).click(function(){
										
	});

	box.click(function(){
//		return false;
	});

	box.css({
		display:'', 
		top : top + 'px',
		left : left  + 'px'
	});
	
	document.body.lastMoorTool = box;
	setTimeout("$('body').bind('click', sHideMoreTools);", 50);
	
	return false;
}

var sHideMoreTools = function(obj, id){
	$(document.body.lastMoorTool).css({display:'none', left : '-1000px'});
	$('body').unbind('click', sHideMoreTools);
}

/*
 *	Управление всплювающим блочком "в закладки в блог"
 */
var sShowFavTools = function(obj){
	var 
		lnk = $(obj),
		box = $('#sFavBox'),
		pos = lnk.sAbsPosition();

	box.css({
		display:'', 
		top : (pos.top - 7) + 'px',
		left : (pos.left + lnk.width() - 138) + 'px'
	});
}

var sHideFavTools = function(obj){
	$(obj).parent().parent().css({display:'none'});
}

/*
 *	Переключение режима списка с аносом или без на внутренней
 */
var sShowHideAnons = function(value){
	value = (value == '') ? 1 : value;
	value = (value == 1) ? 0 : 1;
	$.cookie('showanons', value, { expires: 2000, path: '/', domain: '.' + sHOST, secure: false });
	window.location.reload();
	return false;
}

/*
 *	Инвертирует значение куки
 */
var sSetUnsetCookie = function(name, value){
	value = (value == 1) ? 0 : 1;
	$.cookie(name, value, { expires: 2000, path: '/', domain: '.' + sHOST, secure: false });
	window.location.reload();
	return false;
}

/*
 *	изменение размеров шрифта пользователя
 */
var sSetFontSize = function(size, obj){
	var p = $(obj).parent();
	$('dd', p.parent()).attr('class','');
	p.attr('class', 'selected');

	$.cookie('userfontsize', size, { expires: 2000, path: '/', domain: '.' + sHOST, secure: false });
	$('.editor').css({'font-size' : (size/10) + 'em'});
}


/*
 *	Переключает меню
 */
var sSelectMenu = function(id, obj){
	var p = $(obj);	
	$('span', p.parent()).attr('class','');	
	p.attr('class', 'selected');
	$('#sMenu2').css({ display : 'none' });
	$('#sMenu1').css({ display : 'none' });
        $('#sMenu3').css({ display : 'none' });
	$('#sMenu4').css({ display : 'none' });
	$('#sMenu' + id).css({ display : '' });

	$.cookie('newsmenu', id, { expires: 2000, path: '/', domain: '.' + sHOST, secure: false });
}

/*
 *	Открывает окно с версией для печати
 */
var sPrint = function(obj){
  window.open(obj.href, '', 'width=700,height=600,toolbar=no,menubar=yes,location=no,status=yes,resizable=yes,scrollbars=yes,left=50,top=50').focus();
}

/*
 * Вылидатор для форм.
 */
var sValidator = {
	StatusWait:0,
	Errors : [],
	FieldValidate:function(obj){
		this.StatusWait = 1;
		
		if (obj.name == 'doc_pass2'){
			if ($('input[name="doc_pass"]', obj.form).attr('value') != obj.value){
				this.SetFieldStatus(obj, 'Пароли должны совпадать');
				return;
			}
		}
		
		if (obj.name == 'doc_captcha'){
			if (obj.value == ''){
				this.SetFieldStatus(obj, 'Вы не ввели текст с картинки');
			}else{
				this.SetFieldStatus(obj);
			}
			return;
		}

		$.ajax({
			type : "POST", 
			url : obj.form.action, 
			dataType : "json",
			obj : obj,
			Validator : this,
			data : {
				cmd:'fieldValidate',
				ajax:1,
				fieldName:obj.name,
				fieldValue:obj.value
			},
			
			success : function(a){
				if(a.cmd_errors && a.cmd_errors.length > 0)	{
					this.Validator.SetFieldStatus(this.obj, a.cmd_errors[0]);
				}else{
					this.Validator.SetFieldStatus(this.obj);
				}
			}
		});
	},	
	
	SetFieldStatus:function(obj, err){
		this.StatusWait = 0;
		if (obj.tooltip){
			obj.tooltip.remove();
			obj.tooltip = null;
		}
		
		if(err)	{
			var 
				parent = $(obj).parent(),
				pos = parent.sAbsPosition(),
				width = parent.width();

			obj.tooltip = $('<div class="error-tooltip">' + err + '</div>');
			obj.tooltip.appendTo('body');
			obj.tooltip.css({left : (pos.left + width + 10), top : (pos.top + 6)});
			this.Errors[obj.name] = err;
		}else{
			this.Errors[obj.name] = false;
		}
	},
	
	ValidateForm : function(){
		var res = 0;
		
		for (var v in this.Errors) {
			if (this.Errors[v]){
				res++;
			}
		}		
		
		if (res > 0){
			alert('Вы не указали всю необходимую информацию или указанная информация неверна ');
			return false;
		}
		
		return true;
	}
}

/*
 * преобразует дату и время из формата баз данных в человеческий
 */
var sDateTime = function(txt){
	return txt.replace(/^(.*?)-(.*?)-(.*?) (.*?):(.*?):(.*?)$/, '$3.$2.$1 $4:$5');
}


/******************************************************************************
 *	Вставка флеша
 */
function Flash() {
	return {
    transparent : true,
    needFlashVerion : 6,
    flashvars : "xml_source=/ixml/&menuselid=0",

		BrowserInfo : function( ) { 
			var userAgent = navigator.userAgent.toLowerCase( );
				 this.browserIE = ( userAgent.indexOf( 'msie' ) != -1 );
		},
		
		CheckVersionFlash : function( needVersion ) {
			if ( navigator.plugins[ 'Shockwave Flash' ] ) {
				matchStr = new RegExp ( '^[A-Za-z ]*(.*) .*$' );
				this.flashVerion = parseInt( navigator.plugins[ 'Shockwave Flash' ].description.replace( matchStr, '$1' ) );
				return ( needVersion <= this.flashVerion );
			}
			else if ( this.browserIE ) {
				for( var i = needVersion; i < needVersion + 10; i++ ) {
					try {
						flashPlayer = new ActiveXObject( 'ShockwaveFlash.ShockwaveFlash.' + i );
						this.flashVerion = i;
						return true;
					}
					catch( e ) {
						continue;
					}
				}
				return false;     
			}
			else {
				this.flashVerion = 0;
				return false;
			}
		},
		
		Insert : function( ) {
			this.BrowserInfo();
			if ( this.CheckVersionFlash( this.needFlashVerion ) ) { 
				document.write( this.GenerateHtmlFlash( ) );
			}else{
				document.write( this.GenerateHtmlImage( ) );
			}
		},

		GenerateHtmlFlash : function( ) {
			var flashCode = '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" ';
			flashCode += 'codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version= ' + this.flashVerion + ',0,0,0"' + ' width="' + this.width + '" height="' + this.height + '" align="middle">';
                        
			flashCode += '<param name="allowScriptAccess" value="always"/>';
			flashCode += '<param name="movie" value="' + this.srcFlash + '"/>';
			flashCode += '<param name="quality" value="high"/>';
			if ( this.base ) {
				flashCode += '<param name="base" value="' + this.base + '"/>';
			}
			if ( this.background ) {
				flashCode += '<param name="bgcolor" value="' + this.background + '"/>';
			}
			if ( this.transparent ) {
				flashCode += '<param name="wmode" value="opaque"/>';
			}
			if ( this.flashvars ) {
				flashCode += '<param name="flashvars" value="' + this.flashvars + '"/>';
			}
	 
			flashCode += '<embed quality="high" allowScriptAccess="always" type="application/x-shockwave-flash"' + ' pluginspage="http://www.macromedia.com/go/getflashplayer" ';
			flashCode += 'src="' + this.srcFlash+'" ' + '" width="' + this.width + '" height="' + this.height + '" ';
			if ( this.base ){
				flashCode += ' base="' + this.base + '"';
			}
			if ( this.background ){
				flashCode += ' bgcolor="' + this.background + '"';
			}
			if ( this.transparent ){
				flashCode += ' wmode="opaque"'
			}
			if ( this.flashvars ){
				flashCode += ' flashvars="' + this.flashvars + '"';
			}
			flashCode += '></embed>';
	 
			flashCode += '</object>';
			return flashCode;
		},

		GenerateHtmlImage : function( ) {
			var imageCode = '<img src="' + this.srcImage + '"/>';
			return imageCode;
		}	
	};
}

/******************************************************************************
 *	функции для jquery
 */

/*
 *	работа с куками
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

/*
 *	Определение позиции
 */
jQuery.prototype.sAbsPosition = function(){
	var obj = this[0], x = 0,	y = 0;
    while(obj) {
		x += obj.offsetLeft;
		y += obj.offsetTop;
		obj = obj.offsetParent;
	}
	return {left:x, top:y};
}



	
   