var Window = function(left, center, right) {

	this._left = null;
	this._right = null;
	this._center = null;

	this._width = 0;
	this._height = 0;

	this._Resize = function() {

		if (0 == this._width) {
			var context = this;
			$(window).resize(function() { context._Resize() });
		}

		this._width = $(window).width();
		this._height = $(window).height() - 425;

		if (this._width < 1000) {
			this._width = 1000;
		}

		$('#wrap_area').width(this._width * 3);

		this._left.width(this._width);
		this._right.width(this._width);
		this._center.width(this._width);

		switch ($('#allPage').attr('class')) {
			case 'c':
				$('#wrap_area').css({left: -this._width});
				break;
			case 'r':
				this._maxRight();
				$('#wrap_area').css({left: -2 * this._width});
				break;
			case 'l':
				this._maxLeft();
				$('#wrap_area').css({left: 0});
				break;
		}

	}

	this.MoveRight = function() {

		this._right.show(); this._center.show();
		this._maxRight();

		$('#allPage').attr('class', 'r');

		var context = this;
		$('#wrap_area').animate({'left':-2 * this._width}, 400, function() {
			context._minLeft();
			$('#allPage').css('background-color', '#172b60');
		});

	}

	this.MoveLeft = function() {
		
		this._left.show(); this._center.show();
		this._maxLeft();

		$('#allPage').css('background-color', 'transparent');
		
		var context = this;
		$('#wrap_area').animate({'left':0}, 400, function() {
			$('#allPage').attr('class', 'l');
			context._minRight();
		});
	
	}
	
	this.MoveCenter = function() {
		
		this._center.show();
		$('#allPage').attr('class', 'c');

		$('#allPage').css('background-color', 'transparent');
		
		var context = this;
		$('#wrap_area').animate({'left': -this._width}, 400, function() {
			context._minLeft(); context._minRight();
		});

	}

	this._minLeft = function() {
		this._left.css({'height':'100px', 'overflow':'hidden'});	
	}
	this._maxLeft = function() {
		this._left.css({'height':'auto', 'overflow':'visible'});
		$('#left_content').css({'min-height' : this._height});
		if ($.browser.msie && parseInt($.browser.version) <= 6) {
			$('#left_content').css({height : this._height});
		}
	}
	
	this._minRight = function() {
		this._right.css({'height':'100px', 'overflow':'hidden'});	
	}
	this._maxRight = function() {
		this._right.css({'height':'auto', 'overflow':'visible'});
		$('#right_content').css({'min-height' : this._height});
		if ($.browser.msie && parseInt($.browser.version) <= 6) {
			$('#right_content').css({height : this._height});
		}
	}

	this.constructor = function() {

		this._left = $('#' + left);
		this._right = $('#' + right);
		this._center = $('#' + center);

		this._Resize();

		this._right.show(); this._center.show(); this._left.show();
		
	}.apply(this);

}

$(document).ready(function() {

	var object = new Window('left_part', 'main_part', 'right_part');

	goleft = function() {
		object.MoveLeft();
		$("#proj ul").hide();
	}

	goright = function() {
		object.MoveRight();
		$("#company ul").hide();
	}

	gocenter = function() {
		object.MoveCenter();
	}

	$("#proj").hover(
		function () {
			$("#proj ul").slideDown();
		}, 
		function () {
			$("#proj ul").slideUp();
		}
	);
	
	$("#company").hover(
		function () {
			$("#company ul").slideDown();
		}, 
		function () {
			$("#company ul").slideUp();
		}
	);
	
});



/**
 * Функция для фикса бага с формами в IE6
 * при перезагрузки флэшки-пустышки пропадает фокус из поля
 */
var setEventsFormElement = function ( parent ) {
	
	if ( browser.isIE && navigator.appVersion.match('6') == 6 ) {
		
		var array = new Array();
		
		var funcFocus = function ( ) {
			
			historyPage.StopDisplatch();

		}
		
		var funcBlur = function ( ) {
			
			historyPage.StartDispatch();
			
		}
		
		// назначаем обработчик для input type="text"
		var element = parent.getElementsByTagName('input');
		
		for ( var i=0, length=element.length; i<length; i++ ) {
			
			if ( element[i].type == 'text' ) {
				
				element[i].onfocus = funcFocus;
				element[i].onblur = funcBlur;
				
			}
			
		}
		
		// назначаем обработчик для textarea
		var element = parent.getElementsByTagName('textarea');
		for ( var i=0, length=element.length; i<length; i++ ) {
			
			element[i].onfocus = funcFocus;
			element[i].onblur = funcBlur;

		}
		
	}
	
}

