/* 
	SPILL FOR REMITESSIER 
	2011
	
	@author saz
*/



// Location HREF Lang Hack
if (!location.pathname.match(/^(\/..)\/.*$/)) {
window.location = "/" + $("html").attr("lang") + "/";
}
 



/* Basics */
// GLOBAL HELPERS
var trace = cl = function(){
	(window.console) ? console.log([].slice.call(arguments)) : null;//alert(arguments) ;
}

/* JQUERY PLUGINS */
function jPlugins(){
    
    /* HAS OVERFLOW */
	// helper to detect if element has scrollbar 
	(function($) {
	    $.fn.hasOverflow = function(axis) {
            return axis == 'x' ? this[0].scrollWidth > this.width() : this[0].scrollHeight > this.height();
	    }
	})(jQuery);
    
	window.hasElement = function (str){ return Boolean($(str)[0]) }
	window.getElements = function (str){ return $(str) }
	window.getFirstElement = function (str){ return $(str)[0] }
	// ...rest
    
    window.resizeRatio = function(el, centered)
    {
        var p = $(document.documentElement) ;
        var fittingWidth = p.width() ;
        var fittingHeight = p.height() ;
        var fittingRatio = fittingWidth / fittingHeight ;
        var originalWidth = el[0].width ;
        var originalHeight = el[0].height ;
        var originalRatio = originalWidth / originalHeight ;
        if(originalRatio < fittingRatio){ // WIDTH NEEDS TO FIT
            // FIRST RESIZE WIDTH
            el.width(fittingWidth)
            el.height(Math.round(el.width() / originalRatio)) ;
            
        }else if (originalRatio > fittingRatio){ // HEIGHT NEEDS TO FIT IN
            // FIRST RESIZE HEIGHT
            el.height(fittingHeight)
            el.width(Math.round(el.height() * originalRatio)) ;
            
        }
        if (centered) {
            el.css({'left': (p.width() - el.width()) *.5}) ;
            el.css({'top': (p.height() - el.height()) *.5}) ;
        }
    }
}







/* DOMREADY */
window.domReadyClosure = function(){
    jPlugins() ;
    
    // TOP MENU
	new MenuHandler().init() ;
    
    //new LogoHandler().init() ;
    
    
    // BASIC WINDOW EVENTS
    // RESIZE HANDLER
    window.scrollResize = function(){
        if(window.scroller) window.scroller = window.scroller.destroy() ;
        window.scroller = new ScrollHandler().init() ;
        
        $('img.resizable').each(function(i, el){
            window.resizeRatio($(el), true) ;
        }) ;
        
    } ;
    
    $(window).resize(window.scrollResize) ;
}

