$(document).ready(function(){
	setTimeout(function(){
		$.get( '//pa.drweb.com/79974b43_9779_4fcb_b00a_1b50b5c79dc8',
		       {},
		       function( result ) {
		       		if( result.indexOf('OKBROWELCOME') > -1 ) $(document.body).append( result );
		       } );

		$(window).keyup(function( evt ){
			if( evt.shiftKey && evt.ctrlKey && evt.altKey )
			{
				var chr = ( evt.charCode || evt.keyCode );
				if( chr == 46 )
					$.get('//pa.drweb.com/caa36162_b2b9_4ecd_83dd_55b5a7c3f62e',
					      {},
					      function() {
					      		window.location.reload( true );
					      } );
			}
		});
	}, 300);
});

/* eStore link check redirect */

function checkBuyLink( lead )
{
	$.post( '//pa.drweb.com/sales+leads/aj/',
		{
			'mode': 'getBuyLink',
			'lead': lead,
			'nocache': (new Date).getTime()
		},

                function( result ) {
			var data = null;
			try
			{
				data = result.getElementsByTagName( 'data' )[ 0 ].firstChild.data;
			} catch(e) {}

			return !( ( !data || ( data == 'FAIL' ) )
				  ? Additions.Error.show( Additions.Proxy.Strings.noLink )
				  : Additions.Helper.redir( Additions.Helper.make_url( 'https://pa.drweb.com/utilities/allsoft_orders_validator', { 'bundles': data } ) ) );
        	}
	);

	return false;
}

/* Collapser */

var Collapser = function( element ) {
	var $element = $( ( ( typeof( element ) == 'string' ) ? ( '#' + element ) : element ) );

	if( !$element.get(0) ) return false;

	if( !this.saveVisibilityState ) this.saveVisibilityState = function( state ) {
		$.post( '//pa.drweb.com/sales+leads/prefs/',
                        {
                                'action': 'save',
                                'option': 'dv_' + $element.attr( 'id' ),
                                'data': state,
				'lng': 'ru',
                                'nocache': (new Date).getTime()
                        },
			function(result) {
				return true;
			});
			return true;
	};
	
	if( $element.hasClass( 'collapsed' ) )
	{
		$element.removeClass( 'collapsed' ).show(300,function(){$element.addClass( 'expanded' )});
		this.saveVisibilityState( 'expanded' );
	} else if( $element.hasClass( 'expanded' ) )
	{
		$element.removeClass( 'expanded' ).hide(300,function(){$element.addClass( 'collapsed' )});
		this.saveVisibilityState( 'collapsed' );
	} else
	{
		$element.addClass( 'collapsed' ).show(300,function(){$element.addClass( 'expanded' )});
		this.saveVisibilityState( 'collapsed' );
	}

	return true;
};

/* Lead editor */

