var IE = '\v' == 'v';
var content_shown = false;


var getBounds = function (obj) {
	var left, top;
	var ObjWidth = obj.offsetWidth;
	var ObjHeight = obj.offsetHeight;
    left = top = 0;
    if (obj.offsetParent) {
        do {
            left += obj.offsetLeft;
            top  += obj.offsetTop;
        } while (obj = obj.offsetParent);
    }

    return {		
        x : left,
        y : top,
		width: ObjWidth,
		height: ObjHeight
    };
}

function initArrowMove()
{
	setInterval(ArrowMove, 500);
	$('menu').getElement('.arrow').set('morph', {duration:500, transition: Fx.Transitions.Quint.easeOut});
	$('menu').getElement('.arrow div').set('morph', {duration:100});
}

function ArrowMove()
{
	var arrow = $('menu').getElement('.arrow');
	if (arrow.state == 1) {
		arrow.morph({'marginLeft' : 92, 'marginTop': -12})
		if (!IE) {
			arrow.getElement('div').morph({'opacity' : 1});
		} else {
			arrow.getElement('div').setStyle('visibility', 'visible');
		}
		arrow.state = 0;
	} else {
		arrow.morph({'marginLeft' : 98, 'marginTop': -18})
		if (!IE) {
			arrow.getElement('div').morph({'opacity' : 0});
		} else {
			arrow.getElement('div').setStyle('visibility', 'hidden');
		}
		arrow.state = 1;
	}
}

function initLigthVersionMorph() 
{
	$('light').getElement('a').set('morph', {duration:1000});
	setInterval(LightVersionLinkColor, 1000);
}

function LightVersionLinkColor()
{
	var lighta = $('light').getElement('a');
	if (lighta.color == 1) {
		lighta.morph({'color' : '#FFF'})
		lighta.color = 0;
	} else {
		lighta.morph({'color' : '#a5f600'})
		lighta.color = 1;
	}
}

var subMenuTimeout;

function initSubMenu()
{
	$('submenu').inv_height = $('submenu').getElement('.content').offsetHeight + 10;
	if (!IE) {
		$('submenu').setStyle('opacity', 0);
	}
	$('submenu').getElements('a').each(function(el){
												el.addEvent('click', function(){ hideSubMenu(true); })
												
												
												});
	$('menu').getElement('.a2').addEvents({
												'mouseenter': function () {
													showSubMenu();
						 					    },
												'mouseleave': function () {
													subMenuTimeout = setTimeout('hideSubMenu()', 50);
												}
												});
	$('submenu').addEvents({
												'mouseenter': function () {
													showSubMenu();
						 					    },
												'mouseleave': function () {
													subMenuTimeout = setTimeout('hideSubMenu()', 50);
												}
												});
}

function showSubMenu() 
{
	if (subMenuTimeout) {
		clearTimeout(subMenuTimeout);
	}
	$('submenu').set('morph', {duration:500, transition: Fx.Transitions.Quart.easeOut});
	$('submenu').morph({'height': $('submenu').inv_height, 'opacity': 1});
}

function hideSubMenu(fast)
{
	$('submenu').set('morph', {duration:fast ? 1 : 500, transition: Fx.Transitions.Quart.easeIn});
	$('submenu').morph({'height': 0, 'opacity' : IE ? 1 : 0});	
}

function initSearch()
{
	$('search').getElement('input').addEvents({
												'focus': function () {
													if (this.value == 'Поиск по сайту...') {
														this.value = '';
														this.setStyle('color', '#000');
													}
						 					    },
												'blur': function () {
													if (this.value == '') {
														this.value = 'Поиск по сайту...';
														this.setStyle('color', '#717171');
													}
												}
												});
}

var opened_block;
var side_disabled;

function initSideBlock()
{
	$('side_block').getElements('.list_item').each(function(el) {
																el.addEvents({									
																		  'click': function () {
																								openSideBlock(this.id);
																							   } ,
																		  
																		  'mouseenter': function () {
																			  					this.setStyles({'color': '#ffe04e'});
																		  						 },

																		  'mouseleave': function () {
																			  					this.setStyles({'color': '#FFF'});
																		  						 }
																		   })
																});
	$('info_block').getElement('h1').addEvents({									
												 'click':   function () {
																		closeSideBlock(false);
																	    },
																		  
										 		  'mouseenter': function () {
													  					this.setStyles({'color': '#000'});
																		 },

												  'mouseleave': function () {
													  					this.setStyles({'color': '#3f4c51'});
												 						 }
											  });										
}

