var isIE6 = false;
(function() {
    function pauseflash(p){
        var flash = document.getElementById('flashContentScreenHome');
        if(flash){
            if(p == 'pause' && flash.pauseVideo){
                flash.pauseVideo();
            } else if(p == 'unpause' && flash.unPauseVideo){
                flash.unPauseVideo();
            }
        }
    }
    
    box.bind({
        'addtodom.popin':function() {
            pauseflash('pause');
        },
        'addtodom.popin.generic.staf':function(){
            initStaf();
        },
        'addtodom.popin.generic.team':function(){
            box.ui('scroll').configure({
                bar: '<a href="#" class="{$barCls}"><div><span class="start"></span><span class="end"></span></div></a>'
            });
            box.ui('scroll').create({
                id: 'teamscroll',
                element: '.popinCore',
                buttons: false,
                bar: true
            });
        },
        'addtodom.popin.generic.technical':function(){
            box.ui('scroll').configure({
                bar: '<a href="#" class="{$barCls}"><div><span class="start"></span><span class="end"></span></div></a>'
            });
            box.ui('scroll').create({
                id: 'technicalscroll',
                element: '.scroll',
                buttons: false,
                bar: true
            });
        },
        'removefromdom.popin':function(){
            pauseflash('unpause');
        },
        'beforeclose.popin.generic.staf':function(e){
            box.ui('form').destroy('sendToAfriendForm');
        },
        'removefromdom.popin.generic.team':function(){
            box.ui('scroll').destroy('teamscroll');
        },
        'removefromdom.popin.generic.technical':function(){
            box.ui('scroll').destroy('technicalscroll');
        }
    });
    
    var initStaf = function() {
    box.ui('form').create({
        element: '#sendToAfriendForm'
    }).mustValidate(function(form) {
        
        form.field('firstName').mustValidate(function(field) {
            if(field.isEmpty()) {
                return l10n.errors.form;
            }
        });
        
        form.field('lastName').mustValidate(function(field) {
            if(field.isEmpty()) {
                return l10n.errors.form;
            }
        });
        
        form.field('lastName').mustValidate(function(field) {
            if(field.isEmpty()) {
                return l10n.errors.form;
            }
        });
        
        form.field('email').mustValidate(function(field) {
            if(field.isEmpty()) {
                return l10n.errors.required.email;
            } else if(!field.isMatching('email')) {
                return l10n.errors.invalid.email;
            }
        });

        form.field('firstNameFriend').mustValidate(function(field) {
            if(field.isEmpty()) {
                return l10n.errors.form;
            }
        });
        
        form.field('lastNameFriend').mustValidate(function(field) {
            if(field.isEmpty()) {
                return l10n.errors.form;
            }
        });
        
        form.field('emailFriend').mustValidate(function(field) {
            if(field.isEmpty()) {
                return l10n.errors.required.email;
            } else if(!field.isMatching('email')) {
                return l10n.errors.invalid.email;
            }
        });
            
        return l10n.errors.form;
    });
};
	
	var errorCls = 'error';
    
	var getErrorTarget = function(field) {
		if('radio' != field.type) {
			return field.getLabel();
		} else {
			return field.getElements();
		}
	};
	
	var addFieldError = function(e) {
		getErrorTarget(e.source).parent().addClass(errorCls);
	};
	
	var removeFieldError = function(e) {
		getErrorTarget(e.source).parent().removeClass(errorCls);
	};
	
	var addFormError = function(e) {
	    
		var id = e.source.id + 'Error';
		var msg = '<p>' + e.source.msg + '</p>';
		var error = box.dom('#' + id);
		if(error.length) {
			error.html(msg);
		} else {
			e.source.getElement().prepend('<div id="' + id + '" class="' + errorCls + '">' + msg + '</div>');
		}
	};
	
	var removeFormError = function(e) {
		box.dom('#' + e.source.id + 'Error').remove();
	};
        
    // binding des événements
    box.bind({
        'submit.form.sendToAfriendForm': function(e, domEvent) {
            if(e.valid === true) {
                removeFormError(e);
                if(domEvent) {
                    domEvent.preventDefault();
                    $.ajax({
                        type:$('#sendToAfriendForm').attr('method'),
                        url:$('#sendToAfriendForm').attr('action'),
                        dataType:'html',
                        data: $('#sendToAfriendForm').serialize(),
                        beforeSend: function(){
                            $('#sendToAfriendForm #submit').addClass('loading');
                        },
                        error: function(){
                            // erreur post
                        },                        
                        success: function(response){
                            // success
                            var r = $(response);
                            $('#sendToAfriendForm').css('display','none');
                            $('#sendToAfriendForm #submit').removeClass('loading');
                            r.appendTo('#popinStaf .popinCore');
                            r.find('.taf').click(function(){
                                r.remove();
                                $('#firstNameFriend, #lastNameFriend, #emailFriend').val('');
                                $('#sendToAfriendForm').css('display','block');
                                return false;
                            });
                        }
                     });
                 }
            } else if(e.valid === false) {
                addFormError(e);
            }
        },
        'error.field': addFieldError,
        'valid.field': removeFieldError
    });
    
    var popup = {
        init:function(){
            $('.popup').click(function(){
                 window.open($(this).attr('href'),"popupPrivacy","menubar=no, status=no, scrollbars=yes, menubar=no, width=320, height=320");
                 return false;
            });
        }
    };
    
    
    //retirer le masque et attribuer l'image de fond à l'écran
    var loadManager = {
        init:function(obj,screenbg){
            $(obj).addClass('bgImg').prependTo('#'+screenbg);          
            if($(document).width() > $(obj).width()) {
                if(isIE6){
                    var leftPos = $(document).width()/2 - $(obj).width()/2;
                } else {
                var leftPos = 0;
                }
            } else {
                var leftPos = $(document).width()/2 - $(obj).width()/2;
            }
            $(obj).css({
                left: leftPos+'px'
            });
            $('#'+screenbg+' .screenMask').fadeOut('1000');
            $('#'+screenbg).addClass('js');
            
        }
    }
    
    
    // animation du scroll système
    var animScroll = {
        init:function(){
            if(window.location.href.indexOf('#') > -1 && window.location.href.split('#')[1] != ''){
                $('#navigation ul li a[href='+window.location.hash+']').addClass('on');
                animScroll.doit(window.location.hash);
            }
            $('#tagLogo').click(function(){
                $('#navigation ul li a').removeClass('on');
                animScroll.doit();
                return false;
            });
            $('#navigation ul li a').each(function(){
                $(this).click(function(){
                    var that = this;
                    $('#navigation ul li a').removeClass('on');
                    $(that).addClass('on');
                    animScroll.doit($(that).attr('href'));
                    return false;
                });
            });
        },
        doit:function(h){
            var toElem = (h) ? $(h).offset().top : 0;
            $('html').stop().animate({
                scrollTop: toElem
            }, 1000, function(){
                if(h){
                    if(window.location.href.length == window.location.href.indexOf('#')+1){
                        window.location.href = window.location.href.replace('#',h);
                    } else {
                        if(window.location.href.indexOf('#') > -1){
                            window.location.href = window.location.href.replace(window.location.href.split('#')[1],h.split('#')[1]);
                        } else {
                            window.location.href = window.location.href + h;
                        }
                    }
                } else {
                    if(window.location.href.length != window.location.href.indexOf('#')+1){
                        window.location.href = window.location.href.split('#')[0] + '#';
                    }
                }
            });
        }
    };

    var videoPlayer = function(){
        var params = {
            wmode: "transparent",
            menu: false,
            allowFullScreen: true
        };        
        var flashvars = {
            configXML: "/xml/config.xml"
        };    
        swfobject.embedSWF("/swf/application.swf", "flashContentScreenHome", "959", "358", "9.0.0", "/swf/expressInstall.swf", flashvars, params);
    }
    
    box.dom(document).ready(function() {        

        
        var imgScreen01 = new Image();        
        var screenId01 = 'screenHome';
        imgScreen01.onload = function(){
            loadManager.init(this,screenId01);            
        }   
        imgScreen01.src = '/img/screen-home.jpg';
        
        
        var imgScreen02 = new Image();
        var screenId02 = 'the-odyssey-of-pioneers';
        imgScreen02.onload = function(){
            loadManager.init(this,screenId02);
        }  
        imgScreen02.src = '/img/screen-odissey.jpg';
        
        var imgScreen03 = new Image();
        var screenId03 = 'the-exhibition';
        imgScreen03.onload = function(){
            loadManager.init(this,screenId03);
        }
        imgScreen03.src = '/img/screen-exhibition.jpg';
          
        var imgScreen04 = new Image();
        var screenId04 = 'tesla-motors';
        imgScreen04.onload = function(){
            loadManager.init(this,screenId04);
        }  
        imgScreen04.src = '/img/screen-tesla.jpg';

        var imgScreen05 = new Image();
        var screenId05 = 'the-journey';
        imgScreen05.onload = function(){
            loadManager.init(this,screenId05);
        }  
        imgScreen05.src = '/img/screen-journey.jpg';

        
        
         
        // create a mask for popins
        box.ui('mask').create({
            id: 'generic',
            
            html: '<div id="popinMask"></div>',
            insertStyles: {opacity: 0, width: 'viewport:content-box', height: 'document:content-box'},
            insertAnimStyles: {opacity: 0.9},
            insertAnimDuration: 200,
            removeAnimStyles: {opacity: 0},
            removeAnimDuration: 150,
            resizeStyles: {width: 'viewport:content-box', height: 'document:content-box'}
        });
        
        // create a loader for popins
        box.ui('loader').create({
            id: 'generic',
            
            html: '<div id="popinLoader">' + l10n.loading + '</div>',
            insertStyles: {opacity: 0, top: 'viewport:middle', left: 'viewport:middle'},
            insertAnimStyles: {opacity: 1},
            insertAnimDuration: 200,
            removeAnimStyles: {opacity: 0},
            removeAnimDuration: 150
        });
        
        // create a new popin object
        box.ui('popin').create({
            id: 'generic',
            
            loader: 'generic',
            mask: 'generic',
            
            insertStyles: {top: 'viewport:before', left: 'viewport:middle', 'min-left': 0},
            insertAnimStyles: {top: 'viewport:middle', 'min-top': 0},
            insertAnimDuration: 600,
            removeAnimStyles: {top: 'viewport:before'},
            removeAnimDuration: 500,
            
            openClassName: 'popinOpen',
            closeClassName: 'popinClose'
        });
        
        popup.init();
        animScroll.init();
        videoPlayer(); 
        
        
        
       
    // tooltip map
    if ($('.tooltip').length) {
        $('.tooltip').each(function(){
            var thisClass = $(this).attr('class');
            var thisId = $(this).attr('id');
            $(this).removeClass();
            $(this).addClass(thisClass);
        });
        
        box.ui('plugin.tooltip').create({
            reactArea : '#raceMap',
            element: '.tooltip'
        });
                
    // faux scroll    
        box.ui('scroll').configure({
            id: 'odyssey',
            bar: '<a href="#" class="{$barCls}"></a>',
            btnNext: '<a class="next"></a>',
            btnPrev: '<a class="prev"></a>'
        });
        box.ui('scroll').create({
            id: 'odyssey',
            element: '.scrollableOdyssey',
            buttons: true,
            bar: true
        });
        box.ui('scroll').configure({
            id: 'exhibition',
            bar: '<a href="#" class="{$barCls}"></a>',
            btnNext: '<a class="next"></a>',
            btnPrev: '<a class="prev"></a>'
        });
        box.ui('scroll').create({
            id: 'exhibition',
            element: '.scrollableExhibition',
            buttons: true,
            bar: true
        });
        box.ui('scroll').configure({
            id: 'tesla',
            bar: '<a href="#" class="{$barCls}"></a>',
            btnNext: '<a class="next"></a>',
            btnPrev: '<a class="prev"></a>'
        });
        box.ui('scroll').create({
            id: 'tesla',
            element: '.scrollableTesla',
            buttons: true,
            bar: true
        });        
    }  
        
    });
})();
