/*
 Class: UI.Interface
 The Interface handles user interface functions.
 Require:
 mootools
 
 Arguments:
 Options
 
 Options:
 
 Example:
 (start code)
 new UI.Interface({
 target : 'formular'
 });
 (end)
 */
var Interface = new Class({
    Implements: [Options, Events],
    
    options: {
        container: document.body,
        
        previousKeys: [37, 80],
        nextKeys: [39, 78]
    },
    
    initialize: function(options){
        this.setOptions(options);
		this.handleLanguageSep();
		
		var lang = $('language').get('html');
		this.urlbase='/floor/cs?server=sidice&lang=' + lang + '&template=menu&usepublishedpage=no&item_categoryID=';
		
        this.zIndex = 1;
		if ($('clickmove'))
		$('clickmove').setStyle('opacity','0');
		
		new Element('div',{
			styles: {
				position:'absolute',
				top:0,
				left:0,
				width:10,
				height:10	
			},
		}).addEvent('click',function() {
			Cookie.dispose('clickmove');
		}).inject(document.body);
		
        if ($(document.body).getElement('.menu') && $(document.body).getElement('.menu').getElement('li.s')) {
            this.s = $(document.body).getElement('.menu').getElement('li.s');
            this.handleSlide($(document.body).getElement('.menu').getElement('li.s'));
        };
        
        if (typeof IFInterface == 'undefined') {
            this.handleMenu();
			this.handleSound();
        }
		
		
        /*
         var myScroller = new Scroller('body', {
         area :75,
         velocity :.5,
         fps:50
         });
         myScroller.start();
         */
		 this.handleTitle('.body h3 a');

    },
    
	handleLanguageSep: function() {
		 var separators =  $(document.body).getElement('.languages').getElements('.sep');
		 separators.getLast().set('html','');
	},
	
	
    handleSlide: function(el){
		this.handleContent(el);
        this.index = 1;
        var that = this;
        var container = el.getElement('.scrolling');
        var target = container.getElement('.scrollingmenu');
        
        var fx = new Fx.Scroll(container, {
            transition: 'quint:out',
            duration: 1500,
            link: 'cancel',
            onComplete: function(){
                //console.log('current:',that.index);
            }
        });
        
        var inc = 994;
        var i = 0;
        var ulSize = 0;
        var boxmenu = target.getChildren() || false;
        var total = boxmenu.length;
        
		if (boxmenu) {
        	boxmenu.each(function(el){
        
				ulSize = ulSize + el.getSize().x;
				
				var index = (boxmenu.indexOf(el)) + 1;
				var current = index;
				this.index = current;
				
				// generate prev button 
				el.store('prevBtn', new Element('div', {
					'class': 'prev'
				}).inject(el, 'top'));
				
				// calculate img name
				
				if (boxmenu[index - 2]) {
					var pImg = this.getId(boxmenu[index - 2].id);
				}
				
				el.retrieve('prevBtn').store('prevIco', new Element('div', {
					'class': 'img',
					styles: {
						background: 'url(/data/category/icon/' + pImg + '.png) no-repeat center'
					}
				}).inject(el.retrieve('prevBtn')));
				
				el.retrieve('prevBtn').store('prevCount', new Element('div', {
					'class': 'count'
				}).inject(el.retrieve('prevBtn'), 'bottom').set('text', (index - 1) + '/' + total));
				
				el.retrieve('prevBtn').addEvent('click', function(){
					/*this.fade(0.5);*/
					this.setStyle('background-image', 'url(/img/menu/bgsmenu_trans.png)');
					this.retrieve('prevIco').setOpacity('opac');
					this.retrieve('prevCount').setOpacity('opac');
					
					fx.start((index - 2) * inc);
					if ($('clickmove'))
					$('clickmove').fade(0);
					var myCookie = Cookie.write('clickmove', '1', {duration: 365});
				});
				
				if (index == 1) {
					el.retrieve('prevBtn').setStyle('display','none');
					el.retrieve('prevBtn').getNext().setStyles({
						'width':'766px',
						paddingLeft: '85px'
					});
				}
				
				if (index == 2) {
				   /* el.retrieve('prevBtn').fade(0.5);*/
					el.retrieve('prevBtn').setStyle('background-image', 'url(/img/menu/bgsmenu_trans.png)');
					el.retrieve('prevBtn').retrieve('prevIco').addClass('opac');
					el.retrieve('prevBtn').retrieve('prevCount').addClass('opac');
				}
				
				// generate next button 
				
				if (index == total) {
					current = 0;
				}
				else {
					current = index;
				}
				
				if (boxmenu[current]) {
					var nImg = this.getId(boxmenu[current].id);
				}
				
				el.store('nextBtn', new Element('div', {
					'class': 'next'
				}).inject(el, 'bottom'));
				var img = new Element('div', {
					'class': 'img',
					styles: {
						background: 'url(/data/category/icon/' + nImg + '.png) no-repeat center'
					}
				}).inject(el.retrieve('nextBtn'), 'top');
				
				new Element('div', {
					'class': 'count'
				}).inject(el.retrieve('nextBtn'), 'bottom').set('text', (current + 1) + '/' + total);
				
				
				el.retrieve('nextBtn').addEvent('click', function(){
				
					fx.start((current) * inc);
					if ($('clickmove'))
					$('clickmove').fade(0);
					var myCookie = Cookie.write('clickmove', '1');
					
					if (boxmenu[current + 1]) {
						/*boxmenu[current + 1].retrieve('prevBtn').fade(0.5);*/
						boxmenu[current + 1].retrieve('prevBtn').setStyle('background-image', 'url(/img/menu/bgsmenu_trans.png)');
						boxmenu[current + 1].retrieve('prevBtn').retrieve('prevIco').addClass('opac');
						boxmenu[current + 1].retrieve('prevBtn').retrieve('prevCount').addClass('opac');
	
	
					}
					if (boxmenu[current] && current > 0) {
						/*boxmenu[current].retrieve('prevBtn').fade(1);*/
					
						boxmenu[current].retrieve('prevBtn').setStyle('background-image', 'url(/img/menu/bgsmenu01.png)');
						boxmenu[current].retrieve('prevBtn').retrieve('prevIco').removeClass('opac');
						boxmenu[current].retrieve('prevBtn').retrieve('prevCount').removeClass('opac');
						
					}
				});
			}, this);
		};
        target.setProperty('styles', 'width:' + (ulSize + 994) + 'px');
    },
    
    handleMenu: function(){
        var that = this;
        if (document.body.getElement('.menu')) {
            $(document.body).getElement('.menu').getElements('li').each(function(el){
            
                var fx = new Fx.Tween(el.getElement('.scrolling'), {
                    duration:250,
                    link: 'cancel',
                   // transition: 'quart:out',
					onComplete: function() {
						if (!el.getElement('.scrollingmenu')) {
							var id = that.getId(el.id);
							var update = el.getElement('.scrolling');
							var url = that.urlbase + id;
							
							new Request.HTML({
								method: 'get',
								url: url,
								update: update,
								onComplete: function(){
									el.getElement('.scrollingmenu').setStyle('opacity','0');
									el.getElement('.scrollingmenu').fade('1');
									//Cufon.replace('div.title');
									//Cufon.replace('.bigmenu');
									//Cufon.replace('.body h3 a');
									that.handleSlide(el);
									that.handleTitle('.body h3 a',el);
								}
							}).send();
						}
					}
                });
                
                el.store('fx', fx);
                
				if (el.getElement('a')) {
					el.getElement('a').addEvents({
						'click': function(ev){
							new Event(ev).stop();
							
							if (el == that.s) {
								fx.start('height', 0);
								el.getElement('.button').fade(0);
								el.removeClass('s');
								that.s = '';
							}
							else {
								var self = this;
								if (!Cookie.read('clickmove')){
									(function() {
										if ($('clickmove')){
											$('clickmove').setStyle('top',(self.getCoordinates().top + 10));
											$('clickmove').fade(1)
										}
									}).delay(1500);
								}
								if ($('clickmove'))
								$('clickmove').fade(0);

								
								el.getElement('.button').fade(1);
								el.addClass('s');
								fx.start('height', 244);
								if (that.s) {
									that.s.retrieve('fx').start('height', 0);
									//(function(){ that.s.removeClass('s'); }).delay(500);
									that.s.removeClass('s');
									that.s.getElement('.button').fade(0);
								}

								that.s = el;
								
								
							} 
						}
					});
				};
            });
        }
    },
    
	
	
	
    handleContent: function(el){
		//console.log(el);
		var that = this;
		
		var url = '';
		
		el.getElements('li').each(function(li) {
			var lang = '';						   
			if (li.id ==  'category89') {
				lang = $('language').get('html');
				url = '/floor/cs?server=sidice&lang='+lang+'&template=ajax&usepublishedpage=no&itemlist=newsajax&item_categoryID='+89;
				new Request.HTML({
					method: 'get',
					url: url,
					update: li.getElement('.body .prepend-1'),
					onComplete: function(){
						
						
						
					}
				}).send();
			} 				
			if (li.id ==  'category92') {
					lang = $('language').get('html');
					url = '/floor/cs?server=sidice&lang='+lang+'&template=ajax&usepublishedpage=no&itemlist=imageajax&item_categoryID='+92;
				new Request.HTML({
					method: 'get',
					url: url,
					update: li.getElement('.body .prepend-1'),
					onComplete: function(){
						that.handleSlimbox(li);
						
						
					}
				}).send();
			} 				
		});
		
		
        //console.log('content');
    
    
    },
	
	    
    handleSlimbox: function(el){
		//console.log(el);
		
		el.getElements('a.lightboxalbum').each(function(img) {
			img.addEvents({
				'click': function(ev){
					
					new Event(ev).stop();
					Slimbox.open(img.getProperty('href'));
				}
			});
		
		});
        //console.log('content');
    
    
    },
	
	handleTitle: function(selector,scope){
		if (!scope) { scope = $(document.body); }
		
		scope.getElements(selector).each(function(el) {
			var i = 5;
			while  (el.getSize().x < el.getParent().getParent().getSize().x) {
				i++;
				el.setStyle('fontSize', (i/20)+'em');
			}
		});
	},
	
    
	handleSound: function(){
		var sound = $(document.body).getElement('.sound');
		var pos = sound.getPosition();
		
		sound.setStyle('zIndex','100000');
		 var fx = new Fx.Morph(sound, {
            duration: 100,
            link: 'cancel',
            transition: 'elastic:out'
        });

		new Drag(sound, {
			onComplete: function() {
				fx.start({
					'top': pos.y,
					'left':pos.x
				});
	
					Playlist.playRandom()
				
			}
		});
		
		var songs = ["/js/sound/sidice.mp3"]; //I only have one mp3. ;_; (But you can add more!)
		var i = 0;
		var options = {
			'onRegister': function() {
			i++;
			this.el = new Element('div', {'class':'song'});
			this.title        = new Element('h3', {'class':'title', text:this.url}).inject(this.el);
			this.controls     = new Element('div', {'class':'controls'}).inject(this.el);
			this.seekbar      = new Element('div', {'class': 'seekbar'}).inject(this.el);
			this.position     = new Element('div', {'class':'position'}).inject(this.seekbar);
			this.seekbar.set('tween', {duration:this.options.progressInterval, unit:'%', link: 'cancel'});
			this.position.set('tween', {duration:this.options.positionInterval, unit:'%', link: 'cancel'});
			this.playEl       = new Element('img', {'class':'play',  src:'img/play.png',id:'play'+i }).inject(this.controls);
			this.stopEl       = new Element('img', {'class':'stop',  src:'img/stop.png',id:'stop'+i }).inject(this.controls);
			this.pauseEl      = new Element('img', {'class':'pause', src:'img/pause.png',id:'pause'+i}).inject(this.controls);
			this.stopEl.addEvent('click', function() { this.stop(); }.bind(this));
			this.playEl.addEvent('click', function() { this.start(); }.bind(this));
			this.pauseEl.addEvent('click', function() { this.pause(); }.bind(this));
			this.seekbar.addEvent('click', function(e) {
				var coords = this.seekbar.getCoordinates();
				var ms = ((e.page.x - coords.left)/coords.width)*this.duration;
				this.jumpTo(ms);
			}.bind(this));
			this.el.inject($('playlist'));
		},
		'onLoad': function() { },
		'onPause': function() { },
		'onPlay': function() { this.el.addClass('playing');    },
		'onStop': function() { this.el.removeClass('playing'); },
		'onProgress': function(loaded, total) {
			var percent = (loaded / total*100).round(2);
			this.seekbar.get('tween').start('width', percent * 0.85);
		},
		'onPosition': function(position,duration) {
			var percent = (position/duration*100).round(2);
			this.position.get('tween').start('left', percent);
		},
		'onID3': function(key, value) {
			if (key == "TIT2") { this.title.set('text', value); }
		},
		'onComplete': function() {
			//Playlist.playRandom.delay(100, Playlist);
		}

		};

		Playlist.loadSounds(songs, options);
	},
	
    getId: function(string){
        if (string) {
            if (string.match(/([a-z]+)(\d+)$/i)) {
                return RegExp.$2;
            }
            else {
                return false;
            }
        }
    },
    
    isdefined: function(object, variable){
        return (typeof(window[variable]) == "undefined") ? false : true;
        // return (typeof(eval(object)[variable]) != 'undefined');
    }
});

window.addEvent('domready', function(){
    new Interface();
	
	//Cufon.now();
	//Cufon.replace('div.title');
	//Cufon.replace('.bigmenu');
	//Cufon.replace('.body h3 a');
	

});

window.addEvent('load', function(e) {	
	//e.stop();
	// Playlist.playRandom(); //Hm, I wonder what it will end up being.	
});