function openSideBlock(name)
{
	if (side_disabled) {
		return;
	}
	side_disabled = true;
	if (opened_block) {
		closeSideBlock(name);
		return;
	}

    $('info_block').getElement('.scrollable').set('html', $('sideblock_texts').getElement('div[name='+name+']').get('html'));
	$('info_block').getElement('.scrollable').setStyles({'height' : 'auto'});
	opened_block = name;
	if (!IE) {
		$(name).morph({'opacity' : 0});
	} else {
		$(name).setStyle('display', 'none');
	}
	var inv_height = $('info_block').getElement('.content').offsetHeight;
	inv_height = inv_height > 245 ? 300 : inv_height;
	var m_top = parseInt($(name).getStyle('marginTop'))+27;	
	$('info_block').getElement('h1').set('html', $(name).get('html'));
	$('info_block').setStyle('margin-top', m_top);
	$('info_block').set('morph', {duration:750, transition: Fx.Transitions.Quart.easeOut});	
	$('info_block').morph({'height': inv_height, 'marginTop': inv_height*-1+37, 'opacity' : IE ? 1 : [0, 1]});
	var prev = $(name).getAllPrevious('.list_item');
	for (var i=0; i<prev.length; i++) {
		prev[i].set('morph', {duration:750, transition: Fx.Transitions.Quart.easeOut});
		prev[i].morph({'marginTop' : prev.length == 1 ? 50 : 100-(50*i)});
	}
	$('info_block').getElement('.scrollable').setStyle('width', 220);
	setTimeout('side_disabled = false;', 750);
	if ($('info_block').getElement('.scrollable').offsetHeight > 245) {
		$('info_block').getElement('.scrollable').setStyles({'width': 200, 'height' : 245});
		$('info_block').getElement('.scrollbar').setStyle('display', 'block');
		makeScrollbar($('info_block').getElement('.scrollable'), $('info_block').getElement('.scrollbar'), $('info_block').getElement('.scrollbar_button'));		
	} else {
		$('info_block').getElement('.scrollbar').setStyle('display', 'none');
		$('info_block').getElement('.scrollable').setStyles({'width': 220, 'height' : $('info_block').getElement('.scrollable').offsetHeight});
	}
	$('info_block').getElement('.scrollable').scrollTo(0, 0);
	
}

var cur_slider;

function makeScrollbar(content, scrollbar, handle, horizontal, ignoreMouse){
	var steps = (horizontal?(content.getScrollSize().x - content.getSize().x):(content.getScrollSize().y - content.getSize().y))	
	if (handle.scroll_slider) {
		handle.scroll_slider.detach();
	}
	handle.scroll_slider = new Slider(scrollbar, handle, {	
		steps: steps,
		mode: (horizontal?'horizontal':'vertical'),
		onChange: function(step){
			var x = (horizontal?step:0);
			var y = (horizontal?0:step);
			content.scrollTo(x,y);
		}
	}).set(0);
	if( !(ignoreMouse) ){
		$$(content, scrollbar).addEvent('mousewheel', function(e){	
			e = new Event(e).stop();
			var step = handle.scroll_slider.step - e.wheel * 30;	
			handle.scroll_slider.set(step);					
		});
	}
	cur_slider = handle.scroll_slider;
	$(document.body).addEvent('mouseleave',function(){cur_slider.drag.stop()});	
}

function closeSideBlock(open_next)
{
	faster = open_next != false;
	if (!IE) {
		$(opened_block).morph({'opacity' : 1});
	} else {
		$(opened_block).setStyle('display', 'block');
	}
	
	var m_top = parseInt($(opened_block).getStyle('marginTop'))+27;	
	$('info_block').set('morph', {duration: faster ? 500 : 750, transition: Fx.Transitions.Quart.easeOut});	
	$('info_block').morph({'height': 0, 'marginTop': m_top, 'opacity' : IE ? 1 : [1, 0]});
	var prev = $(opened_block).getAllPrevious('.list_item');
	for (var i=0; i<prev.length; i++) {
		prev[i].set('morph', {duration: faster ? 500 : 750, transition: Fx.Transitions.Quart.easeOut});
		prev[i].morph({'marginTop' : prev.length == 1 ? 0 : 50-(50*i)});
	}
	opened_block = false;
	if (open_next != false) {
		setTimeout("side_disabled = false; openSideBlock('"+open_next+"');", faster ? 500 : 750);
	}
}

