var IE7 = $.browser.msie && parseInt($.browser.version, 10) == 7;

// Réinitialisation du captcha
function resetCaptcha(){
	$('#captcha').attr( 'src', REL_PATH + 'img/captcha/captcha.php?r=' + (new Date().getTime()) );
}

/**
 *
 * @param form jQuery form element
 * @param captcha jQuery captcha input element
 * @param wait String waiting message during captcha check
 * @param alert String alert message when captcha is wrong
 * @param url String AJAX URL to check captcha
 */
function submitWithCaptcha(form, captcha, wait, alert, url) {

    form.bind('submit.captcha',function(event) {

        event.preventDefault();
        event.stopImmediatePropagation();

        if (form.validationEngine('validate')) {

            captcha.validationEngine(
                'showPrompt',
                wait,
                'load',
                'topRight',
                true
            );

            $.post(
                url,
                // POST data
                {
                    fieldId:    captcha.attr('id'),
                    fieldValue:    captcha.val()
                },
                // callback
                function(data) {
                    if (data[1]) {
                        form.unbind('submit.captcha');
                        form.submit();
                    } else {
                        setTimeout(function() {
                            captcha.validationEngine(
                                'showPrompt',
                                alert,
                                'red',
                                'topRight',
                                true
                            );
                            captcha.select();
                            resetCaptcha();
                        }, 500);
                    }
                },
                "json"
            );
        } else {
            //console.log('invalid');
        }

        return false;
    });
}

// Positionnement du menu principal
function centerMainMenu() {
	var menuWidth = 0;
	var nbrMenu = $('#gMainMenu > ul li > a').size();
	var menuItemWidth = 0;
	var menuItemWidthRest = 950;
	
	$('#gMainMenu > ul li > a').each(function() { menuWidth = menuWidth + $(this).innerWidth(); });
	menuItemWidth = Math.floor((950 - menuWidth) / nbrMenu);
	
	$('#gMainMenu > ul li > a').each(function() {
		$(this).css('width', ($(this).width() + menuItemWidth) + 'px');
		menuItemWidthRest = menuItemWidthRest - $(this).innerWidth();
	});
	
	$('#gMainMenu > ul li > a:eq(' + (nbrMenu - 1) + ')').css('width', ($('#gMainMenu > ul li > a:eq(' + (nbrMenu - 1) + ')').width() + menuItemWidthRest - 1) + 'px');
	$('#gMainMenu > ul li > a').fadeTo(0, 0).css('display', 'block').fadeTo(750, 1);
}


// Centrer les liens pour le slideshow de l'accueil
function centerSlideshowThumb() {
	var nbrThumbs = $('.info_slide_dots span').size();
	var thumbsWidth = (nbrThumbs * $('.info_slide_dots span:eq(0)').width()) + ((nbrThumbs - 1) * parseInt($('.info_slide_dots span:eq(1)').css('margin-left')));
	$('.info_slide_dots span:eq(0)').css('margin-left', Math.round(($('.info_slide_dots').width() - thumbsWidth) / 2) + 'px');
	$('.info_slide_dots span').show();
        //.fadeTo(0, 0)
        //.css('display', 'block')
        //.fadeTo(500, 1)
}



// Égaliser la hauteur des sous-menus
function equalizeSubmenusHeight() {
	$('.gSubmenu').each(function() {
		var submenuHeight = 0;
		
		$('a', this).each(function() {
			if ($(this).height() > submenuHeight) { submenuHeight = $(this).height(); }
		});
		
		$('a', this).css('height', submenuHeight + 'px');
	});
}

/**
 * share global options for colorbox calls
 * @param Object|undefined obj
 */
function colorboxOptions(obj){
    return $.extend({
        scrolling: false,
        fixed: IE7 ? false : true,
        maxWidth: $(window).width(),
        maxHeight: $(window).height()
    }, obj || {});
}

$(document).ready(function() {

    // pour les popups de Matissoft
    $('.pop').colorbox(colorboxOptions());

    // zoom pour les images plein écran de meunerie soltions (les images maps)
    $('.mZoom').colorbox(colorboxOptions());

    // rendre ouvrable dans une nouvelle fenêtre les images des popups ci-haut
    $(document).bind('cbox_complete', function () {
        $('img.cboxPhoto').wrap(function(){
            return '<a target="_blank" href="' + $(this).attr('src') + '" />';
        });
    });

    $('.gOpenCloseContainer, .gOpenCloseForm').children().plusMoins({
        onOpen: function (event) {
            $(this).find('.gOpenCloseContent').stop(true, true).slideDown();
        },
        onClose: function (event) {
            $(this).find('.gOpenCloseContent').stop(true, true).slideUp();
        },
        onDestroy: function (event) {
            $(this).find('.gOpenCloseContent').stop(true, true).show();
        }
    });
	
	
	// Égalisation de toutes les boîtes de solutions
	var minSolHeight = 0;
	
	$('.gSolutionsContainer .gText').each(function() {
		if ($(this).height() > minSolHeight) { minSolHeight = $(this).height(); }
	});
	
	$('.gSolutionsContainer .gText').css('height', minSolHeight + 'px');
});