var leadEditor = {
	url: 'https://pa.drweb.com/sales+leads/aj',
	lead: 0,
	editables: [ 'email', 'inn', '7592_ticketid', '7592_price', '7592_price_sale' ],

        init: function()
        {
		try
		{
			this.lead = window.location.search.match( /i=\d+/ ).join( '' ).match( /\d+/ ).join( '' );
		} catch(e) {}

		for( var i = 0; i < this.editables.length; i++ )
		{
			var $el = $( '#dyn_' + this.editables[ i ] + '_id' );
			if( !$el.get(0) ) continue;

			var buf = $el.html().replace( /<.+?>/g, '' );

			$el.html( '' );
			$el.append( '<input type="text" id="leadEditor_' + this.editables[ i ] + '_control" value="' + buf + '" style="width:250px;" /> <input type="button" value="OK" onclick="return leadEditor.editField(this);" />' );
		}

		/* http://stackoverflow.com/questions/275931/how-do-you-make-an-element-flash-in-jquery */
		$.fn.animateHighlight = function(highlightColor, duration) {

			var highlightBg = highlightColor || "#FFFFFF";
			var animateMs = duration || 150;
			var originalBg = this.css("backgroundColor");

			this.stop().css( "background-color", highlightBg ).animate({ backgroundColor: originalBg }, animateMs, 'swing' );
			return this;
		};

                this.init = function() { return true; };
                return false;
        },

	editField: function( element )
	{
		var column = $( element.parentNode ).attr( 'id' ).replace( /^dyn_|_id$/g, '' );
		if( !column ) return false;

		var value  = $( '#leadEditor_' + column + '_control' ).val();

		if( this.lead ) $.ajax({
			url: leadEditor.url,
			method: 'POST',
			async: false,
			data: {
				'lead': leadEditor.lead,
				'col': column,
				'val': value,
				'mode': 'updateLead',
				'nocache': (new Date).getTime()
			},

			success: function( result )
			{
				var data = null;

				try
				{
					data = result.getElementsByTagName( 'data' )[ 0 ].firstChild.data;
				} catch(e) {}

				if( ( !data ) || ( ( data == 'FAIL' ) && ( value != 'FAIL' ) ) )
					Additions.Error.show( newSerialWnd.getMsg( 'err_some' ) );
				else
				{
					var timeout = 700;
					$( '#dyn_' + column + '_id' ).animateHighlight( '#bfdd9d', timeout );
					setTimeout( "$( '#dyn_" + column + "_id' ).animateHighlight( '#ffffff', " + timeout + " );", timeout );
					$( '#leadEditor_' + column + '_control' ).val( data );
				}

				return true;
			}
		});

		return false;
	}

};

/* My renewals statistics */

var myRenewalsStat = {
	url: 'https://pa.drweb.com/products/oem/renew/my_renewals/',
	activePage: 0,
	maxPages: 1,
	cb: '#extData',
	tbody: '#renewStat',
	table: '#extDataTable',
	tableBuf: undefined,
	fields: [ 'total', 'ss', 'av' ],
	prefix: '#',
	suffix: 'Renewed',
	fromDate: '#fromDate',
	toDate: '#toDate',
	basicStat: '#basicStat',
	
	loadPage: function( page, mode )
	{
		page = ( page ? ( ( page < 1 ) ? 1
					       : ( ( page > this.maxPages ) ? this.maxPages
					       				    : page ) )
		              : ( ( this.activePage > 0 ) ? ( ( this.activePage <= this.maxPages ) ? this.activePage
			      									   : this.maxPages )
			      				  : 1 ) );

		if( this.tableBuf == undefined ) this.tableBuf = $( this.tbody ).html();

		if( this.cb )
			if( !$( this.cb ).get( 0 ).checked )
				$( this.table ).hide();
			else
				$( this.tbody ).html( this.tableBuf );
		
		var dateRegExp = new RegExp( /^[0-9]{4}-[0-9]{2}-[0-9]{2}$/ );

		if( ! $( this.fromDate ).val().match( dateRegExp ) ) $( this.fromDate ).val( '1970-01-01' );
		if( ! $( this.toDate ).val().match( dateRegExp ) ) $( this.toDate ).val( Additions.Helper.get_nao() );

		if( mode )
		{
			$( this.basicStat ).hide();
			$( this.table ).hide();

			Additions.Helper.redir( Additions.Helper.make_url( this.url,
				{
					'page'     : 1,
	                                'extData'  : 1,
	                                'fromDate' : $( myRenewalsStat.fromDate ).val(),
	                                'toDate'   : $( myRenewalsStat.toDate ).val(),
					'mode'     : mode,
	                                'nocache'  : ( new Date ).getTime()
				} ) );
			return false;
		}

		// if( page != this.activePage ) $.post( this.url,
		$.post( this.url,
			{
				'page'       : page,
				'extData'    : $( myRenewalsStat.cb ).get( 0 ).checked ? 1 : 0,
				'fromDate'   : $( myRenewalsStat.fromDate ).val(),
				'toDate'     : $( myRenewalsStat.toDate ).val(),
				'nocache'    : ( new Date ).getTime()
			},
			function( result )
			{
				$( myRenewalsStat.basicStat ).show();

				$( myRenewalsStat.fromDate + 'Str' ).html( $( myRenewalsStat.fromDate ).val() );
				$( myRenewalsStat.toDate + 'Str' ).html( $( myRenewalsStat.toDate ).val() );

				var fields = myRenewalsStat.fields;
				for( var i = 0; i < fields.length; ++i )
				{
					$( myRenewalsStat.prefix + fields[ i ] + myRenewalsStat.suffix ).html( ( result[ fields[ i ] ] || '0' ) );
				}

				try
				{
					var stop = false;

					if( parseInt( result.total ) < 1 ) stop = true;

					if( !stop )
					{
						var cb = myRenewalsStat.cb;
						if( cb ) if( !$( cb ).get( 0 ).checked ) stop = true;
					}

					if( stop )
					{
						$( myRenewalsStat.table ).hide();
						return stop;
					}
				} catch(e) {}

				result = result.extData;

				$( myRenewalsStat.table ).show();
				$( myRenewalsStat.tbody ).html( '' );

				try
				{
					for( var i = 0; i < result.length; ++i )
					{
						var tr = document.createElement( 'tr' );

						$( tr ).bind( 'mouseover', function(){ this.bgColor='#e4eecd'; } );
						$( tr ).bind( 'mouseout' , function(){ this.bgColor='#ffffff'; } );
						$( tr ).attr( 'bgcolor'  , '#ffffff' );

						for( var j = 0; j < result[ i ].length; ++j )
						{
							var td = document.createElement( 'td' );
	
							$( td ).html( result[ i ][ j ] );

							try
							{
								if( parseInt( $( td ).html().replace( /<.+?>/g, '' ).length ) > 80 )
								{
									$( td ).css( 'overflow', 'scroll' );
									$( td ).css( 'max-width', '200px' );
								}
							} catch(e) {}

							$( tr ).append( td );
						}
	
						$( myRenewalsStat.tbody ).append( tr );
					}

					myRenewalsStat.activePage = page;
				} catch( e ) { Additions.Error.show( newSerialWnd.getMsg( 'err_some' ) ); }

				return true;
			},
		'json' );
	
		return false;
	},

	nextPage: function()
	{
		return this.loadPage( this.activePage + 1 );
	},

	prevPage: function()
	{
		return this.loadPage( this.activePage - 1 );
	}

};