function resizeContent()
{
	var nw = $('right_col').offsetWidth;
	if ($('text_content').getElement('.left').getStyle('width') != nw-30) {
		$('text_content').getElement('.left').setStyle('width', nw-30);
	}
}

function initContentResize() 
{
	window.onresize = resizeContent;
}

var currentAnchor = null;  

function checkAnchor(){  
    if(currentAnchor != document.location.hash){  
        currentAnchor = document.location.hash;  
        if(!currentAnchor)  
            query = "/index/";  
        else  
        {  
            var splits = currentAnchor.substring(1).split('&');  
            var section = splits[0];  
            delete splits[0];  
            var params = splits.join('&');  
            var query = section  + params;  
        }  
			$('page_content').set('html', '');	
			$('page_content').scrollTo(0, 0);
		if (query ==  "/index/")
		{
			hideContent();
		} else {	
			if (!content_shown) {				
				showContent();
			}
				var req = new Request({
				url: query,
				evalScripts : true,
		
				onSuccess: function(txt){
					$('page_content').set('html', txt);
					$('page_content').removeClass('loading');
					if (currentAnchor == '#/order/') {
						initOrderForm();
					}
				},
		
				onFailure: function(){
					$('page_content').set('html', '<h1>Произошла ошибка</h1>Приносим свои извинения, неисправность будет устранена в ближайшее время.');
					$('page_content').removeClass('loading');
				}
		
				});
				req.send();
				$('page_content').addClass('loading');
		}
		
//		alert(query);
//        $.get("callbacks.php",query, function(data){  
//            $("#content").html(data);  
//        });  
    }  
}  



function showContent()
{
	pauseBanners();
	$('text_content').set('morph', {duration: 750, transition: Fx.Transitions.Quart.easeOut});
	$('text_content').morph({'height' : 536, opacity: 1});
	content_shown = true;
}

function hideContent()
{
	resumeBanners();	
	$('text_content').set('morph', {duration: 500, transition: Fx.Transitions.Quart.easeIn});
	$('text_content').morph({'height' : 0, 'opacity' : IE ? 1 : 0});
	content_shown = false;
}

function initContent() 
{
	$('text_content').setStyles({'display' : 'block', 'height' : 0, 'opacity' : IE ? 1 : 0});
	setInterval(updateContentScroll, 100);
}

//var scroll_pagecontent;
var scroll_last_pagecontent = false;

function updateContentScroll()
{
	if ($('page_content').getScrollSize().y > 500) {
		if (scroll_last_pagecontent == false) {
			$('text_content').getElement('.scrollbar').setStyles({'display' : 'block'});		
		}
		if ($('page_content').getScrollSize().y != scroll_last_pagecontent) {
			makeScrollbar($('page_content'), $('text_content').getElement('.scrollbar'), $('text_content').getElement('.scrollbar_button'));		
			scroll_last_pagecontent = $('page_content').getScrollSize().y;
		}
		} else {
		if (scroll_last_pagecontent != false) {
			$('text_content').getElement('.scrollbar').setStyles({'display' : 'none'});			
			scroll_last_pagecontent = false;
		}
	}
}

var curimage = 0;
var banners;
var banners_interval;

function bannersDance()
{
	var next = curimage == banners.length-1 ? 0 : curimage+1;
	banners[next].setStyle('opacity', 0);
	for (i = 0; i<banners.length; i++) {		
		if (i != curimage && i != next) {
			banners[i].setStyle('z-index', 0);
		}
	}
	banners[curimage].setStyle('z-index', 99);
	banners[next].setStyle('z-index', 100);	
	banners[next].morph({opacity:1});
	curimage = next;
}

function pauseBanners()
{
	clearInterval(banners_interval);
}

function resumeBanners()
{
	clearInterval(banners_interval);
	banners_interval = setInterval(bannersDance, 4000);	
}

function initBanner()
{
	banners = $('banner').getElements('img');
	$('banner').getElements('img').each(function(el){
												el.set('morph', {duration: 3000, transition: Fx.Transitions.Quart.easeOut});																	 
												 });

}