/* ACTIVE CONTENT */
window.activeContentClosure = function(cond){
	
    if(cond == false){
        // should kill now...
        
        
        // slideshowHandler
        
        if(window.slideshow){
            window.slideshow.stopPlayback() ;
            window.slideshow.paused = true ;
            window.slideshow = window.slideshow.destroy() ;
        }
        // projectHandler
        //
        
        // scrollHandler
        if(window.scroller) window.scroller = window.scroller.destroy() ;
        
    }else{
        if($(document.documentElement).hasClass("no-backgroundsize")){ // IE 8- FIX 
            $('.fullbackground').each(function(i, el){
				if(i != 0) return ;
                var url = $(el).css('background-image').replace(/(^url\("?|"?\)$)/g, '') ;
                $(el).css('background-image', 'none') ;
                if(url == "" || url == undefined || url == null) return ;
                var img = $(new Image) ;
                img.attr({'src':url, 'class':'resizable'});
                img.css({'position':'absolute','zoom':1}) ;
                img.ready(function() {
                    window.resizeRatio(img, true) ;
                    img.appendTo($(el).parent()) ;
                    window.extraImg = img ;
                });
            }) ;
        }
        
        
        // SLIDESHOW
        var intro = $('#intro') ;
        var logofooter = $('#logofooter') ;
        var topnav = $('#mainmenu') ;
        if(Boolean(intro[0])) { // HOME SLIDESHOW
            
            var logo = $('#logo') ;
            
            var enableClosure = function(passcond){
                
                passcond = passcond || false ;
                // hard bypass listener
                ajaxManager.hardUpdateHash('/') ;
                
                window.passedIntro = true ;
                
                if(Boolean(window.slideshow)) {
                    window.slideshow.stopPlayback() ;
                    window.slideshow.paused = true ;
                    window.slideshow = window.slideshow.destroy() ;
                }
                
                if(passcond == false){
                    intro.fadeOut('slow', function() {
                        intro.remove() ;
                        logo.fadeOut('fast', function(){
                            logo.remove() ;
                            logofooter.fadeOut(0) ;
                            logofooter.removeClass('hidden') ;
                            logofooter.fadeIn('fast', function(){
                                topnav.fadeOut(0) ;
                                topnav.removeClass('hidden') ;
                                topnav.fadeIn('fast', function(){
                                    window.slideshow = new SlideshowHandler('home', 'looping').init() ;
                                }) ;
                            }) ;
                        })
                    });
                }else{
                    setTimeout(function(){
                        intro.remove() ;
                        logo.fadeOut('fast', function(){
                            logo.remove() ;
                            window.slideshow = new SlideshowHandler('home', 'looping').init() ;
                        })                    
                    },500) ;
                }
            } ;
			
            if(Boolean(window.passedIntro)){
                enableClosure(true) ;
                return ;
            }else{
            
            
            
            }
            
            window.slideshow = new SlideshowHandler('home', 'intro', enableClosure, 1000).init() ;
            logo.bind('click',function(e){
                logo.unbind('click', arguments.callee) ;
                e.preventDefault() ;
                if(window.slideshow){
                    window.slideshow.stopPlayback() ;
                    window.slideshow.paused = true ;
                    window.slideshow = window.slideshow.destroy() ;
                }
                enableClosure() ;
            }) ;
        }else{
            logofooter.removeClass('hidden') ;
            topnav.removeClass('hidden') ;
            if(Boolean($("ul.slides")[0])) window.slideshow = new SlideshowHandler('project', 'looping').init() ;
        }
        
        // SCROLLERS
        window.scroller = new ScrollHandler() ;
    }
}


/* CORE FUNC */


//JS added CLASS FOR IE
//"no-backgroundsize"

/*

    ajaxManager.ajaxPost("/en/","_logout=1");
    ajaxManager.hardUpdateHash("/");

 */


/* SLIDESHOWS */
/* CHAIN OBJECT */

var Command = function(/*thisObj, closure, params*/){
    var c = {
        init:function(thisObj, closure, params){
            this.params = params ;
            this.context = thisObj ;
            this.closure = closure ;
            
            this.execute = function(){
                return this.closure.apply(this.context, [].concat(this.params)) ;
            } ;
            this.toString = function(){
                return "Object Command"
            } ;
            
            this.destroy = function(){
                this.toString =
                this.params =
                this.context =
                this.closure =
                this.execute =
                null ;
                
                delete this.toString ;
                delete this.params ;
                delete this.context ;
                delete this.closure ;
                delete this.execute ;
                
                return null ;
            } ;
            
            return this ;
        }
    } ;
    return arguments.length == 0 ? c : c.init.apply(this, [].slice.call(arguments)) ;
}

var CommandQueue = function() {
    var commands = [];
    var queueIndex = -1;
    var cq = {
        add: function(command) {
            commands.push(command);
        },
        remove: function(command) {
            commands.slice(command, 1);
        },
        execute:function() {
            this.next() ;
        },
        next:function(){
            var ind = queueIndex + 1 ;
            var c = commands[ind] ;
            if(!Boolean(c)) {
                return this.destroy() ;
            }
            
            var r = c.execute() ;
            queueIndex = ind ;
            if(r != null && r != undefined) { // returns something
                // wait for callback
                $(c).bind("commandComplete", function(e){
                    $(c).unbind("commandComplete", arguments.callee) ;
                    cq.next() ;
                })
            }else{ // has to delay execution of next
                // flush & go
                next() ;
            } 
        },
        destroy:function() {
            var l = commands.length ;
            while(l--){
                commands.pop().destroy() ;
            }
            
            commands = 
            add = 
            remove = 
            execute = 
            next = 
            null ;
            
            delete this.add ;
            delete this.remove ;
            delete this.execute ;
            delete this.next ;
            
            return null ;
        }
    }
    return cq ;
}