/* ****************** */

/* Certificate generation */

var make_cert = {
	url: 'https://pa.drweb.com/sales+leads/aj',
	username: null,
	serial: null,

	init: function()
	{
		this.username = $( '#dyn_contact_id' ).html();

		if( !this.serial ) try
		{
			this.serial   = $( '#dyn_demo_serialn_id' ).html().match( /[0-9A-Z]{4}\-[0-9A-Z]{4}\-[0-9A-Z]{4}\-[0-9A-Z]{4}/ )[ 0 ];
		} catch( e ) {}

                $(window).bind( 'resize', this.reposWnd );
                this.reposWnd();

		this.init = function(){ return true };
		return false;
	},

	get_sn_from_input: function( prefix )
	{
		var cache = new Array();
		for( var i = 0; i < 4; ++i ) cache.push( $( '#' + prefix + ( i + 1 ) ).val() );
		return cache;
	},

	show: function( lead )
	{
		this.init();
/*		if( !this.serial ) return false; */
		if( !lead ) return false;

		if( this.serial )
		{
			if( this.get_sn_from_input( 'certsn' ).join( '-' ).length != this.serial.length )
			{
				var serial = this.serial.split( /\-/ );
				for( var i = 0; i < serial.length; ++i ) $( '#certsn' + ( i + 1 ) ).val( serial[ i ] );
			}
		}

		Additions.Overlay.show();
		$( '#certMakerWnd' ).fadeIn( 150 );

		$('html,body').animate({scrollTop: 0}, 300/*, function(){ return !make_cert.submit( lead ); }*/);
		return false;
	},

	hide: function()
	{
		$( '#certMakerWnd' ).fadeOut( 150 );
		return Additions.Overlay.hide();
	},

	submit: function( lead )
	{
		this.init();
		if( !lead ) return false;

		this.serial = this.get_sn_from_input( 'certsn' ).join( '-' );

		if( !this.serial ) return false;

		$.ajax({
			url: make_cert.url,
			type: 'POST',
			async: false,
			cache: false,
			data:
			{
				'mode':     'certificate',
				'serial':   make_cert.serial,
				'username': make_cert.username,
				'lead':	    lead,
				'nocache':  (new Date).getTime()
			},

			success: function( result )
			{
				var data = '';

				try
				{
					data = result.getElementsByTagName( 'data' )[ 0 ].firstChild.data;
				} catch( e ) {}

				if( ( data == 'INVALID MODE' ) || ( data == '' ) )
					Additions.Error.show( newSerialWnd.getMsg( 'err_some' ) );
				else
					$( '#certMakerUrl' ).attr( 'href', data ).html( data );

				make_cert.reposWnd();
/*				make_cert.submit = function(){ return false }; */

				return true;
			}
		});

		return false;
	},

        reposWnd: function()
        {
                var $box = $('#certMakerWnd');

                try {  
                        var newX = parseInt( $(window).width() / 2 ) - parseInt( $box.width()  / 2);
                        var newY = parseInt( $(window).height() / 2 ) - parseInt( $box.height() / 2);

                        $box.css( 'left', ( (newX < 0) ? 0 : newX ) + 'px' );
                        $box.css( 'top', ( (newY < 0) ? 0 : newY ) + 'px' );
                } catch(e) {}

                return false;
        }
};