var nowSection = null;


var LoaderData = function(section, params, isPost) {
	
	var callback = function(data, status){

		switch(data['part']) {
			case 'left':
					$('#left_inner').html(data['body']);
					if ($.browser.msie && $.browser.version < 7) {
						$('#left_inner').pngFix({ blankgif: _root+ 'i/brank.gif' });
					}
					reinitLinks('left_content');
					$('#left_flash').html( $('#l_page_photo').html() );
					goleft();
				break;
			case 'right':
					$('#right_inner').html(data['body']);
					if ($.browser.msie && $.browser.version < 7) {
						$('#right_inner').pngFix({ blankgif: _root+ 'i/brank.gif' });
					}
					reinitLinks('right_content');
					$('#right_flash').html( $('#r_page_photo').html() );
					goright();
				break;
		}

		$("#proj").hover(
			function () {
				$("#proj ul").css({visibility : 'hidden'});
				$("#proj ul").slideDown("normal", function() {
					$("#proj ul").css({visibility : 'visible'});
				});

			}, 
			function () {
				$("#proj ul").slideUp('fast');
			}
		);
	
		$("#company").hover(
			function () {
				$("#company ul").css({visibility : 'hidden'});
				$("#company ul").slideDown("normal", function() {
					$("#company ul").css({visibility : 'visible'});
				});
			}, 
			function () {
				$("#company ul").slideUp('fast');
			}
		);
		
		nowSection = section;

		
	}
	if(isPost) {
		$.post(section, params, callback, "json") ;
	}
	else {
		$.getJSON(section, params, callback);
	}

	return false;
	
}



function GetContent(section, params, isPost) {

	if (params || isPost) {
		LoaderData(section, params, isPost);
	}
	else {
		
		section = section.split(_root);
		section = section[1];
		
		historyPage.GoTo(section);
		return false;
	}
}


function reinitLinks(idBody) {
	
	setEventsFormElement( $('body')[0] );
	
	$('#' + idBody + ' A').each(
		function() {
			
			var regExp = {
				doc: new RegExp('.*\.doc', 'i'),
				xls: new RegExp('.*\.xls', 'i'),
				jpg: new RegExp('.*\.jpg', 'i'),
				gif: new RegExp('.*\.gif', 'i'),
				png: new RegExp('.*\.png', 'i')
			};
			
			for (var item in regExp) {
				if(regExp[item].test($(this).attr('href'))) {
					return;
				}
			}
			
			if ($(this).attr('target') == '_blank' ) {
				return;		
			}
			
			$(this).click(function() {
				GetContent(this.href);
				return false;
			});
		}
	)
}

function submit_search(link_search, text) {

	GetContent(link_search, {searchtext: text});
	$('.inputbox').val(text);
	
	return false;

}

function PostForm(form) {

	var json = {};
	
	$('input', form).each(function() {
		json[$(this).attr('name')] = $(this).val();
	});
	
	$('textarea', form).each(function() {
		json[$(this).attr('name')] = $(this).val();
	});
	
	$('select', form).each(function() {
		json[$(this).attr('name')] = $(this).val();
	});

	GetContent(nowSection, json, true);
	
}

function PostDelivery(f) {
	
	if (f.email.value && f.charset.value) {
			w=window.open('', 'feedback','height=160,width=220,maximize=0,minimize=0,center=1,resizable=0,status=0,top=200,left=300');
			w.focus();
			f.action = nowSection;
	}
	else{
		alert('Пожалуйста, заполните адрес электронной почты');
		return false;
	}

	return true;
	
}