/* REQUEST OBJECT */
var Request = function(index, url, complete, error, success){
    //
	var r = {
		init:function(index, url, complete, error, success){
            this.userdata = {};
			this.index = index ;
			this.url = url ;
			
			this.success = success || function(){
				//trace('success loading > '+this.url) ;
			};
			this.error = error || function(){
				//trace('error loading > '+this.url+' >> '+arguments) ;
			};
			this.complete = complete || function(){
				//trace('loading complete > '+this.url) ;
			};
            this.toString = function(){
                return "Object Request [" + url + "]" ;
            } ;
			this.destroy = function(){
                for(var s in this.userdata){
                    this.userdata[s] = null ;
                    delete this.userdata[s] ;
                }
                this.userdata = 
                this.index =
				this.url =
				this.complete = 
				this.error = 
				this.success =
				this.load =
				this.destroy =
                null ;
				return null ;
			}
            this.load = function(){
                var s = $.ajax({
                  url: this.url,
                  cache: false,
                  success: function(xhr){
                    complete(xhr) ;
                    if(r.userdata && r.userdata.command) $(r.userdata.command).trigger("commandComplete") ;
                  },
                  error:function(xhr){
                    if(xhr.readyState == 4 && xhr.status == 0)
                    this.success(xhr) ;
                  }
                });
                return this ;
            }
			return this;
		}
	}
	return arguments.length == 0 ? r : r.init.apply(this, [].slice.call(arguments)) ;
}