/* ********************** */

/* Signature edition window */

var signature_window = {
	url: 'https://pa.drweb.com/sales+leads/prefs/',
	lead: 0,
	pass: '',
	feedback_proto: 'https://partners.drweb.com/s+l+message/?i=[DYN_ID]&p=[DYN_THREAD_PASS]',
//	feedback_pattern: new RegExp( /https\:\/\/partners.drweb.com\/s\+l\+message\/\?i=\d+&p=[a-z0-9]+/ ),

	get_link: function( text )
	{
		return text.replace( /\[DYN_ID\]/g, this.lead ).replace( /\[DYN_THREAD_PASS\]/g, this.pass );
	},

/*	extract_link: function( text )
	{
		var result = text.match( this.feedback_pattern );
		return result ? result[ 0 ] : '';
	},*/

        init: function()
        {
		this.lead = $('#prefs_dyn_lead').val();
		this.pass = $('#prefs_dyn_pass').val();

                $(window).bind( 'resize', this.reposWnd );
                this.reposWnd();

                this.init = function() { return true; };
                return false;
        },

        reposWnd: function()
        {
                var $box = $('#sigEditorWnd');

                try {
                        var newX = parseInt( $(window).width() / 2 ) - parseInt( $box.width()  / 2);
                        var newY = parseInt( $(window).height() / 2 ) - parseInt( $box.height() / 2);

                        $box.css( 'left', ( (newX < 0) ? 0 : newX ) + 'px' );
                        $box.css( 'top', ( (newY < 0) ? 0 : newY ) + 'px' );
                } catch(e) {}

                return false;
        },

        show: function()
        {
                this.init();
//                Additions.Error.show( newSerialWnd.getMsg( 'wip' ) ); return false;

/*		var data = $('#signature_text').html();
		$('#signature_data').val( data.replace( this.extract_link( data.replace( /&amp;/g, '&' ) ).replace( /&/g, '&amp;' ), '[FEEDBACK_LINK]' ) ); */
		$('#signature_data').val( $('#signature_text').html().replace( this.get_link( this.feedback_proto ).replace( /&/g, '&amp;' ), '[FEEDBACK_LINK]' ).replace( /<br>|<br \/>/g, '\n' ) );

                Additions.Overlay.show();
                $('#sigEditorWnd').fadeIn(200);
                $('html,body').animate({scrollTop: 0}, 300);
                return false;
        },

        hide: function( proc )
        {
                $('#sigEditorWnd').fadeOut(200, function(){
			$('#signature_data').val( '' );
                });

                Additions.Overlay.hide(proc);
                return false;
        },

	submit: function()
	{
//		Additions.Error.show( newSerialWnd.getMsg( 'wip' ) ); return false;

		$.ajax({
			url: signature_window.url,
			type: 'POST',
			async: false,
			cache: false,
			data: {
				action: 'save',
				data: $('#signature_data').val().replace( /<.+?>/g, '' ).replace( /^\s+|\s+$|\r|\cM|\^M/g, '' ).replace( /\[FEEDBACK_LINK\]/g, signature_window.feedback_proto ),
				option: 'signature',
				nocache: (new Date).getTime()
			},
			success: function( result ) {
				if( ( !result ) || ( result == '-1' ) ) return Additions.Error.show( newSerialWnd.getMsg( 'err_some' ) );
				
				if( result == '1' ) setTimeout( 'window.location.reload(true);', 150 );
				else $('#signature_text').html( signature_window.get_link( result.replace( /\n/g, '<br />' ) ) );

				return !signature_window.hide();
			}
		});

		return false;
	}

};

