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;
    }
});

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

window.addEvent('domready', function(){
    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;

    // Форма поиска
    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 });
});