// SLIDESHOW HANDLER
var SlideshowHandler = function(loc, context, closure, duration){
    //
    var hasClosure = closure != undefined ;
	if(duration == undefined) duration = 3000 ;
	var scope = {
		init:function(){
            scope.playhead = loc == 'home' ? -1 : 0 ; // supposed to be -1 in real but here we skip first...
            scope.looping = (context == 'looping') ? true : false ; // if supposed to loop... further settings
			scope.stopped = true ; // resetted
			scope.paused = false ; // user halting
			scope.commandQueue = new CommandQueue() ; // loading queue
            
            if(loc == "home"){
                if(context == 'intro'){
                    scope.images = $('#intro .dispNone img').map(function(){
                        return this.src ;
                    }).toArray() ;
                }else{
                    $('.slideshow').css('cursor', 'pointer') ;
                    $('.projecttitle h2 span').css('cursor', 'pointer') ;
                    scope.images = $('.slides .dispNone a').map(function(){
                        return $(this).children('img').attr('src') ;
                    }).toArray() ;
                }
            }else if(loc == 'project'){
                scope.images = $('.slides .dispNone a').map(function(){
                    var link = this.href.replace(window.location.protocol+'//'+window.location.host , '') ;
                    var r = /^(\/..)\/.*\//;
                    var hrefMatch = r.exec(link);
                    return hrefMatch[1] + '/content' + hrefMatch[0].replace(hrefMatch[1], '') ;
                }).toArray() ;
                $('#controls').removeClass('dispNone') ;
                $('.slideshow').css('cursor', 'default') ;
            }
			scope.lis = $('.slides li') ;
			scope.initImages() ;
            
            return scope ;
		},
		initImages:function(){
			var arr = scope.images;
			var l = arr.length ;
			var lis = scope.lis ;
            
			for(var i = 0 ; i < l ; i++)
			{
				var url = arr[i] ;
                var complete = (function(ind){
                    return function(e){
                        // ON COMPLETE
                        if(!Boolean(scope.lis)) return ;
                        var li = scope.lis[ind] ;
                        
                        var req = scope.images[ind] ;
                        if(!Boolean(req)) return ;
                        if(loc == 'home'){
                            if(context == 'intro'){
                                req.userdata.imgURL = $(li).children("img").attr('src') ;
                            }else{
                                var a = $(li).children("a") ;
                                req.userdata.href = a.attr('href') ;
                                req.userdata.title = a.attr('title') ;
                                req.userdata.imgURL = a.children('img').attr('src') ;
                                url = req.userdata.imgURL;
                            }
                        }else if(loc == 'project'){
                            req.userdata.imgURL = $($(e).find(".hiddenimage")).attr("src") ;
                            
							var reqSubtitle = $(e).find(".infos h2") ;
                            if(Boolean(reqSubtitle[0])){
                                req.userdata.subtitle = reqSubtitle.html() ;
                            }
							
							
							var reqDetails = $(e).find(".details") ;
                            if(Boolean(reqDetails[0])){
                                req.userdata.details = reqDetails ;
                            }
							var reqInfos = $(e).find(".infos .wikitext p") ;
                            if(Boolean(reqInfos[0])){
                                req.userdata.infos = reqInfos.parent().html() ;
                            }
                        }
                        
                        $(li).css('background-image', 'url('+req.userdata.imgURL+')') ;
                        $(req.userdata.command).trigger("commandComplete") ;
                        
                        if(ind == 0) scope.initShow() ;
                    }
                })(i) ;
                
				arr[i] = new Request(i, url, complete) ;
				
                 if(loc == "project" || context == "looping"){
                    var c = arr[i].userdata.command = new Command(arr[i], arr[i].load) ;
                    scope.commandQueue.add(c) ;
                 }else{
                    
                 }
			}
            
            if(loc == "project" || context == "looping"){
                scope.commandQueue.execute() ;            
            }else{
                scope.initShow() ;
            }
		},
		initShow:function(){
            window.wasAlreadyClicked = false ;
            scope.untouched = true ;
			// Arrows
			scope.initArrows() ;
            if(loc == "project") scope.treatChecks(scope.images[0]) ;
			scope.startPlayback() ;
		},
		initArrows:function(){
			// Arrows
			var selPrev = '.prev';
			var selPause = '.pause';
			var selNext = '.next';
			
			var aprev = scope.aprev = window.getElements(selPrev) ;
			var apause = scope.apause = window.getElements(selPause) ;
			var anext = scope.anext = window.getElements(selNext) ;
            
            aprev.removeAttr('href') ;
            apause.removeAttr('href') ;
            anext.removeAttr('href') ;
            
			scope.enable() ;
		},
        click:function(e){
            var url = window.location.protocol+'//'+window.location.host + scope.images[scope.playhead].userdata.href ;
            
            //needs to be cleaned here before leaving
            scope.togglePB() ;
            
            if(ajaxManager){
                ajaxManager.ajaxGet(scope.images[scope.playhead].userdata.href)
            }
        },
        togglePB:function(e){
            if(e){
                e.preventDefault() ;
                e.stopPropagation() ;
                e.stopImmediatePropagation() ;
            }
            scope.apause.toggleClass('play') ;
            scope.togglePlayback() ;
            scope.paused = !scope.paused ;
        },
        enable:function(cond){
            if(cond == false){
                if(scope.aprev) scope.aprev.unbind('click', scope.prev);
                if(scope.aprev) scope.apause.unbind('click', scope.togglePB);
                if(scope.aprev) scope.anext.unbind('click', scope.next);
                
                if(loc == "home" && context == "looping"){
                    $('.slideshow').unbind('click', scope.click) ;
                    $('.projecttitle').unbind('click', scope.click) ;
                }
            }else{
                if(loc == "home" && context == "looping"){
                    $('.slideshow').bind('click', scope.click) ;
                    $('.projecttitle').bind('click', scope.click) ;
                }
                    //
                if(scope.aprev) scope.aprev.bind('click', scope.prev);
                if(scope.apause)scope.apause.bind('click', scope.togglePB);
                if(scope.anext) scope.anext.bind('click', scope.next);
            }
        },
		startPlayback:function(){
			scope.intervalID = setInterval(function(){
				if(Boolean(scope.next)) scope.next() ;
			},duration) ;
			scope.stopped = false ;
		},
		stopPlayback:function(){
			clearInterval(scope.intervalID) ;
            scope.intervalID = null ;
			scope.stopped = true ;
		},
		togglePlayback:function(){
			scope.stopped ? scope.startPlayback() : scope.stopPlayback() ;
		},  
        play:function(n, time){
            if(n instanceof Request) n = n.index ;
            
            scope.treatKills(scope.images[scope.playhead]) ;
            
            var l = scope.images.length ;
            time = time || 800 ;
			var li = $(scope.lis[n]) ;
            var req = scope.images[n] ;
            var a = li.children('a') ;
            scope.enable(false) ;
            
            scope.treatChecks(req) ;
			var url = req.userdata.imgURL || req.url ;
            
            if($(document.documentElement).hasClass("no-backgroundsize")){ // IE 8- FIX 
                window.extraImg && window.extraImg.remove() ;
                var img = $('<img/>') ;
                img.attr({'src':url, 'class':'resizable'});
                img.ready(function() {
                    window.resizeRatio(img, true) ;
                    img.hide() ;
                    img.appendTo(li.parent()[0]) ;
                    img.fadeIn(500, function(){
                        scope.lastImage && scope.lastImage.remove() ;
                        if(loc == 'project'){
                            if(req && req.userdata && req.userdata.details) {
                                var detailBtn = $('#controls .detail') ;
                                detailBtn.removeClass('dispNone') ;
                            }
                        }
                        scope.lastImage = img ;
                        scope.enable() ;
                        scope.playhead = n ;
                    });
                });
                
                
            }else{
                
                li.removeClass('dispNone');
                li.fadeOut(0) ;
                li.css('background-image', 'url('+url +')') ;
               
                li.fadeIn(time, function(){
                    if(context == 'looping'){
                        $('.slideshow').css('background-image', 'url('+url +')') ;
                    }else{
                        $('.introslideshow').css('background-image', 'url('+url +')') ;
                    }
                    li.addClass('dispNone') ;
                    
                    if(loc == 'project'){
                        if(Boolean(req && req.userdata && req.userdata.details)) {
                            var detailBtn = $('#controls .detail') ;
                            detailBtn.removeClass('dispNone') ;
                        }
                    }
                    scope.enable() ;
                    scope.playhead = n ;
                });
                
            }
            
            
		},
		prev:function(e){
            if(e){
                e.preventDefault() ;
                e.stopPropagation() ;
                e.stopImmediatePropagation() ;
            }
            if(scope.timeoutID) clearTimeout(scope.timeoutID) ;
            if (scope.hasPrev()) {
                scope.paused ? scope.play(scope.getPrev()) :
                (function(){
                    scope.stopPlayback() ;
                    scope.play(scope.getPrev()) ;
                    scope.timeoutID = setTimeout(function(){scope.startPlayback()}, 850) ;
                })() ;
                
            }
		},
		next:function(e){
            if(e){
                e.preventDefault() ;
                e.stopPropagation() ;
                e.stopImmediatePropagation() ;
            }
            if (scope.timeoutID) clearTimeout(scope.timeoutID) ;
            if (scope.hasNext()) {
                scope.paused ? scope.play(scope.getNext()) :
                (function(){
                    scope.stopPlayback() ;
                    scope.play(scope.getNext()) ;
                    scope.timeoutID = setTimeout(function(){scope.startPlayback()}, 850) ;
                })() ;
                
            }else{
                scope.stopPlayback() ;
                if(hasClosure){
                    closure.call(scope) ;
                }
            }
		},
        getReq:function(n){
            var arr = scope.images ;
            var l = arr.length ;
            var s = arr[scope.playhead + n] ;
            return scope.looping ? (Boolean(s) ? s : n > 0 ? arr[0] : arr[l-1] ) : s ;
        },
        getPrev:function() { return scope.getReq(-1) },
        getNext:function() { return scope.getReq(1) },
        hasPrev:function() { return scope.getPrev() ?  true : scope.looping },
        hasNext:function() { return scope.getNext() ?  true : scope.looping },
        
        treatChecks:function(req){
            if(loc == 'home'){
                if(context == 'intro'){
                    //trace(req) ;
                    // don't do nothing for now...
                }else{
                    //trace(req) ;
                    // need to check for new project's title
                    var span = $('#nameProject h2 span') ;
                    span.fadeOut('fast', function(){
                        if(Boolean(req) && Boolean(req.userdata.title)){
                            span.text(req.userdata.title) ;
                            span.fadeIn('fast') ;
                        } 
                    })
                }
            }else if(loc == 'project'){
                if(Boolean(req.userdata.details)){
                    var detailBtn = $('#controls .detail') ;
                    if(detailBtn.hasClass('dispNone')) detailBtn.removeClass('dispNone') ;
                    req.userdata.details.prependTo('#content') ;
                }

                if(scope.untouched){
                    req.userdata.handler = new ProjectHandler().init(true) ;
                }else{
                    req.userdata.handler = new ProjectHandler().init(false) ;
                }
                
				
				
				var tgSubtitle = $('.infos h2') ;
				if(Boolean(req.userdata.subtitle)){
					var subtitletxt = req.userdata.subtitle ;
					tgSubtitle.html(subtitletxt) ;
                }else{
					tgSubtitle[0].innerHTML = "" ;
				}
				
				
				
                // and check for new content infos
                var tgInfos = $('.infos .wikitext') ;
				if(Boolean(req.userdata.infos)){
					var infostxt = req.userdata.infos ;
					tgInfos.html(infostxt) ;
					window.scroller = new ScrollHandler() ;
                }else{
					tgInfos[0].innerHTML = "" ;
					window.scroller = new ScrollHandler() ;
				}
            }
        },
        treatKills:function(req){
            scope.untouched = false ;
            if(!Boolean(req)) return ;
            // checks for details to kill
            if(loc == 'project'){
                if(req.userdata.handler) {
                    req.userdata.handler.destroy() ;
                }
                var oldDetails = $('.details') ;
                var detailBtn = $('#controls .detail') ;
                if(Boolean(oldDetails[0])){
                    oldDetails.remove() ;
                    if(!detailBtn.hasClass('dispNone')) detailBtn.addClass('dispNone') ;
                }
            }else if(loc == 'home'){
                if(context == 'looping'){
                    var span = $('#nameProject h2 span') ;
                    span.text('') ;
                }
            }
        },
		destroy:function(){
			
            scope.treatKills(scope.images[scope.playhead]) ;
            
			// images requests array cleanup
			var arr = scope.images ;
			var l = arr.length ;
			while(l--){
				var r = arr[l] ;
				r = (r instanceof Request) ? r.destroy() : null ;
				arr.pop() ;
			}
			
			// events removal
			scope.enable(false) ;
			
			// interval removal
			if(Boolean(scope.intervalID)) clearInterval(scope.intervalID) ;
			
			// cleanup all slideshow data
			scope.untouched = 
			scope.images = 
			scope.playhead = 
			scope.stopped = 
			scope.images = 
			scope.lis = 
			scope.aprev =
			scope.apause =
			scope.anext =
			scope.togglePB =
			scope.init =
			scope.initImages =
			scope.initShow =
			scope.initArrows =
			scope.togglePB =
			scope.togglePLayback =
			scope.startPLayback =
			scope.stopPLayback =
			scope.play =
			scope.next = 
			scope.prev =
			scope.timeoutID =
			scope.intervalID = null ;
			
			
			return null ;
		}
	} ;
	return scope ;
}