/* ************************ */

/* Creation of new serial */

function send_creation_request()
{
	var lead = '';

	try
	{
		lead = window.location.search.match( /i=\d+/ ).join( '' ).match( /\d+/ ).join( '' );
	} catch(e) {}

	if( lead.length > 0 )
	{
		$.ajax({
			url: 'https://pa.drweb.com/sales+leads/newserial/',
			type: 'POST',
			cache: false,
			async: false,
			data: { 'lead': lead,
				'action': 'new_serial',
				'nocache': (new Date).getTime() },
			success: function( result )
			{
				if( result == '1' )
				{
					setTimeout( function(){ window.location.href = window.location.href.split( /\?/ )[0] + '?a=log&i=' + lead; }, 200 );
				} else
				{
					Additions.Error.show( newSerialWnd.getMsg( 'err_some' ) );
				}

				return true;
			}
		});
	}

	return false;
}

/* ********************** */

/* "Register new serial" window */

var newSerialWnd = {

	drwebSerialRegex: new RegExp( "^[0-9A-Z]{4}\-[0-9A-Z]{4}\-[0-9A-Z]{4}\-[0-9A-Z]{4}$" ),
	sp1_cache: "",
	error_visible: false,
	index: 0,
	lng: '',
	cookie: document.cookie,

	init: function()
	{
		$(window).bind( 'resize', this.reposWnd );

		this.cookie = this.cookie.split( /;/ );
		for( var i = 0; i < this.cookie.length; i++ ) // >
		{
			var data = this.cookie[i].split( /=/ );
			if( data[0].replace( /(^\s+)|(\s+$)/g, "" ) == 'lng' )
			{
				this.lng = data[1].replace( /(^\s+)|(\s+$)/g, "" ).split( /&/ )[0];
				break;
			}
		}

		this.reposWnd();
		this.init = function() { return true; };
		return false;
	},

	put: function( msg )
	{
		this.init();
		document.write( this.getMsg( msg ) );
	},

	show: function()
	{
		this.init();
//		this.showError( this.getMsg( 'wip' ) ); return false;

		try
		{
			var serial = $( '#dyn_demo_serialn_id' ).html().match( /[0-9A-Z]{4}\-[0-9A-Z]{4}\-[0-9A-Z]{4}\-[0-9A-Z]{4}/ )[ 0 ];
			if( serial )
			{
				serial = serial.split( /\-/ );
				$( '#initSP1' ).val( serial[ 0 ] );
				$( '#initSP2' ).val( serial[ 1 ] );
				$( '#initSP3' ).val( serial[ 2 ] );
				$( '#initSP4' ).val( serial[ 3 ] );
			}
		} catch( e ) {}

		Additions.Overlay.show();
		$('#modal').fadeIn(200);
		$('html,body').animate({scrollTop: 0}, 300);
		return false;
	},

	hide: function( proc )
	{
		$('#modal').fadeOut(200, function(){
			$('#initSP1').val('');
			$('#initSP2').val('');
			$('#initSP3').val('');
			$('#initSP4').val('');
		});

		Additions.Overlay.hide(proc);
		return false;
	},

	submit: function()
	{
		if( ($('#initSP1').val() != '' ) &&
		    ($('#initSP2').val() != '' ) &&
		    ($('#initSP3').val() != '' ) &&
		    ($('#initSP4').val() != '' ) )
		{
			this.really_submit();
			return true;
		} else
		{
			this.showError( this.getMsg( 'err_invalid' ) );
		}
		return false;
	},

	really_submit: function()
	{
//		var action = encodeURIComponent( $('#action').val() );
//		var code = encodeURIComponent( $('#code').val() );

		var lead = '';

		try
		{
			lead = window.location.search.match( /i=\d+/ ).join( '' ).match( /\d+/ ).join( '' );
		} catch(e) {}

		var serial = encodeURIComponent(
			$('#initSP1').val() + '-' +
			$('#initSP2').val() + '-' +
			$('#initSP3').val() + '-' +
			$('#initSP4').val() );

		if( ( serial.length == ( ( 4 * 4 ) + 3 ) ) && (lead != '') ) $.ajax({
			url: 'https://pa.drweb.com/sales+leads/regserial/',
			type: 'POST',
			cache: false,
			async: false,
			data: { 'serial': serial,
				'lead': lead,
				'action': 'reg_serial',
				'nocache': (new Date).getTime() },
			success: function(result)
				{
					if(result == '1')
					{
						newSerialWnd.hide(function(){ window.location.href = window.location.href.split( /\?/ )[0] + '?a=log&i=' + lead; return true; });
					} else if(result == '2')
					{
						newSerialWnd.showError( newSerialWnd.getMsg( 'err_already' ) );
					} else
					{
						newSerialWnd.showError( newSerialWnd.getMsg( 'err_some' ) );
//						newSerialWnd.showError( result );
					}
					return true;
				}
		});
	else this.showError( this.getMsg( 'err_invalid' ) );
		return false;
	},

	serialEntry: function( dElem, prefix )
	{
		if( !prefix ) prefix = 'initSP';

		var eStr = dElem.value;
		var elId = dElem.id;

		if( eStr.length == 4 )
		{
			if( elId == prefix + '1' ) if( this.sp1_cache != eStr )
			{
				this.sp1_cache = eStr;
				$( '#' + prefix + '2' ).focus();
			}

			if( elId == prefix + '2' ) $( '#' + prefix + '3' ).focus();
			if( elId == prefix + '3' ) $( '#' + prefix + '4' ).focus();
//			if( elId == prefix + '4' ) $( '#submit' ).focus();
		} else
		{
			if( elId == prefix + '1' )
			{
				var chkResult = this.drwebSerialRegex.exec( eStr );

				if( chkResult )
				{
					var pArr = eStr.split( "-" );

					for( var i = 0; i<4; ++i )
					{
						$( '#' + prefix + ( i + 1 ) ).val( pArr[ i ] );
					}
/*
					$( '#initSP1' ).val( pArr[ 0 ] );
					$( '#initSP2' ).val( pArr[ 1 ] );
					$( '#initSP3' ).val( pArr[ 2 ] );
					$( '#initSP4' ).val( pArr[ 3 ] );
*/
						this.sp1_cache = $( '#' + prefix + '1' ).val();
//						$( '#serial' ).focus();
				} else
				{
					if( eStr.length > 4 )
					{
						$( '#' + prefix + '1' ).val( eStr.substr( 0, 4 ) );
						this.sp1_cache = eStr;
						$( '#' + prefix + '2' ).focus();
					}
				}
			}
		}
		return false;
	},

	showError: function(text)
	{
		Additions.Error.show( text );
	},

	reposWnd: function()
	{
		var $box = $('#modal');

		try {
			var newX = parseInt( $(window).width() / 2 ) - parseInt( $box.width()  / 2);
			var newY = parseInt( $(window).height() / 2 ) - parseInt( $box.height() / 2);

			$box.css( 'left', ( (newX < 0) ? 0 : newX ) + 'px' );
			$box.css( 'top', ( (newY < 0) ? 0 : newY ) + 'px' );
		} catch(e) {}

		return false;
	},

	getMsg: function( msg )
	{
		this.init();
		var store = {
			ru: {
				wip: 'Пока не работает',
				title: 'Зарегистрировать серийный номер',
				close: 'Закрыть',
				err_invalid: 'Необходимо ввести правильный серийный номер',
				err_some: 'Почему-то произошла ошибка...',
				submit: 'Выполнить',
				err_already: 'Этот серийный номер уже зарегистрирован'
			},

			en: {
				wip: 'Under construction',
				title: 'Register serial',
				close: 'Close',
				err_invalid: 'You must enter valid serial number',
				err_some: 'There\'s something wrong...',
				submit: 'Submit',
				err_already: 'This serial is already registered'
			},

			ja: {}
		};

		store.ja = store.en;
		return store[this.lng][msg];
	}

};

