
var schedule = (function() {
    // Local variables 
    
    var buttons, box, obj_table, left,fx,
		delta = {'next' : {'x0' : 0, 'x1' : -410}, 'prev' : {'x0' : -410, 'x1' : 0}}
    
    var shear = function (direct){
        left = box.offsetLeft;
       
		if (0 > left || left > -410 ) {
			fx.start(delta[direct].x0, delta[direct].x1)
			Array.each(buttons,function(el){ el.toggleClass('off') });
		}
    }
	
	var init = function(){
		buttons = [document.id('p_prev'),document.id('p_next')];
        
		box = document.id('price_box'), obj_table = document.id('table_price'), left,
		fx = new Fx.Tween(box, { property: 'left',  duration: 500 });
		
		buttons.push(
			new Element('div',{'id':'prev_but','class':'off',
				'events':{'click':shear.bind(this,['prev'])}
			}).inject(obj_table),
			new Element('div',{'id':'next_but',
				'events':{'click':shear.bind(this,['next'])}
			}).inject(obj_table)
		);
		
		document.id('p_next').onclick = shear.bind(this,['next']);
		document.id('p_prev').onclick = shear.bind(this,['prev']);
	
		document.getElements('div.find h4').each(function(el){
			el.addEvent('click',function(e){
				document.id(el.parentNode).toggleClass('show');
			});
		});
	}
    
    return {
        init: init
    };
})();

var sailorTest = function()
{	
	var count = 0,
		result = -1,
		buttons, questOut, countOut, rope;
	
	var test = [
		{q: '', a: [1,1,0]},
		{q : 'Вы предпочитаете активный отдых?', a: [3,1,0]},
		{q : 'Вы любите путешествовать в компании друзей?', a: [3,1,0]},
		{q : 'Вас «укачивает» в транспорте?', a: [1,2,3]},
		{q : 'Вы любите приключения?', a: [3,1,0]},
		{q : 'Вам нравится фильм «Пираты Карибского моря»?', a: [3,1,0]},
		{q : 'Вы любите роскошь?', a: [3,1,0]},
		{q : 'Считаете ли Вы себя Экстремалом?', a: [3,2,1]},
		{q : 'Вы мечтали в детстве о кругосветном путешествии?', a: [3,1,0]},
		{q : 'Вы умеете плавать?', a: [3,1,0]},
		{q : 'Вы знаете, что означает «Volvo Ocean Race»?', a: [3,1,0]},
		{q : 'У Вас крепкое здоровье?', a: [3,2,1]},
		{q : 'Вы умеете вязать хоть один морской узел?', a: [3,1,0]},
		{q : 'Нравится ли Вам книга Жюль Верна «20000 лье под водой»?', a: [3,1,0]},
		{q : 'Вы любите смотреть на море?', a: [3,1,0]},
		{q : 'Вы любите рыбалку?', a: [3,1,0]},
		{q : 'Вам нравится совершать открытия?', a: [3,1,0]}
	];
	
	var discount = [
		'Как стать настоящим моряком? <br /> Вы получите инструкцию юнги при заказе яхты и <b>скидку 5%</b> <br />	на чартер выбранной яхты!',
		'Вы уже не новичок! Поздравляем! <br /> Вы получите специальную скидку 6% <br /> при заказе яхты!',
		'Вы настоящий моряк! Ура! <br /> Вы получите скидку в 7% при заказе яхты!'
	];
	
	var next = function(i){
		if (count >= test.length-1) return showResult();
		
		var j = test[count].a.length;
		while(j--){
			buttons[j].className = test[count].a[j] == 0 ? 'hide' : '';
		}
		result += test[count].a[i];
		
		count++;
		questOut.set('text', test[count].q);
		countOut.set('text', count);
		rope.setStyle('width', rope.offsetWidth + 45);
	}
	
	var showResult = function(){
		questOut.set('html', 'Вы набрали <b>'+ declaration(result, ['балл', 'балла', 'баллов']) +'</b>' );
		buttons.getParent().addClass('hide');
		countOut.getParent().addClass('hide');
		
		var mailBox = document.id('mail-box'),
			mailSend =  document.id('mail-send');
			
		var tDiscount = result < 16 ? 0 : (result < 33 ? 1 : 2);
		mailBox.addClass('show');
		mailBox.getElement('.incut').innerHTML = discount[tDiscount]
		
		
		mailBox.getElement('span').addEvent('click', function(){
			mailBox.removeClass('show');
			var inputs = document.id('mail-box').getElements('form.mail input');
			var i, j = inputs.length;
			
			for (i = 0; i < j && !!inputs[i].value; i++);
			if (i != j) alert('Все поля формы должны быть заполнены')
			
			new Request({method: 'post', url: 'main/send_cert.php'}).send(
				document.id('mail-box').getElement('form.mail').toQueryString() + '&ag_discount='+(tDiscount+5)
			);
			
			mailSend.addClass('show');
		});
	}
	
	var declaration = function(number, ending){
		var cases = [2,0,1,1,1,2];
		return number +' '+ ending[number%100>4 &&  number%100<20 ? 2 : cases[Math.min(number%10, 5)]];
	}
	
	var init = function(button){
		var wn = document.id('sailor-test'),
			fade = document.id('fadeout'),
			bClose = document.id('sailor-test').getElement('.close'),
			bOpen = document.id(button);
			
		rope = document.id('rope').getElement('b');
		buttons = wn.getElements('div.buttons span');
		questOut = wn.getElement('h3');
		countOut = wn.getElement('#counter b');
		
		buttons.each(function(button, i){
			button.addEvent('click', function(){
				next(i);
			})
		});
		
		var close = function(){
			wn.removeClass('show');
			fade.setStyle('height', 0)
		}
		
		var open = function(){
			wn.addClass('show');
			fade.setStyle('height', document.id('container').offsetHeight)
		}
		
		bOpen.addEvent('click', open)
		bClose.addEvent('click', close);
		
		next(0);
	}
	
	return { 
		init : init
	}
}();