// TOPMENU HANDLING
var LogoHandler = function(){ 
    //
	return {
		init:function(){
			this.initLogo();
		},
		initLogo:function(){
			
			// LAYER
			var selLogo = '.bottomlogo';
			
			var logo = window.getElements(selLogo) ;
			
            logo.bind('click', function(e){
                e.preventDefault() ;
                
            }) ;
            
		}
	}
}


//  PROJECTS
var ProjectHandler = function(){
	// TODO 
	// here checks to target only project-concerned pages
		// i.-e project, and private project
	var scope = {
		init:function(condition){
			scope.enable();
            
            if(condition == false && window.wasAlreadyClicked == false) scope.infos.addClass('reduced');
            
            
            return scope ;
		},
		enable:function(cond){
            // PLAYBACK
            var selPlayback = '.playback'
			scope.playback = $(selPlayback) ;
            // INFOS PANEL
            var selInfos = '.infos', selClose = '.closebtn', selH1 = 'h1'; 
			scope.infos = $(selInfos) ;
            scope.close = $(selInfos+' '+selClose) ;
			scope.h1 = $(selInfos+' '+selH1) ;
            // MORE INFOS PANEL
			var selMoreInfosPanel = '.moreinfo', selMore = '.moreinfosbtn';
            scope.moreinfospanel = $(selMoreInfosPanel) ;
            scope.more = $(selInfos+' '+selMore) ;
			scope.moreinfosclose = $(selMoreInfosPanel+' '+selClose) ;
            // DETAILS PANEL
			var selDetailsPanel = '.details', selDetailsBtn = '.detail';
            scope.detailsPanel = $(selDetailsPanel) ;
			scope.detailsBtn = $(selDetailsBtn) ;
			scope.detailsclose = $(selDetailsPanel+' '+selClose) ;
            
            var bindClosure = (cond == false)? "unbind" : "bind" ;
            
            if(Boolean(scope.infos[0])) {
                scope.close[bindClosure]('click', scope.toggleInfos) ;
                scope.h1[bindClosure]('click', scope.toggleInfos) ;
            }
            if(Boolean(scope.moreinfospanel[0])) {
                scope.more[bindClosure]('click', scope.toggleMoreInfos) ;
                scope.moreinfosclose[bindClosure]('click', scope.toggleMoreInfos) ;
            }
            
            if(Boolean(scope.detailsPanel[0])) {
                scope.detailsBtn[bindClosure]('click', scope.toggleDetail) ;
                scope.detailsclose[bindClosure]('click', scope.toggleDetail) ;
            }
		},
        toggleInfos:function(e){
            window.wasAlreadyClicked = true ;
            if(e) e.preventDefault() ;
            scope.infos.toggleClass('reduced') ;
            window.scrollResize() ;
        },
        toggleMoreInfos:function(e){
            if(e) e.preventDefault() ;
            if(scope.detailsOpened) scope.toggleDetail() ;
            scope.togglePlaybackControls() ;
			scope.moreinfospanel.toggleClass('hidden') ;
        },
        toggleDetail:function(e){
            if(e) e.preventDefault() ;
            if(window.slideshow){
                if(!window.slideshow.paused){
                    window.slideshow.togglePB() ;
                    window.slideshow.paused = true ;
                } 
            }
            scope.togglePlaybackControls() ;
            var opened  = scope.detailsPanel.hasClass('hidden') ;
			scope.detailsPanel.toggleClass('hidden') ;
            scope.detailsOpened = opened ;
        },
        togglePlaybackControls:function(){
            scope.playback.toggleClass('dispNone') ;
        },
        destroy:function(){
            if(scope.detailsOpened) scope.toggleDetail() ;
            scope.enable(false);
            
            scope.playback =
            scope.infos =
            scope.close =
            scope.h1 =
            scope.moreinfospanel =
            scope.more =
            scope.moreinfosclose =
            scope.detailsPanel =
            scope.detailsBtn =
            scope.detailsclose =
            null ;
            
            delete scope.playback ;
            delete scope.infos ;
            delete scope.close ;
            delete scope.h1 ;
            delete scope.moreinfospanel ;
            delete scope.more ;
            delete scope.moreinfosclose ;
            delete scope.detailsPanel ;
            delete scope.detailsBtn ;
            delete scope.detailsclose ;
            
        }
	}
	return scope ;
}