$(window).load(function() {
	centerMainMenu();
	equalizeSubmenusHeight();
	
	// Clic sur le bouton de réinitialisation du captcah
	$('#gBtnRefresh').click(resetCaptcha);
	
	
	// Clic sur les liens (div) des sidebox
	$('.gSideBoxLink, .gSideBoxTextLink, .gSideBoxTextColorLink').click(function() {
		document.location.href = $(this).find('a').attr('href');
	});
	
	
	// Rollover des icônes sociaux
	$('#gSocialLinks img').hover(function() {
		$('#gSocialLinks img').addClass('unselected');
		$(this).removeClass('unselected').addClass('selected');
		$('#gSocialLinks img.unselected').clearQueue().fadeTo(350, 0.3);
		$('#gSocialLinks img.selected').clearQueue().fadeTo(350, 1);
	}, function() {
		$('#gSocialLinks img.unselected').clearQueue().fadeTo(350, 1);
		$('#gSocialLinks img').removeClass('selected').addClass('unselected');
	});
	
	
	// Rollover du menu principal
	$('#gMainMenu img').animate({ opacity: 0, delay: 0 }).css('display', 'block');
	
	$('#gMainMenu > ul li > a, #gMainMenu > ul li .gSubmenu').hover(function() {
		posx = Math.round($(this).parents('li').find('a').position().left + ($(this).parents('li').find('a').innerWidth() / 2) - ($('#gMainMenu img').width() / 2));
		posxd = Math.round($(this).parents('li').find('a').position().left);
		
		/*if (IE7) {
			posxd = posxd + 949;
			posx = posx + 949;
		}*/
		
		$('#gMainMenu #gMainMenuArrow').clearQueue().animate({ left: posx, opacity: 1 }, 500);
		$('#gMainMenu #gMainMenuDegrade').clearQueue().animate({ width: $(this).parents('li').find('a').innerWidth(), height: 92, left: posxd, opacity: 1 }, 500);
	}, function() {
		$('#gMainMenu img').clearQueue().animate({ opacity: 0 }, 500);
	});
	
	
	// Affichage des sous-menus du menu principal
	$('#gMainMenu > ul li a, #gMainMenu > ul li .gSubmenu').hover(function() {
		submenuHeight = $(this).parent('li').find('.gSubmenu .gSubmenuTitle').innerHeight() + $(this).parent('li').find('.gSubmenu .gSubmenuLinks').innerHeight();
		$(this).parent('li').find('.gSubmenu').clearQueue().animate({ height: submenuHeight });
	}, function() {
		$(this).parent('li').find('.gSubmenu').clearQueue().animate({ height: 0 });
	});

    $('#gNewsTitlesLinksContainer .gNewsTitleLink').each(function() {
        var img = $(this).find('img')[0];
        var on = img.src.replace(/-pale/, '');
        var off = img.src;
        new Image().src = on;
        $(this).hover(
            function() {
                img.src = on;
            },
            function() {
                img.src = off;
            }
        )
    });
	
	
	// Clic sur le titre de la nouvelle dans la liste des nouvelles et clic sur les secteurs de l'entreprise de la section contact
	$('#gNewsTitlesLinksContainer .gNewsTitleLink').click(function() {
		document.location.href = $('a', this).attr('href');
	});
	
	
	$('.gEnvelopeTitleLink').click(function() {
		clickedEQ = $('.gEnvelopeTitleLink').index(this);
		$('#selDepartment option').attr('selected', '');
		$('#selDepartment option:eq(' + (clickedEQ + 1) + ')').attr('selected', 'selected');
		document.location.hash = 'information';
		$('#information').trigger('plusmoinsopen');
	});

	// Agrandissement de l'image du background
	$.supersized({
		vertical_center : 0,
		slides : [
			{ image : REL_PATH + 'img/' + DIVISION + '/common/background.jpg' }
		]
	});

});