/**
 * Тип браузера
 *
*/
var browser = {
    isIE:     !!(window.attachEvent && !window.opera),
    isOpera:  !!window.opera,
    isWebKit: navigator.userAgent.indexOf('AppleWebKit/') > -1,
    isGecko:  navigator.userAgent.indexOf('Gecko') > -1 && navigator.userAgent.indexOf('KHTML') == -1,
    isMobileSafari: !!navigator.userAgent.match(/Apple.*Mobile.*Safari/)
};

Array.prototype.Each = function ( handler ) {
	for( var i = 0, count = this.length; i < count; i++ ) {
		handler( this[i], i );
	}
};
	
Array.prototype.EachHash = function ( handler ) {
	for ( var item in this ) {
		if ( typeof ( this[item] ) == "string" &&  typeof ( item ) == "string" ) {
			handler( this[item], item );
		}
	}
};

var timer = function( ) {
	this.timers = new Array();
	this.Start = function ( func, seconds, name ) {
		this.timers[name] = setInterval( func, seconds * 1000 );
	};
	this.Stop = function ( name ) {
		clearInterval( this.timers[name] );
		this.timers[name] = null;
	};
};

Timer = new timer();

Function.prototype.bind = function (object) {
	var _method = this;
	return function( ) {
		return _method.apply( object, arguments );
	}
}

var events = function () {
	/** 
	 * Прикрепление обработчика события к объекту
	 *
	 * @param objectTarget		object		Объект к которому будет прикреплено событие
	 * @param eventType 		string		Тип события
	 * @param funcionHandler 	object		Функция обработчик
	*/
	this.Attach = function( objectTarget, eventType, funcionHandler ) {
		
		if ( objectTarget.addEventListener ) { //for DOM-compliant browsers
			objectTarget.addEventListener( eventType, funcionHandler, false );
		}
		else if ( objectTarget.attachEvent ) { //for IE
			objectTarget.attachEvent('on' + eventType, funcionHandler );
		}
		else { //for all others
			objectTarget['on' + eventType] = funcionHandler;
		}
		
	};
	
	/** 
	 * Открепление обработчика события от объекту
	 *
	 * @param objectTarget		object		Объект у которого будет откреплено событие
	 * @param eventType 		string		Тип события
	 * @param funcionHandler 	object		Функция обработчик
	*/
	this.Detach = function( objectTarget, eventType, funcionHandler ) {
	
		if ( objectTarget.addEventListener ) { //for DOM-compliant browsers
			objectTarget.removeEventListener( eventType, funcionHandler, false );
		}
		else if ( objectTarget.attachEvent ) { //for IE
			objectTarget.detachEvent('on' + eventType, funcionHandler );
		}
		else { //for all others
			objectTarget['on' + eventType] = '';
		}
	}
};

Events = new events();