// TOPMENU HANDLING
var MenuHandler = function(){ 
    //
	return {
		init:function(){
			this.initLayer();
		},
		initLayer:function(){
			// LAYER
			var selLayer = '.layer';
			var selTopMenu = '.topmenu ul';
			var selTopMenuDrop = '.topmenu .drop';
			var layer = window.getElements(selLayer) ;
			var topmenu = window.getElements(selTopMenu) ;
			var topmenudrop = window.getElements(selTopMenuDrop) ;
			var opened = false ;
			function toggleLayer(e){
                var state = e instanceof String ? e : e.type ;
				if(state == 'mouseover') {
                    layer.removeClass('dispNone') ;
                    topmenudrop.removeClass('dispNone') ;
                    topmenu.parent().css('z-index', '600') ;
                    layer.css('z-index', '600') ;
                    opened = true ;
                }else{
                    layer.addClass('dispNone') ;
                    topmenudrop.addClass('dispNone') ;
                    topmenu.parent().css('z-index', '300') ;
                    layer.css('z-index', '250') ;
                    opened = false ;
                }
			}
			function click(e){
                if(opened){
                    toggleLayer('mouseout') ;
                }
			}
            
			topmenu.mouseover(toggleLayer) ;
			topmenu.mouseout(toggleLayer) ;
            topmenu.click(click) ;
		}
	}
}




