window.addEvent('load', function() {
	var frm = new Mainframe( );
} );

var Mainframe = new Class({
	initialize: function( ) {
	    this.startPopups();
        this.startAccordions();
    	if (Browser.Engine.trident && (Browser.Engine.version < 5))
			this.startCarousels();
		else
			this.startCarousels2();
	    this.startAudios();
        this.startVideos();
		this.startMarquees();
		
        // wiki
        this.startFastSearches();
	},

    startPopups: function( ) {
		if (!this.popup)
        {
            var wsize = document.getSize();
            this.popupbg = new Element('div', {'class': 'popup-bg'}).setStyles({'height': wsize.y}).inject( document.getElement('body'), 'top' );
            this.popup = new Element('div', {'class': 'popup'}).inject( this.popupbg );
            this.popup.close = new Element('a', {'href':'javascript:;', 'class': 'popup-close'}).set('html', 'Chiudi x').addEvent('click', this.closePopup.bind(this) ).inject( this.popup );
            this.popup.box = new Element('div', {'class': 'popup-box'}).inject( this.popup );
        }
        $$('.open-popup').each( this.startPopup.bind(this) );
    },

    startPopup: function( item ) {
        item.addEvent('click', this.openPopup.pass(item,this) );
        item.addEvent('click', function(e) { new Event(e).stop(); } );
    },

    openPopup: function( item )
    {
		if (item.get('href').indexOf('.jpg') !== -1)
		{
			this.popup.box.html( '<img src="' + item.get('href') + '" />' );
			this.popupbg.setStyle('display', 'block');
		}
		else
		{
	        var xhr = new Request( { url: item.get('href') + '&ajax=true' } ).send();
	        xhr.addEvent('onComplete', function(response) {
	            this.popup.box.html(response);
	            this.popupbg.setStyle('display', 'block');
	        }.bind(this) );
		}

    },

    closePopup: function( )
    {
        this.popupbg.setStyle('display', 'none');
    },

    startAccordions: function( )
    {
        $$('.accordion').each( this.startAccordion.bind(this) );
    },

    startAccordion: function( item )
    {
		if (item.getElements('.toggler').length > 0)
		{
	        item.fx = new Fx.Accordion( item.getElements('.toggler'), item.getElements('.block') );
	        item.getElement('.toggler-selected').fireEvent('click');
	        item.fx.addEvent('onActive', function(toggler,element) {
	            toggler.addClass('toggler-selected');
	        } );
	        item.fx.addEvent('onBackground', function(toggler,element) {
	            toggler.removeClass('toggler-selected');
    	    } );
		}
    },

    startCarousels: function( )
    {
        $$('.carousel').each( this.startCarousel.bind(this) );
    },

    startCarousel: function( item )
    {
        item.img = item.getElement('.carousel-img');
        item.voices = item.getElements('li a');
        for (var i=0; i<item.voices.length; i++)
        {
            item.voices[i].addEvent('click', function(item, index) {
                $clear( item.loopTimer );
                this.stepCarousel( item, index );
            }.pass([item, i], this) );
            item.voices[i].addEvent('click', function(e) { new Event(e).stop(); } );
        }
        item.loopIndex = 0;
        item.loopTimer = this.stepCarouselLoop.periodical( 3000, this, [item] );
    },

    stepCarouselLoop: function( item )
    {
        item.loopIndex++;
        if (item.loopIndex >= item.voices.length)
            item.loopIndex = 0;
        this.stepCarousel( item, item.loopIndex );
    },

    stepCarousel: function( item, index )
    {
        item.img.getElement('img').src = item.voices[index].get('rel');
        item.img.set('href', item.voices[index].get('href'));
        item.voices.each( function(el,i) { el.removeClass('carousel-selected'); } );
        item.voices[index].addClass('carousel-selected');
    },
	
	startCarousels2: function( )
    {
        $$('.carousel').each( this.startCarousel2.bind(this) );
    },

    startCarousel2: function( item )
    {
        item.img = item.getElement('.carousel-img');
		item.list = item.getElement('ul');
        item.voices = item.getElements('li a');
		item.addClass('js-carousel');
		item.img.setStyle('display', 'none');
		item.list.setStyle('display', 'none');
		item.voices.setStyle('display', 'none');
		
		item.slider = new Element('div', {'class': 'js-carousel-slider'}).setStyle('width', item.voices.length * 280).inject( item );
		item.caption = new Element('div', {'class': 'js-carousel-title'} ).inject( item );
		item.fx = new Fx.Tween( item.slider, {'property': 'margin-left'} );
		item.slides = [];
		item.thumbbox = new Element('div', {'class': 'js-carousel-thumbbox' }).inject( item )
		item.thumbs = [];
		item.fx_options = { 'link': 'cancel', 'duration': 1000, 'transition': Fx.Transitions.Bounce.easeOut };
        for (var i=0; i<item.voices.length; i++)
        {
        	item.slides[i] = new Element('div', {'class': 'js-carousel-slide'} ).inject( item.slider );
			item.slides[i].lnk = new Element('a', {'href': item.voices[i].get('href')} ).inject( item.slides[i] );
			item.slides[i].img = new Element('img', {'src': item.voices[i].get('rel')} ).inject( item.slides[i].lnk );
			item.slides[i].fx = new Fx.Morph( item.slides[i], item.fx_options );
			item.slides[i].img.fx = new Fx.Morph( item.slides[i].img, item.fx_options );
			
			item.thumbs[i] = new Element('div', {'class': 'js-carousel-thumb'} ).inject( item.thumbbox );
			item.thumbs[i].img = new Element('img', {'src': item.voices[i].get('rel')} ).inject( item.thumbs[i] );
			item.thumbs[i].addEvent('click', function(item,i) { $clear(item.timer); item.index = i-1; this.stepCarousel2(item); }.pass([item,i], this) );
        }
		
		item.index = -1;
		this.stepCarousel2( item );
		item.timer = this.stepCarousel2.periodical( 3000, this, item );
    },
	
	stepCarousel2: function( item )
	{
		var k=0;
		var go = false;
		for (var i=0; i<item.slides.length; i++)
		{
			item.slides[i].setStyle('display', 'block');
			//if ( (i >= item.index) && (i < item.index+3) )
			//if ( ( (k == 1) && (item.index > -1) ) || ( (k == 0) && (item.index == -1) ) )
			if (i == item.index+1)
			{
				var w = 280;
				var m = 10;
				item.caption.html( item.voices[i].get('html') );
				item.thumbs[i].addClass('js-carousel-thumb-selected');
			}
			else
			{
				var w = 140;
				var m = 70;
				item.thumbs[i].removeClass('js-carousel-thumb-selected');
			}
			
			item.slides[i].fx.start( {
				'width': w,
				'height': w,
				'margin-top': m,
				'margin-bottom': m
			} );
			item.slides[i].img.fx.start( {
			'width': w - 20
			} );
			
			k++;
		}
		if (item.index >= item.slides.length-1)
		{
			var ml = 0;
			item.index = -1;
			item.fx.start( ml );
		}
		else
		{
			var ml = -(item.index*140);
			item.fx.start( ml );
			item.index++;
		}
	},

    startAudios: function( ) {
        $$('.play-mp3').each( this.startAudio.bind(this) );
    },

    startAudio: function( item ) {
        if (!this.player)
        {
            var i = 0;
            this.playerOptions = {
                'swfLocation': 'includes/libraries/player/MooSound.swf',
		        'onRegister': function() {},
		        'onLoad': function() { },
		        'onPause': function() { },
		        'onPlay': function() {   },
		        'onStop': function() {  },
		        'onProgress': function(loaded, total) {
			       // var percent = (loaded / total*100).round(2);
			       // this.seekbar.get('tween').start('width', percent * .85);
		        },
		        'onPosition': function(position,duration) {},
		        'onID3': function(key, value) {
		        },
		        'onComplete': function() {
		        }
	        };
            this.player = new Playlist( this.playerOptions );
            this.player.playing = null;
        }
        item.progress = new Fx.Tween( item, { property: 'background-position', 'unit': '%', transition: Fx.Transitions.Elastic.easeOut } );

        item.addEvent('click', function( e ) { new Event(e).stop(); } );
        item.addEvent('click', function( item ) {
            var url = item.get('href');
            if (this.player.playing == url)
            {
                this.pauseAudio( url, item );
            }
            else if (this.player.pausing == url)
            {
                this.resumeAudio( url, item );
            }
            else
            {
                if (this.player.playing != null)
                {
                    this.stopAudio( this.player.playing, item );
                }
                this.playAudio( url, item );
            }
        }.pass(item, this) );
    },

    playAudio: function( url, item )
    {
        this.player.playing = url;
        this.player.loadSound( url, {
            onRegister: function() {
                this.start.delay( 100, this );
            },
            onPlay: function() { item.addClass('play-mp3_play'); },
            onStop: function() { item.removeClass('play-mp3_play'); },
            onComplete: function() { item.removeClass('play-mp3_play'); },
            onPosition: function(position, total)
            {
                var percent = (position / total*100).round(2);
                this.progress.start( percent+'% 0%' );
                if (percent == 100) { item.removeClass('play-mp3_play'); var time = ''; }
                else                { var time = total /*convertTime( total );*/ }
                //this.getElement('span').set('html', time );
            }.bind(item)
        } );
    },

    pauseAudio: function( url )
    {
        this.player.playing = null;
        this.player.pausing = url;
        this.player.getSound( url ).pause();
    },

    resumeAudio: function( url )
    {
        this.player.playing = url;
        this.player.pausing = null;
        this.player.getSound( url ).start();
    },

    stopAudio: function( url )
    {
        this.player.playing = null;
        this.player.getSound( url ).stop();
    },

    startVideos: function( ) {
        $$('.play-video').each( this.startVideo.bind(this) );
    },

    startVideo: function( item )
    {
        item.icon = new Element('span', {'class':'play-video-icon'}).setStyles( {'width': item.getElement('img').getSize().x, 'height': item.getElement('img').getSize().y} ).set('html', '&nbsp;').inject( item, 'top' );
        item.icon.addEvent('click', this.openVideo.pass(item, this) );
        item.icon.addEvent('click', function(e) { new Event(e).stop(); } );
		
		var pos = location.href.indexOf('#');
		if (pos !== -1)
		{
			if ( location.href.substring(pos+1) == 'play-video-'+item.get('rel') )
				this.openVideo( item );
		}
    },
	
	openVideo: function( item )
	{
		var vid = item.get('rel');
        var url = 'http://www.youtube.com/v/'+vid+'&hl=it&fs=1&color1=0xe1600f&color2=0xfebd01&autoplay=1';
        var html = '<object width="460" height="380"><param name="movie" value="'+url+'"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="'+url+'" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="460" height="380"></embed></object>';
        //item.set('html', html);
		this.popup.box.html( html );
        this.popupbg.setStyle('display', 'block');
	},
	
	startMarquees: function( ) {
        $$('.marquee').each( this.startMarquee.bind(this) );
    },

    startMarquee: function( item )
    {
    	item.items = item.getElements('div');
		item.index = 0;
		for (var i=0; i<item.items.length; i++)
		{
			item.items[i].fx = new Fx.Tween( item.items[i], {'property': 'opacity', 'duration': 500}).set(0);
		}
		this.startMarqueePlay( item );
    },
	
	startMarqueePlay: function( item )
	{
		item.items[item.index].fx.start(1).chain( function(item) {
			item.items[item.index].fx.start.delay(2000, item.items[item.index].fx, 0);
			item.index++;
			if (item.index > item.items.length-1)
				item.index = 0;
			this.startMarqueePlay.delay( 2200, this, item );
		}.pass(item,this) );
	},
	

    startFastSearches: function( )
    {
        $$('.fast-search').each( this.startFastSearch.bind(this) );
    },

    startFastSearch: function( item )
    {
        item.act = item.getElement('.fast-action').get('value');
        item.trg = item.getElement('.fast-target');
		item.dtl = item.getElement('.fast-details');
        item.addEvent('submit', this.launchFastSearch.pass(item, this) );
        item.addEvent('submit', function(e) { new Event(e).stop(); } );

        var inputs = item.getElements('input, select, textarea', true)
        for (var i=0; i<inputs.length; i++)
        {
            inputs[i].addEvent('change', function(item) {
                this.launchFastSearch( item );
            }.pass(item,this) );
        }
		
		this.parseFastSearch(item);
    },

    launchFastSearch: function( item )
    {
        var xhr = new Request( { url: item.act, method: 'post', encoding: 'iso-8859-1', data: item.toQueryString() } ).send();
        xhr.addEvent('onComplete', function(response) {
            item.trg.html( response, { 'onComplete': this.parseFastSearch.pass(item) } );
        }.bind(this) );
        return false;
    },
	
	parseFastSearch: function( item )
	{
		item.links = item.trg.getElements('.fast-links');
		for (var i=0; i<item.links.length; i++)
		{
			item.links[i].addEvent('click', function(item, i) {
				var href = item.links[i].get('rel');
				var xhr = new Request( { url: href } ).send();
				xhr.addEvent('onComplete', function(response) {
					item.dtl.html(response);
				} );
			}.pass([item,i], this) );
			item.links[i].addEvent('click', function(e) { new Event(e).stop(); } );
		}
	},

    foo: function(){}
} );

function convertTime( seconds )
{
    mins = Math.floor(seconds / 60);
    secs = seconds % 60;
    return mins + ':' + ((secs < 10) ? '0' : '') + secs;
}

Element.implement( {

	html: function( html, options ) {
		if (!this.fx)
			this.fx = new Fx.Tween( this, {'duration': 500, 'transition': Fx.Transitions.Pow.easeInOut} );
		this.fx.start('opacity', 0)
		.chain( function(html, options) {
			this.set('html', html);
			this.fx.start('opacity', 1);
			if (options)
				options.onComplete.attempt();
		}.pass([html, options], this) );
	}
	
} );