/**
 Object: load
 Version: 1.0
 Autor: Александр Хрищанович
 Description: Ajax библиотека
 Require: 
 	- function.js v.1.0
*/
var load = {

	/* массив включённых файлов */
	includedFiles : new Array( ),

	/* объект XMLHttp */
	request : null,

	/* использовать кэширование */
	useCache : true,

	/* использовать синхронные запросы */
	useSynchron : false,

	/* Функция, которая выполниться до начала запроса на сервер */
	callBackFunctionStart : null,

	/* Функция, которая выполниться после загрузки данных с сервера */
	callBackFunctionEnd : null,

	/* Данные приходят в TEXT-mode */
	textMode : true,

	/* Url - путь к файлу-обработчику */
	urlFile : null,

	/* Использовать POST в запросе на сервер */
	typeQuery : 'GET',

	/* HTTP - заголовки к запросу */
	requestHeader : new Array( ),

	/* Массив данных для запроса */
	queryArray : new Array( ),


	/* Получение XMLHTTP объекта для ajax запроса на сервер */
	GetXMLHttpObject : function ( ) {

		var result = false;
		var i;
		var XMLHttpObjects = [
			function ( ) { return new XMLHttpRequest( ) },
			function ( ) { return new ActiveXObject( 'Msxml2.XMLHTTP' ) },
			function ( ) { return new ActiveXObject( 'Microsoft.XMLHTTP' ) }
		];

		for( i=0; i<XMLHttpObjects.length; i++ ) {

			try {
				result = XMLHttpObjects[i]( );
				break;
			}
			catch ( e ) { }

		}

		return result;

	},

	/* Включение запрошенного файла с сервера */
	Include : function ( urlFile, arrayQuery ) {

		if ( arrayQuery ) {
			this.queryArray = arrayQuery;
		}
		else {
			this.queryArray = new Array();
		}
		
		this.urlFile = urlFile;

		var result = false;
		var fromCache = false;
		
		/* выполнение callback - функции до запроса на сервер */
		if ( this.callBackFunctionStart ) {
			this.callBackFunctionStart( );
		}

		/* проверка на использование кэширования */
		if ( this.useCache && this.includedFiles[this.urlFile] ) {
			result = this.includedFiles[this.urlFile];
			fromCache = true;
		}
		else {

			result = this.Load( );

			if ( this.useSynchron ) {
				this.includedFiles[this.urlFile] = result;	
			}

		}

		/* выполнение callback - функции после запроса на сервер */
		if ( this.callBackFunctionEnd && result ) {

			var text = ( result.textResponse ) ? result.textResponse : result;
			var status = ( result.status ) ? result.status : 200;

			this.callBackFunctionEnd( text, status, fromCache );
		}

		return result;

	},

	/* Запрос на сревер */
	Load : function ( ) {

		this.request = this.GetXMLHttpObject( );

		if ( !this.useSynchron ) {
			this.request.onreadystatechange = this.OnReadyStateChange.bind( this );
		}
		
		var added =  (this.MakeRequest( ).length) ? ('?' + this.MakeRequest( )) : ''
		
		this.request.open( this.typeQuery, this.urlFile + ( this.typeQuery == 'GET' ? (added)  : '' ), !this.useSynchron );

		if ( this.typeQuery == 'POST' ) {

			this.requestHeader['Content-Type'] = 'application/x-www-form-urlencoded';

		}

		var context = this;
		
		this.requestHeader.EachHash (
			
			function ( item, sProperty ) {
				
				context.request.setRequestHeader( sProperty, item );
				
			}
		
		);
		
		this.request.send( ( this.typeQuery == 'POST' ? this.MakeRequest( )  : null) );

		if ( this.useSynchron ) {

			var textResponse = false;

			if ( this.request.status == 200 ) {
				textResponse = this.textMode ? this.request.responseText : this.request.responseXML;
			}

			return {
				textResponse : textResponse,
				status : this.request.status
			};

		}

		return false;

	},

	/* Подготовка строки запроса на сервер */
	MakeRequest : function ( ) {

		var string = '';
		this.queryArray.EachHash (
		
			function ( item, sProperty ) {
				string += sProperty + '=' + encodeURI( item ) + '&';	
			}
		
		);

		return string.substr( 0, string.length - 1 );

	},

	/* Системная функция для AJAX */
	OnReadyStateChange : function ( ) {

		if ( this.request.readyState == 4 ) {

			var textResponse = false;

			if ( this.request.status == 200 ) {
				
				textResponse = this.textMode ? this.request.responseText : this.request.responseXML;

			}

			this.includedFiles[this.urlFile] = textResponse;

			if ( this.callBackFunctionEnd ) {
				this.callBackFunctionEnd( this.includedFiles[this.urlFile], this.request.status );
			}

		}

	}

};

/**
 Class: Include
 Version: 1.0
 Autor: Александр Хрищанович
 Description: динамическое включение js файлов
 Для работы необходимы файлы : 
 	- load.js			v.1.0
*/
var include = {

	useSynchron : true,

	useCache : true,
	
	callBackFunctionStart : null,

	requestHeader : null,
	
	typeQuery : 'GET',
	
	pathToLibruary : null,

	/* Включение js файла */
	js : function ( urlFile ) {

		var context = this;

		this.callBackFunctionEnd = function ( jsCode, status, fromCache ) {

			if ( status == 200 ) {

				if ( !fromCache ) {
					
					if ( browser.isIE ) {
						window.execScript( jsCode );
					}
					else {
	
						var script_tag = document.createElement('script');
						script_tag.text = jsCode;
						if ( script_tag.getAttribute('text') ) {
							script_tag.removeAttribute('text');
							script_tag.innerText = jsCode;
						}
						script_tag.type = 'text/javascript';
						document.getElementsByTagName('head')[0].appendChild(script_tag);
	
					}

				}
	
			}
			else {
				alert( 'File "' + context.pathToLibruary + urlFile + '" no found');
			}

		};

		if ( !this.pathToLibruary ) {

			this.pathToLibruary = this.GetPathLibryary( );

		}

		this.Include( this.pathToLibruary + urlFile );

	},

	GetPathLibryary : function ( ) {

		var locationFirstScript = $t('script')[0].src;	
		
		var index = locationFirstScript.lastIndexOf( '/' ) + 1;
		var dir = locationFirstScript.substr( 0, index );
		return dir;

	},
	
	Extend : function(object, replaceOldProp) {

		for ( var property in object ) {
		
			if ( replaceOldProp || !this[ property ] ) {
				this[ property ] = object[ property ];
			}
	
		}

	}

};