function animateOpen(bounds, el) {
	var splits = el.href.split('#');
	if (document.location.hash == '#'+splits[1]) return;

	$('rect').setStyles({'width':bounds.width,'height':bounds.height, 'top':bounds.y, 'left':bounds.x , 'opacity' :0.75});
	var contentbounds = getBounds($('text_content'));
	$('rect').morph({'top': contentbounds.y, 'left': contentbounds.x, 'width': contentbounds.width, 'height': 537, 'opacity' : 0})
}

function initLinks()
{
	$('rect').set('morph', {duration: 1000, transition: Fx.Transitions.Quart.easeOut});
	$('rect').setStyles({'display':'block', 'opacity': 0})
	$('container').getElements('a').each(function(el){
												  if (el.href.indexOf('#/') >0 & el.href.indexOf('#/index/') == -1 ) {
												  el.addEvents({'click': function(){
																				  	animateOpen(getBounds(this), this);
																				   }})
												  }
												  })
}

window.addEvent('domready', function() {
	initLigthVersionMorph();
	initArrowMove();
	initSubMenu();
	initSearch();
	initSideBlock();
	initContentResize();
	initContent();
	initBanner();
	initLinks();
	resizeContent();	
	setInterval("checkAnchor()", 500);
});

var agreementChecked = false;

function updateOrderAgreement(chk) {
	agreementChecked = chk.checked;
	if (chk.checked) {
		$('orderdiv').getElement('.orderformsubmit').setStyles({'opacity': 1, 'cursor' : 'pointer'});		
	} else {
		$('orderdiv').getElement('.orderformsubmit').setStyles({'opacity': 0.5, 'cursor' : 'default'});
	}
}

function updateOrderPrice() {
	$('workprice').set('text', 'Стоимость: '+worktypeprices[$('worktype').selectedIndex]);
}

var field_errors = {'fio': 'Введите ФИО', 'phone': 'Введите контактный телефон', 'city': 'Введите город и регион', 'email': 'Введите корректный e-mail', 'institute': 'Введите институт и кафедру', 'teacher': 'Введите ФИО преподавателя', 'subject':'Введите предмет', 'theme':'Введите тему работы', 'size':'Введите объем работы'}

var orderFormValidator;

function initOrderForm() {
	
	MooTools.lang.setLanguage("ru-RU");
	orderFormValidator = new FormValidator($('orderform'), {
	onFormValidate: function(ok) {
		if (!ok) {
			$('page_content').scrollTo(0,0);
		}
	},
	onElementPass: function(el, vals) {
		if (el.errorDivLink) {
			el.errorDivLink.destroy();
		}
	},
	onElementFail: function(el, vals) {
		if (el.errorDivLink) {
			el.errorDivLink.destroy();
		}
		var errorDiv = new Element('div', {
			'class': 'fielderror',
			'html': field_errors[el.name]
		});
		el.errorDivLink = errorDiv;
		errorDiv.inject(el.getParent());
	},
	stopOnFailure:true,
	evaluateFieldsOnBlur:false
	});

	$('orderdiv').getElement('.orderformsubmit').setStyles({'opacity': 0.5, 'cursor' : 'default'});
	$('orderdiv').getElement('.orderformsubmit').addEvents({ 'click':function(){ if(agreementChecked) { if (orderFormValidator.validate()) { $('orderform').submit(); } }}});
}

function checkOrderForm(){
	return false;
}

function sendForm (form) {
	currentAnchor = '#/search/';
	document.location.hash = '#/search/';
	if (!content_shown) {				
		showContent();
	}
	form.set('send', {url: form.action, method: 'post', 
						 
						 onSuccess: function(txt){
							$('page_content').set('html', txt);
							$('page_content').removeClass('loading');
							if (currentAnchor == '#/order/') {
								initOrderForm();
							}
						},
				
						onFailure: function(){
							$('page_content').set('html', '<h1>Произошла ошибка</h1>Приносим свои извинения, неисправность будет устранена в ближайшее время.');
							$('page_content').removeClass('loading');
						}	
						 
						 });
	form.send();
	
	$('page_content').set('html', '');	
	$('page_content').scrollTo(0, 0);
	$('page_content').addClass('loading');
	
	return false;
}