var CrawlLine = function(cont,speed){
	var cont = document.id(cont), duration, animate, fx, i = 35, button, ani;
	if(!cont) return false;
	
	duration = (cont.offsetWidth*70)/speed | 0;
	
	button = document.id('move_line').getNext().getElement('b');
	
	
	animate = function(){
		fx = new Fx.Tween(cont, { property: 'left', duration: duration, fps: 100, transition: Fx.Transitions.linear });
		fx.start(i,-cont.offsetWidth).chain(function(){
			i = document.id(cont.parentNode).offsetWidth;
			animate();
		});
	}
	animate();

	ani = true;
	button.addEvent('click', function(){
		if(ani) fx.pause();
		else fx.resume();
		button.toggleClass('pause');
		ani = !ani;
	})
}

window.addEvent('domready',function(){

	if (document.id('test_box')){
		sailorTest.init('test_box');
	}
	
	var searchBox = document.id('search_box');
	if (searchBox)
	{
		searchBox.getElements('.select-list').each(function(select){
			select.addEvent('click', function(e){ this.toggleClass('show') });
			var list = select.getElements('li');
			var selected = list[0];
			
			list.each(function(el){
				el.addEvent('click', function(){
					selected.removeClass('selected')
					this.addClass('selected');
					selected = this;
				})
			});
			
		});
		searchBox.getElements('.radio-list').each(function(radioList){
			var list = radioList.getElements('li');
			var selected = list[0];
			
			list.each(function(el){
				el.addEvent('click', function(){
					selected.removeClass('selected')
					this.addClass('selected');
					selected = this;
				})
			});
		})
		searchBox.getChildren('a').each(function(el, i){
			if ( ! el.rel) return;
			el.addEvent('click', function(e){
				e.stop();
				this.toggleClass('active');
				document.id('yacht_rent').toggleClass('active');
			});
		});
	}
	
	
 
	CrawlLine('move_line', 3);
    
    /** opacity **/ 
    document.getElements('.images img').each(function(el){
        el.onmouseover = function() { this.setStyle('opacity', 1); }
        el.onmouseout = function() { this.setStyle('opacity', 0.7); }
        el.setStyle('opacity', 0.7); 
    })

    
    if(document.id('table_price') ) {
        schedule.init();
    }
    
    if(document.id('accordion')){
        var accordion = new Fx.Accordion(document.id('accordion'), 'h4.question','div.answer',{
            opacity: false,
            
            onActive: function(toggler, element){
                toggler.addClass('active');
            },
            onBackground: function(toggler, element){
                toggler.removeClass('active');
            }

        });
    }
     
    /** headbox **/
	document.id('head_box').innerHTML += '<div id="boat"></div><div id="blick"></div>';
 
	var fx = new Fx.Tween(document.id('boat'),{ property: 'left',  duration: 400 }),
		boatSize = document.id('boat').offsetWidth;
  
	document.getElements('ul#topmenu li').each(function(li,i){
		if(li.hasClass('navactive')){
			document.id('blick').setStyle('left', li.offsetLeft - 72);
			fx.set(li.offsetLeft + li.offsetWidth - boatSize)
		}
		var a = li.getFirst();
		
		a.addEvent('click',function(e){
			e.stop();
			
			var li = this.getParent();
			fx.start(li.offsetLeft + li.offsetWidth - boatSize).chain(function(){
				window.location.href = a.href
			});
			
		   return false;
		});
	});
    

	
	if (Browser.ie)
	{
		/** Placeholders **/
		document.getElements('input').each(function(el){
			var placeholder = el.get('placeholder');
			if (placeholder){
				el.addEvents({
					'focus'	: function() { el.value = el.value == placeholder ? '' : el.value },
					'blur'	: function() { el.value = el.value == '' ? placeholder : el.value }
				})
				el.value = placeholder
			}
		});
		
		/** StripTables **/
		document.getElements('table.tb_strip').each(function(table){
			table.getElements('tr').each(function(tr,i){ if((i%2)-1 && !tr.hasClass('nostrip')) tr.addClass('strip')})
        });
	}
	
});
