var topMenu = new Class({
	Implements: [Options],
	initialize: function(container, options){
		this.elements = $$(container.getElements('td'));
		this.pnames = {};
		$each(this.elements, function(elm, id){
			this.pnames[elm.title] = elm;
            if (elm.hasClass('active')) this.active = elm.title;
//			elm.setStyles({'margin-top': 0, 'height': 30}).set('morph', {'duration': 200, 'transition': Fx.Linear, 'wait': false});
			/*elm.addEvents({
                'mouseenter': function(e){ this.morph({'margin-top': -5, 'height': 35}); },
                'mouseleave': function(e){ this.morph({'margin-top': 0, 'height': 30}); }
			});*/
			elm.erase('title');
		}, this);
	},
	setActive: function(id){
		if (id == this.active) return;
        if (this.pnames[this.active]) this.pnames[this.active].removeClass('active');
		if (this.pnames[id]) this.pnames[id].addClass('active');
		this.active = id;
	}
});

var fullAjax = new Class({
	Implements: [Events, Options, Chain],
	options: {/*
		open: $empty(newUrl, title, oldUrl),
		beforeRollIn: $empty, // Constructor 1
		afterRollIn: $empty, // Constructor 2
		beforeRollOut: $empty, // Destructor 1
		afterRollOut: $empty // Destructor 2*/
		activeElm: 0,
		historyKey: '',
		defHKey: ['/'],
		nHeight: '70px',
		defTitle: ''
	},

	initialize: function(bodyelm, options){
		this.bodyelm = bodyelm;
		this.bodyfx = new Fx.Morph(this.bodyelm, {duration: 350, transition: Fx.Transitions.linear, wait: false});
		this.setOptions(options);

		this.baseURL = (arr=/^http:\/\/([a-z0-9\-\.]+)/.exec(document.URL))?arr[1]:'';

		this.adoptAnchors(document.body); // !!!
		this.phiden = 0; // stage of effects 0 - elements are shown; 1 - elements are moving out; 2 - elements are moving in
		this.ploaded = true; // stage of loading false - still loading; true - loaded
		this.aPath = "/"; // active path

		this.HStarted = false;
		this.scriptLoaded = false; // Is the script loaded properly ?

		this.history = HistoryManager.register(// arguments are (key, defaults, onMatch, onGenerate, regexp, options)
		this.options.historyKey,
		// Array with default values, here index 0 is the current page index
		this.options.defHKey,
		// onMatch, callback when the state changed
		function(values) {
			if (!this.HStarted && values[0] == "/") return;
			this.open(values[0]);
		}.bind(this),
		// onGenerate, callback that returns the string for the hash
		function(values) {
			return [this.options.historyKey, '', values[0], ''].join('');
		}.bind(this),
		// RegExp for the hash value, works
		this.options.historyKey + '(([a-z0-9_\\/]+))');
		this.$events = {};
	},

	open: function(path, data){
		if (!this.ploaded || (this.phiden != 0)){ this.history.setValue(0, this.aPath); return; }
		this.ploaded = false; this.phiden = 1;
		this.fireEvent('beforehide');
		var newPage = new Request.JSON({'url': path, 'method': 'post', 'data': $merge({'ajax': true}, data), 'evalScripts': true, 'onComplete': function(data, text){
            this.fireEvent('open', [path, data.title, this.aPath]);
            this.aPath = path;
            this.newdata = data;
            MotionToday.topMenu.setActive(data.parents[1]);
			this.ploaded = true;
			this.showattempt();
		}.bind(this)}).send();
		this.scriptLoaded = false;
		var screenX = window.getSize().x;
		//		this.headfx.start({'left': wdt1}).chain(function(){ document.body.className = 'preload'; this.headelm.setStyle('left', '-' + wdt1 + 'px'); });
		this.bodyfx.start({'opacity': 0}).chain(function(){
            this.phiden = 2;
            document.body.className = 'preloadme';
            /* this.bodyelm.setStyle('left', wdt2 + 'px'); */
            this.fireEvent('afterhide');
            this.showattempt();

            // Скроллим страницу вверх
            document.body.scrollTo(0, 0);

        }.bind(this));
	},

	adoptAnchors: function(elm){
		var noext='(^javascript\:)|(^\/index.php)'
		var otherWindow='((\.[a-z]{2,4})$|https\:|http\:\/\/)'
		var anchors = $$(elm.getElementsByTagName('a'));
		anchors.each(function(elm){
			var mhref = elm.getProperty('href');
			if (arr=/^((\w+):\/\/)?((\w+):?(\w+)?@)?([^\/\?:]+):?(\d+)?(\/?[^\?#]+)?\??([^#]+)?#?(\w*)/.exec(mhref)) if (arr[6] == this.baseURL) mhref = arr[8];
			//			if (mhref.test('.\'))
			if (!mhref || mhref.test(noext) || elm.getProperty('target')) return;
			if (!mhref.test(otherWindow)) elm.setProperty('href', '#' + mhref); else elm.setProperty('target', '_blank');
		}.bind(this));
	},

	showattempt: function(){
		if ((this.phiden != 2) || !this.ploaded) return;
		this.phiden = 3;
		//		this.headelm.setHTML(elms[0].innerHTML);
		this.bodyelm.set('html', this.newdata.output);
        this.adoptAnchors(this.bodyelm);

        MotionToday.mbox.touch('mb');
        MotionToday.mbox.overlay.position();

		document.body.set('class', this.newdata.pageclass);

		this.fireEvent('beforeshow');
		//		this.headfx.start({'left': 0});
		this.bodyfx.start({'opacity': 1}).chain(function(){
//            document.body.className = '';
            if (this.phiden != 3) return;
            this.phiden = 0;
            this.fireEvent('aftershow');
        }.bind(this));
	},

	setTitle: function(newTitle){
        document.title = ((newTitle != '')?(newTitle + " :: "):'') + this.options.defTitle;
    }
});

/* b-team */
var bTeam = new Class({
    options: {
        width: 80,
        height: 80,
        frontArea: 40,
        keys: ['a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'space'],
        keyStates: ['x', 'w', 'nw', 'n', 'ne', 'e', 'se', 's', 'sw', 'f']
    },
    initialize: function(container){
        this.container = $(container);
        this.faces = this.container.getElements('.b-team-person-photo');
        this.places = {};
        this.states = {};
        this.listenKeys = true;
        $$('input').each(function(elm){
            elm.addEvents({
                'focus': function(){ this.listenKeys = false; }.bind(this),
                'blur': function(){ this.listenKeys = true; }.bind(this)
            });
        }.bind(this));
        this.events = {
            lookAtCursor: function(e){ this.lookAtCursor(e.page); }.bind(this),
            keyState: function(e){
                var keyIndex;
                if (this.listenKeys === false) return;
                if ((keyIndex = this.options.keys.indexOf(e.key)) === -1) return;
                e.stop();
                var nextState = this.options.keyStates[keyIndex];
                $each(this.faces, function(face, id){
                    this.setState(id, nextState);
                }, this);
            }.bind(this)
        };
        this.timer = this.refreshPlaces.periodical(1000, this);
        $(document.body).addEvent('mousemove', this.events.lookAtCursor);
        $(document).addEvent('keydown', this.events.keyState);
        this.refreshPlaces();
//        MotionToday.ajax.addEvent('beforehide',
//                function(){ this.detach(); }.bind(this));
    },
    detach: function(){
        $(document.body).removeEvent('mousemove', this.events.lookAtCursor);
        $(document).removeEvent('keydown', this.events.keyState);
    },
    refreshPlaces: function(){
        $each(this.faces, function(face, id){
            var coord = face.getCoordinates();
            this.places[id] = {x: coord.left + this.options.width/2, y: coord.top + this.options.width/2};
        }, this);
    },
    lookAtCursor: function(abscrd){
        $each(this.places, function(place, id){
            var relcrd = {x: abscrd.x - place.x, y: abscrd.y - place.y};
            this.setState(id, this.countState(relcrd));
        }, this);
    },
    countState: function(crd){
        if (Math.abs(crd.x) < this.options.frontArea && Math.abs(crd.y) < this.options.frontArea) return 'c';
        if (crd.y == 0) return (crd.x>0)?'e':'w';
        var tg = crd.x/crd.y;
        var space = 1;
        if (tg < -2.414){
            return (crd.y>0)?'w':'e';
        }else if(tg >= -2.414 && tg < -0.414){
            return (crd.y>0)?'sw':'ne';
        }else if(tg >= -0.414 && tg < 0.414){
            return (crd.y>0)?'s':'n';
        }else if(tg >= 0.414 && tg < 2.414){
            return (crd.y>0)?'se':'nw';
        }else if(tg >= 2.414){
            return (crd.y>0)?'e':'w';
        }
        return 'n';
    },
    setState: function(id, state){
        if (this.states[id] == state) return;
        this.faces[id].className = 'b-team-person-photo state_'+state;
        this.states[id] = state;
    }
});

/*************************************************************/
function openp(){
    window.location.assign('#/');
}

/**
 * Roar - Notifications
 *
 * Inspired by Growl
 *
 * @version		1.0.1
 *
 * @license		MIT-style license
 * @author		Harald Kirschner <mail [at] digitarald.de>
 * @copyright	Author
 */

var Roar = new Class({

	Implements: [Options, Events, Chain],

	options: {
		duration: 3000,
		position: 'upperLeft',
		container: null,
		bodyFx: null,
		itemFx: null,
		margin: {x: 20, y: 20},
		offset: 10,
		className: 'roar',
		onShow: $empty,
		onHide: $empty,
		onRender: $empty
	},

	initialize: function(options) {
		this.setOptions(options);
		this.items = [];
		this.container = $(this.options.container) || document;
	},

	alert: function(title, message, options) {
		var params = Array.link(arguments, {title: String.type, message: String.type, options: Object.type});
		var items = [new Element('h3', {'html': $pick(params.title, '')})];
		if (params.message) items.push(new Element('p', {'html': params.message}));
		return this.inject(items, params.options);
	},

	inject: function(elements, options) {
		if (!this.body) this.render();
		options = options || {};

		var offset = [-this.options.offset, 0];
		var last = this.items.getLast();
		if (last) {
			offset[0] = last.retrieve('roar:offset');
			offset[1] = offset[0] + last.offsetHeight + this.options.offset;
		}
		var to = {'opacity': 1};
		to[this.align.y] = offset;

		var item = new Element('div', {
			'class': this.options.className,
			'opacity': 0
		}).adopt(
			new Element('div', {
				'class': 'roar-bg',
				'opacity': 0.7
			}),
			elements
		);

		item.setStyle(this.align.x, 0).store('roar:offset', offset[1]).set('morph', $merge({
			unit: 'px',
			link: 'cancel',
			onStart: Chain.prototype.clearChain,
			transition: Fx.Transitions.Back.easeOut
		}, this.options.itemFx));

		var remove = this.remove.create({
			bind: this,
			arguments: [item],
			delay: 10
		});
		this.items.push(item.addEvent('click', remove));

		if (this.options.duration) {
			var over = false;
			var trigger = (function() {
				trigger = null;
				if (!over) remove();
			}).delay(this.options.duration);
			item.addEvents({
				mouseover: function() {
					over = true;
				},
				mouseout: function() {
					over = false;
					if (!trigger) remove();
				}
			});
		}
		item.inject(this.body).morph(to);
		return this.fireEvent('onShow', [item, this.items.length]);
	},

	remove: function(item) {
		var index = this.items.indexOf(item);
		if (index == -1) return this;
		this.items.splice(index, 1);
		item.removeEvents();
		var to = {opacity: 0};
		to[this.align.y] = item.getStyle(this.align.y).toInt() - item.offsetHeight - this.options.offset;
		item.morph(to).get('morph').chain(item.destroy.bind(item));
		return this.fireEvent('onHide', [item, this.items.length]).callChain(item);
	},

	empty: function() {
		while (this.items.length) this.remove(this.items[0]);
		return this;
	},

	render: function() {
		this.position = this.options.position;
		if ($type(this.position) == 'string') {
			var position = {x: 'center', y: 'center'};
			this.align = {x: 'left', y: 'top'};
			if ((/left|west/i).test(this.position)) position.x = 'left';
			else if ((/right|east/i).test(this.position)) this.align.x = position.x = 'right';
			if ((/upper|top|north/i).test(this.position)) position.y = 'top';
			else if ((/bottom|lower|south/i).test(this.position)) this.align.y = position.y = 'bottom';
			this.position = position;
		}
		this.body = new Element('div', {'class': 'roar-body'}).inject(document.body);
		if (Browser.Engine.trident4) this.body.addClass('roar-body-ugly');
		this.moveTo = this.body.setStyles.bind(this.body);
		this.reposition();
		if (this.options.bodyFx) {
			var morph = new Fx.Morph(this.body, $merge({
				unit: 'px',
				chain: 'cancel',
				transition: Fx.Transitions.Circ.easeOut
			}, this.options.bodyFx));
			this.moveTo = morph.start.bind(morph);
		}
		var repos = this.reposition.bind(this);
		window.addEvents({
			scroll: repos,
			resize: repos
		});
		this.fireEvent('onRender', this.body);
	},

	reposition: function() {
		var max = document.getCoordinates(), scroll = document.getScroll(), margin = this.options.margin;
		max.left += scroll.x;
		max.right += scroll.x;
		max.top += scroll.y;
		max.bottom += scroll.y;
		var rel = ($type(this.container) == 'element') ? this.container.getCoordinates() : max;
		this.moveTo({
			left: (this.position.x == 'right')
				? (Math.min(rel.right, max.right) - margin.x)
				: (Math.max(rel.left, max.left) + margin.x),
			top: (this.position.y == 'bottom')
				? (Math.min(rel.bottom, max.bottom) - margin.y)
				: (Math.max(rel.top, max.top) + margin.y)
		});
	}
});

$roar = false;
window.addEvent('domready', function(){

    $roar = new Roar({position: 'upperRight'});
    $$('.b-subscribe').addEvent('submit', function(e){
        e.stop();
        new Request.JSON({
            "url": "/user/31-livecoach/run/subscribe.php",
            "data": {"mail": document.getElement('.b-subscribe .myemail').get('value')},
            "onSuccess": function(data){
                $roar.alert(data.success?'Заявка отправлена':'Ошибка при отправке заявки', data.message)
            }
        }).send();
    });

//    MotionToday.topMenu = new topMenu($('mainMenu'));
	MotionToday.mbox = new MultiBox('mb', {descClassName: 'multiBoxDesc', useOverlay: true});
//    MotionToday.ajax = new fullAjax($('content'), {});
//	HistoryManager.start();
//    MotionToday.ajax.HStarted = true;

    // Лица команды
    $$('.b-team').each(function(elm){ new bTeam(elm); });

//    MotionToday.ajax.addEvent('beforeshow', function(){
//        $$('.b-team').each(function(elm){ new bTeam(elm); });
//    });

    // Форма поиска
    /*var searchForm = document.getElement('#searchForm');
    searchForm.addEvent('submit', function(e){
        e.stop();
        var action = searchForm.get('action');
        MotionToday.ajax.open(action, {'squery': searchForm.getElement('input').get('value')})
        window.location.assign('#' + action);
        MotionToday.ajax.history.setValue(0, action);
    });*/

    // Логотип MotionToday
    var mtLogo = document.getElement('.siteCreations a').setStyle('opacity', .5);
    mtLogo.addEvents({
        'mouseenter': function(e){ mtLogo.tween('opacity', 1); }.bind(mtLogo),
        'mouseleave': function(e){ mtLogo.tween('opacity', .5); }.bind(mtLogo)
    }).set('tween', { duration: 250 });
});