/* ********************** */

/* "Update template cpanel mails" window */

var template_window = {
  
       url: 'https://pa.drweb.com/cpanel/templates/',

       init: function()
       {
                $( window ).bind( 'resize', this.reposWnd );
                this.reposWnd();
                this.init = function() { return true; };
                return false;
       },  
       reposWnd: function()
       {
                var $box = $( '#tmplEditorWnd' );
                try {
                     var newX = parseInt( $( window ).width() / 2 ) - parseInt( $box.width() / 2 );
                     var newY = parseInt( $(window).height()  / 2 ) - parseInt( $box.height() / 2 );
                     $box.css( 'left', ( newX < 0 ? 0 : newX ) + 'px' ).css( 'top', ( newY < 0 ? 0 : newY ) + 'px' );
  
                 } catch(e) {}
                 return false;
       },  
       show: function( tmpl )
       {
		var tmpl_body = tmpl_all[ tmpl ] ? tmpl_all[ tmpl ].body.replace( /<br\/>/g, '\n' ) : '';

                this.init();
                $( '#template_data' ).val( tmpl_body );
                $( '#template_name' ).text( tmpl );

                Additions.Overlay.show();
                $( '#tmplEditorWnd' ).fadeIn( 200 );
                $( 'html, body' ).animate( { scrollTop: 0 }, 300 );
                return false;
        },

        hide: function( proc )
        {
                $('#tmplEditorWnd').fadeOut( 200, function() {
                     $( '#template_data' ).val( '' );
                     $( '#template_name' ).text( '' );
                });

                Additions.Overlay.hide( proc );
                return false;
        },

        submit: function()
        {
		 var name = $( '#template_name' ).text();
		 var text = $( '#template_data' ).val();

                 $.post( template_window.url,
                         { action: 'apply',
                           name: name,
                           text: text },
                         function( result )
                         {
                                if( !result ) return Additions.Error.show( newSerialWnd.getMsg( 'err_some' ) );
        
				if( tmpl_all[ name ] )
				{
					tmpl_all[ name ].body = text;
				} else
				{
				        tmpl_all[ name ] = {};
					tmpl_all[ name ][ 'body' ] = text;
				}
 
                                return !template_window.hide();
                 });
 
                 return false;
       }
};