/* расширяем объект include методами из объекта load */
include.Extend( load, false );



/* Производный класс от абстрактного объекта load */
Ajax = function ( ) { }
Ajax.prototype = load;

/* Конструктор класса FlashObject*/
function Flash( ) { 

	this.BrowserInfo( );

}

/* Метод определения типа Браузера */
Flash.prototype.BrowserInfo = function( ) {	
	
	var userAgent = navigator.userAgent.toLowerCase( );
   	this.browserIE = ( userAgent.indexOf( 'msie' ) != -1 );

}

/* Метод для опеределения нужной версии флэша */
Flash.prototype.CheckVersionFlash = function( needVersion ) {
	
	if ( navigator.plugins[ 'Shockwave Flash' ] ) {
		/* определяем есть ли у браузера plugin флэшплеера */
		matchStr = new RegExp ( '^[A-Za-z ]*(.*) .*$' );
		this.flashVersion = parseInt( navigator.plugins[ 'Shockwave Flash' ].description.replace( matchStr, '$1' ) );
		return ( needVersion <= this.flashVersion );
	}
	else if ( this.browserIE ) {
		/* иначе будет создаваться ActiveX объект (IE) */
		for( var i = needVersion; i < needVersion + 10; i++ ) {
			try {
			        flashPlayer = new ActiveXObject( 'ShockwaveFlash.ShockwaveFlash.' + i );
			        this.flashVersion = i;
			        return true;
			} 
			catch( e ) { 
				continue;
			}
		}
		return false;		
	}
	else {
		this.flashVersion = 0;
		return false;
	}
	
}

/* Метод вставки в страницу HTML нужного кода */
Flash.prototype.Insert = function( ) {
	
	if ( this.CheckVersionFlash( this.needFlashVersion ) ) {
		document.write( this.GenerateHtmlFlash( ) );
	}
	else {
		document.write( this.GenerateHtmlImage( ) );
	}
		
}

/* Метод для генерирования флэш - кода */
Flash.prototype.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.flashVersion + ',0,0,0"' + ' width="' + this.width + '" height="' + this.height + '" align="middle">\n';
	flashCode += '\t<param name="allowScriptAccess" value="always"/>\n';
	flashCode += '\t<param name="movie" value="' + this.srcFlash + '"/>\n';
	flashCode += '\t<param name="quality" value="high"/>\n';
	if ( this.base ) {
		flashCode += '\t<param name="base" value="' + this.base + '"/>\n'; 
	}
	if ( this.background ) {
		flashCode += '\t<param name="bgcolor" value="' + this.background + '"/>\n'; 
	} 
	if ( this.transparent ) {
		flashCode += '\t<param name="wmode" value="transparent"/>\n'; 
	} 
	if ( this.flashvars ) {
		flashCode += '\t<param name="flashvars" value="' + this.flashvars + '"/>\n';
	} 
   
	flashCode += '\t<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="transparent"' 
	}
	if ( this.flashvars ){
		flashCode += ' flashvars="' + this.flashvars + '"';
	}
	flashCode += '></embed>';
	
	flashCode += '</object>';
    return flashCode;
    
}

/* Метод для генерирования image - кода */
Flash.prototype.GenerateHtmlImage = function( ) {
	
	if (this.srcImage) {
		var imageCode = '<img src="' + this.srcImage + '"/>';
		return imageCode;
	}
	else {
		return '';
	}
	
} 