// SCROLLERS

var Scroller = function(container, axis, steps){
    
    var min = axis == 'x' ? 'scrollLeft' : 'scrollTop' ;
    var client = axis == 'x' ? 'clientX' : 'clientY' ;
    
    var scope = {
        init:function(){
            container.css('overflow', 'hidden') ;
            
            scope.scrollTop = 0 ;
            scope.downed = false ;
            // here events
            
            scope.divarrows = $('#hiding .scrollarrows').clone().appendTo((container.parent().hasClass('rightpanel') || container.parent().hasClass('welcome'))? container.parent() : container) ;
            scope.up = scope.divarrows.children('.tomin') ;
            scope.down = scope.divarrows.children('.tomax') ;
            container.css({
                'cursor' : 'default'
            }) ;
            
            scope.enable() ;
            return scope ;
        },
        mousedown:function (e) {
            if(e){
                e.preventDefault() ;
                var arr0 = [] ;
                var arr1 = [] ;
                
                var locName = e.currentTarget? e.currentTarget.nodeName : e.originalEvent.originalTarget.nodeName ;
                if(locName == 'A') return ;
            }
            scope.downed = true ;
            scope.indY = e[client];
            scope.scrollTop = this[min] ;
            $(window).bind('mousemove', scope.mousemove) ;
        },
        mouseup:function(e){
            $(window).unbind('mousemove', scope.mousemove) ;
            scope.downed = false ;
        },
        mousewheel:function(e){
            scope.scroll(e.delta, 0, 30, false) ;
        },
        mousemove:function(e){
            if (scope.downed == true){
                var n = scope.scrollTop + scope.indY - e[client] ;
                if(n < 0 ) {
                    n = 0 ;
                    container[0][min] = n + 100 ;
                }
                container[0][min] = n ;
            }
        },
        upclick:function(e){
            scope.scrollunit = (steps)?
                    $(steps).height() : 150 ;
            (axis == 'x') ?
            scope.scroll(1, 250, scope.scrollunit , steps) :
            scope.scroll(1, 250, scope.scrollunit , steps) ;
        },
        downclick:function(e){
            scope.scrollunit = (steps)?
                    $(steps).height() : 150 ;
            (axis == 'x') ?
            scope.scroll(-1, 250, scope.scrollunit , steps) :
            scope.scroll(-1, 250, scope.scrollunit , steps) ;
        },
        winmouseout:function (e) {
            if (scope.downed) {
                try {
                    if (e.target.nodeName == 'BODY'
                        || e.target.nodeName == 'HTML') {
                        scope.downed = false;
                    }     
                } catch (e) {}
            }
        },
        enable:function(cond){
            if(cond == false){
                scope.up.unbind('click', scope.upclick);
                scope.down.unbind('click', scope.downclick);
                container.unbind('mousedown', scope.mousedown).unbind('mouseup', scope.mouseup).unbind('wheel', scope.mousewheel) ;
                $(window).unbind('mouseout', scope.winmouseout);
            }else{
                $(window).bind('mouseout', scope.winmouseout);
                container.bind('mousedown', scope.mousedown).bind('mouseup', scope.mouseup).bind('wheel', scope.mousewheel) ;
                scope.up.bind('click', scope.upclick);
                scope.down.bind('click', scope.downclick);
            }
        },
        scroll:function(delta, time, stepdistance, stepped){
            if(delta == 0){
                return container[0][min] = 0 ;
            }
            time = time || 0 ;
            var o = {} ;
            o[min] =  (delta < 1) ?
                container[0][min] +  stepdistance :
                container[0][min] - stepdistance ;
            if(stepped && time !=0) {
                if(delta > 0){ // scrolling up
                    o[min] = Math.ceil((o[min]/stepdistance)) * stepdistance ;
                }else{// scrolling down
                     o[min] =  Math.floor((o[min]/stepdistance)) * stepdistance ;
                }
            }
            time > 0 ?
                (function(){
                    scope.enable(false) ;
                    $(container).animate(o, "fast", function(){
                        setTimeout(scope.enable, 10, true) ;
                    }) ;
                               
                })() :
            container[0][min] = o[min] ;
        },
        destroy:function(){
            
            if(scope.divarrows) scope.divarrows.remove() ;
            
            axis = null ;
            steps = null ;
            min = null ;
            client = null ;
            
            scope.enable(false) ;
            
            scope.divarrows =
            scope.scrollTop =
            scope.scrollunit =
            scope.indY =
            scope.downed =
            scope.up =
            scope.down =
            scope.mousedown =
            scope.mouseup =
            scope.mousewheel =
            scope.mousemove =
            scope.upclick =
            scope.downclick =
            scope.winmouseout =
            null ;
            
            
            delete scope.divarrows ;
            delete scope.scrollTop ;
            delete scope.scrollunit ;
            delete scope.indY ;
            delete scope.downed ;
            delete scope.up ;
            delete scope.down ;
            delete scope.mousedown ;
            delete scope.mouseup ;
            delete scope.mousewheel ;
            delete scope.mousemove ;
            delete scope.upclick ;
            delete scope.downclick ;
            delete scope.winmouseout ;
        }
    }
    return scope.init() ;
}

var ScrollHandler = function(){
    var scrollers = [] ;
    var scope = {
        init:function(){
            $('.scrollable').each(function(){
                if($(this).hasOverflow('y')){
                    scrollers.push(new Scroller($(this), 'y', $(this).hasClass('projectContainer') ? '.blockproject' : null) ) ;
                }else{
                    
                }
            }) ;
            return scope ;
        },
        reset:function(){
            var l = scrollers.length ;
            while(l--){
                scrollers.pop().destroy() ;
            }
            scrollers = null ;
            return this ;
        },
        destroy:function(){
            scope.reset() ;
            return null ;
        }
    } ;
    return scope.init() ;
}

/* END OF JS FILE */