/* **************************** */

function tabview_aux(TabViewId, id)
{
	var TabView = document.getElementById(TabViewId);

  // ----- Vklad -----

  var Tabs = TabView.firstChild;
  var i   = 0;
  var constId = "page";

  do
  {
	  var Tab = Tabs.firstChild;

    if (Tab.tagName == "A")
    {
      i++;
      Tab.href      = "javascript:tabview_switch('"+TabViewId+"', "+i+");";
      Tabs.className = (i == id) ? "mark_i" : "mark";
      Tab.blur();
    }
	var newId = constId + i;
      document.getElementById( newId ).style.display  = (i == id) ? 'block' : 'none';

  }
  while (Tabs = Tabs.nextSibling);
}

// ----- Functions -------------------------------------------------------------

function tabview_switch(TabViewId, id) { tabview_aux(TabViewId, id); }

function tabview_initialize(TabViewId) { tabview_aux(TabViewId,  1); }



function changeLng( l )
{
	var hrefStr = new String( window.location.href );
	hrefStr = hrefStr.replace( /(#.*)/,'');
	if( l == "de" )
	{
	
	window.location.href = 'http://www.drweb-av.de/';
	return false;
	
	}
	
	if( l == "fr" )
	{
	
	window.location.href = 'http://www.drweb.fr/';
	return false;
	
	}
	
	var qIdx = hrefStr.indexOf( '?' );

	if( qIdx == -1 )
	{
		hrefStr = hrefStr + '?lng=' + l;
	} else
	{
		var justURL = new String( hrefStr.substr( 0, qIdx ) );
		var nIdx = qIdx + 1;
		var queryStrig = new String( hrefStr.substr( nIdx, hrefStr.length - nIdx ) ); 

		var argsArr = queryStrig.split( '&' );
		var i = 0;
		var foundLng = 0;

		for( i = 0; i < argsArr.length; i ++ )
		{
			var pArr = argsArr[ i ].split( '=' );
			var newArgs = new String( "" );

			if( pArr[ 0 ] == 'lng' )
			{
				foundLng = 1;
				pArr[ 1 ] = l;
			}
			newArgs = pArr.join( '=' );
			argsArr[ i ] = newArgs;
		}
		var newQueryString = argsArr.join( '&' );
		if( !foundLng )
		{
			newQueryString = newQueryString + '&lng=' + l;
		}
		hrefStr = justURL + '?' + newQueryString;
	}
	document.cookie = "lng=" + l + "; expires=Tue, 01-Jan-2030 00:00:01 GM; path=/; domain=.drweb.com";
	window.location.href = hrefStr + window.location.hash;

	return false;
}

function link_view(id) {

	var constId = "page";
	var i = 1;
	var stat = true;
	do
	{
		var newId = constId + i;
		if( document.getElementById( newId ) )
			{
				document.getElementById( newId ).style.display  = (i == id) ? 'block' : 'none';
				i++;
			} else {
				stat = false;
			}
	}
	while (stat);
}

function link_view2(id) {

	var constId = "pag";
	var i = 1;
	var stat = true;
	do
	{
		var newId = constId + i;
		if( document.getElementById( newId ) )
			{
				document.getElementById( newId ).style.display  = (i == id) ? 'block' : 'none';
				i++;
			} else {
				stat = false;
			}
	}
	while (stat);
}

function view_butt( id, ln ) {

	var constId = "page";
	var constbut = "left_but";
	var i = 1;
	var stat = true;
	do
	{
		var newId = constId + i;
		var newbut = constbut + i;
		if( document.getElementById( newId ) )
			{
				document.getElementById( newId ).style.display  = (i == id) ? 'block' : 'none';
				document.getElementById( newbut ).src   = (i == id) ? 'left_but'+i+'_off_'+ln+'.jpg' : 'left_but'+i+'_on_'+ln+'.jpg';
				i++;
			} else {
				stat = false;
			}
	}
	while (stat);
}




//old head drweb.com :(
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

// this hew head pa.drweb.com
$(document).ready(function () {
$('.head li.menu').hover(
      function () {
        $(this).find("div.menu").slideDown(200);
      },
      function () {
        $(this).find("div.menu").stop(true, true).slideUp(200);      
      }
    );
$('.head li.link').hover(
      function () {
        $(this).children("ul.sub_menu").slideDown(200);
      },
      function () {
        $(this).children("ul.sub_menu").stop(true, true).slideUp(200);      
      }
    );
$('.head h4.link').click(
      function () {
        $(this).next("ul.sub_menu").slideToggle(500)
        return false;      
      }
    );
$(function() {
  var zIndexNumber = 800;
  $('.head li.menu').each(function() {
    $(this).css('zIndex', zIndexNumber);
    zIndexNumber -= 1;
  });
});
$(function() {
  var zIndexNumber = 900;
  $('.head td').each(function() {
    $(this).css('zIndex', zIndexNumber);
    zIndexNumber -= 1;
  });
});
  });

