// JavaScript Document
$(document).ready(function () {

    // Call specific functions to each page
    switch (getUrlVarsFrom(document.location.href, true)['tabid']) {
    case undefined:
        initSlideshowHome();
        break;
    case '5':
        initSwitchList();
        initToggleObject();
        break;
	case '6':
        initFancyBox();
		initOpacity();
		initSlideOpacity();
        break;
	case '9':
        initFormatText();
		initPrettyPhoto();
        break;
    case '24':
        initSlidePublications();
		initPrettyPhoto2();
        break;
	case '28':
        initInspirationSlide();
        break;
	case '46':
		initExhibitions();
		initToggleObject();
		break;
	case '47':
		initExhibitionToggle();
		initToggleObject();
		initPrettyPhoto();
		break;

    }
    initSubMenu();
    initSlideshowHome();
	
	jQuery.event.add(window, "load", screenResize);
	jQuery.event.add(window, "resize", screenResize);
	
});
function getUrlVarsFrom(url, preventUnwantedVars) {
    var vars = [],
        hash;
    var hashes = url.split('#')[0].slice(url.indexOf('?') + 1).split('&');
    for (var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        if (preventUnwantedVars == 1) {
            if (hash[0] != 'lg' && hash[0] != 'objectid' && hash[0] != 'tabindex' && hash[0] != 'page' && hash[0] != 'keyword' && hash[0] != 'mediaid' && hash[0] != 'testmode') {
                if (hash[0] == 'categoryid' && hash[1] == 0) {} else {
                    vars.push(hash[0]);
                    vars[hash[0]] = hash[1];
                }
            }
        } else {
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
    }
    return vars;
}
function screenResize() {
	
	var h = $(window).height();
    var w = $(window).width();
    $("#background-slide").css({ 'width' : (w < 800) ? '250%': '100%', 'margin-left' : (w < 800) ? '-450px' : 0 });
	
	
	}
function initExhibitionToggle() {
	
	$('.object-list').css('display', 'none');
	
	$('.bn-view-selected').click(function(){
		$('.description-object').hide();
		$('.object-list').show();
		
	});
	$('.bn-close').click(function(){
		$('.object-list').hide();
		$('.description-object').show();
		return false;
		
	});
			
	if (getUrlVarsFrom(document.location.href, false)['page'] != undefined){
		$('.description-object').hide();
		$('.object-list').show();
	}
}
function initFormatText() {
	
	$("strong").replaceWith(function() { return $(this).contents(); });
	
	}
function initSubMenu() {

    $('.menu-trigger').mouseover(function () {
        $(this).parent().parent().parent().find('.sub-menu').slideDown('fast').show();

        $('.sub-menu').hover(function () {}, function () {
            $(this).slideUp('slow').hide('slow'); //When the mouse hovers out of the subnav, move it back up  
        });

    });
	
	$('.menu-trigger-events').mouseover(function () {
        $(this).parent().parent().parent().find('.sub-menu-events').slideDown('fast').show();

        $('.sub-menu-events').hover(function () {}, function () {
            $(this).slideUp('slow').hide('slow'); //When the mouse hovers out of the subnav, move it back up  
        });

    })
	$('.previous img').attr("src","../media/mohtashemimedia/images/button-previous.png");
	$('.next img').attr("src","../media/mohtashemimedia/images/button-next.png");
}

function slideSwitch() {
    var $active = $('.slideshow div.active');

    if ($active.length == 0) $active = $('.slideshow div:last');

    // use this to pull the images in the order they appear in the markup
    var $next = $active.next().length ? $active.next() : $('.slideshow div:first');

    $active.addClass('last-active');

    $next.css({
        opacity: 0.0
    }).addClass('active')
    //.animate({opacity: 1.0}, 1500, function() {
    .animate({
        opacity: 1.0
    }, 1000, function () {
        $active.removeClass('active last-active');
    });
}

function initSlideshowHome() {

    setInterval("slideSwitch()", 7500);

}

function initSwitchList() {

    $('table.objectListTable td').each(function (index, domEle) {

        $('ul.object-list').append('<li />');
        $('div.object', domEle).appendTo('ul.object-list li:last');

    })

}

function initToggleObject() {

    $('.object').each(function (index, domEle) {

        $(domEle).hover(function () {

            $(domEle).children('.area-text').fadeIn('fast');

        }, function () {

            $(domEle).children('.area-text').fadeOut('slow');

        })

    });
}

function initSlidePublications() {

    var retour = true;
    var tempsTransition = 1000;
    var affichePlayPause = false;
    var lectureAutomatique = false;
    var tempsAttente = 12000;

    var icones = new Array();
    icones['play'] = 'img/play_slider.png';
    icones['pause'] = 'img/pause_slider.png';

    var currentPosition = 0;
    var slideWidth = 880;
    var slides = $('.slide');
    var numberOfSlides = slides.length;
    var interval;
    var lectureEnCours = false;
	
	
    
    // Supprime la scrollbar en JS
    $('.slidesContainer').css('overflow', 'hidden');

    // Attribue  #slideInner  à toutes les div .slide
    slides.wrapAll('<div id="slideInner"></div>')
    // Float left to display horizontally, readjust .slides width
    .css({
        'float': 'left',
        'width': slideWidth
    });

    // Longueur de #slideInner égale au total de la longueur de tous les slides
    $('#slideInner').css('width', slideWidth * numberOfSlides);

    // Insert controls in the DOM
    $('.slideshow').prepend('<span class="control" id="leftControl">Précédent</span>').append('<span class="control" id="rightControl">Suivant</span>');


    //Crée un écouteur d'évènement de type clic sur les classes .control
    $('.control').bind('click', function () {

        // Determine la nouvelle position
        currentPosition = ($(this).attr('id') == 'rightControl') ? currentPosition + 1 : currentPosition - 1;

        if (currentPosition == numberOfSlides && retour == false) {
            currentPosition--;
            pause();
        }

        // Cache ou montre les controles
        manageControls(currentPosition);
        // Fais bouger le slide
        $('#slideInner').animate({
            'marginLeft': slideWidth * (-currentPosition)
        }, tempsTransition);
    });

    // manageControls: Cache ou montre les flêches de controle en fonction de la position courante


    function manageControls(position) {
        // Cache la fleche "précédent" si on est sur le premier slide
        if (position == 0) {
            $('.slideshow #leftControl').hide();
        } else {
            $('.slideshow #leftControl').show()
        }
        // Cache la fleche "suivant" si on est sur le dernier slide (et que le retour automatique n'est pas activé)
        if (position == numberOfSlides - 1 && retour == false) {
            $('.slideshow #rightControl').hide();
        } else {
            $('.slideshow #rightControl').show();
        }
        if (position == numberOfSlides && retour == true) {
            currentPosition = 0;
            $('.slideshow #leftControl').hide();
        }
    }
	// Hide left arrow control on first load
    manageControls(currentPosition);

    function suivant() {
        $('#rightControl').click();
    }

    function start() {
        lectureEnCours = true;
        interval = setInterval(suivant, tempsAttente);
    }

    function pause() {
        lectureEnCours = false;
        clearInterval(interval);
    }

    //Si le diapo est activé 
    if (lectureAutomatique == true) {
        start();
    }
    if (affichePlayPause == true) {
        $('.slidesContainer').prepend('<img id="navDiapo" src="" alt="Navigation diaporama" />');
        if (lectureAutomatique == true) {
            $('#navDiapo').attr('src', icones['pause']);
        } else {
            $('#navDiapo').attr('src', icones['play']);
        }
        $('#navDiapo').bind('click', function () {
            if (lectureEnCours == true) {
                $(this).attr('src', icones['play']);
                pause();
            } else {
                $(this).attr('src', icones['pause']);
                start();
            }
        });
    }
}
function initFancyBox() {
	
	 $(".zoom-object").fancybox({
	         'width': '60%',
			 'height': '80%',
	         'autoScale' : true,
	         'transitionIn' : 'none',
	         'transitionOut' : 'none',
	         'type' : 'inline',
			 'scrolling' : 'no'
			 
	     });
	 $(".contact-us").fancybox({
	         'width' : 600,
	         'height' : '75%',
	         'autoScale' : false,
	         'transitionIn' : 'none',
	         'transitionOut' : 'none',
	         'type' : 'iframe',
			 'scrolling' : 'no'
	     });
	 
	     
	
	}
function initPrettyPhoto() {
	
	$("a[rel^='prettyPhoto']").prettyPhoto({
		default_width:  flashW,
			default_height:  flashH,
		flash_markup: flashMarkup
		});
	
	
}
function initPrettyPhoto2() {

	$("a[rel^='prettyPhoto']").prettyPhoto();
	
}
function initInspirationSlide() {
	
	//Configuration
	var retour = true;
	var tempsTransition = 1000;
	var affichePlayPause = false;
	var lectureAutomatique = false;
	var tempsAttente = 10000;

	var icones = new Array();
	icones['play'] = 'img/play_slider.png';
	icones['pause'] = 'img/pause_slider.png';

	var currentPosition = 0;
	var slideWidth = 978;
	var slides = $('.slide');
	var numberOfSlides = slides.length;
	var interval;
	var lectureEnCours = false;
	// Supprime la scrollbar en JS
	$('.slidesContainer').css('overflow-x', 'hidden');

	// Attribue  #slideInner  à toutes les div .slide
	slides.wrapAll('<div id="slideInner"></div>')
	// Float left to display horizontally, readjust .slides width
	.css({
		'float': 'left',
		'width': slideWidth
	});

	// Longueur de #slideInner égale au total de la longueur de tous les slides
	$('#slideInner').css('width', slideWidth * numberOfSlides);

	// Insert controls in the DOM
	$('.liens').append('<span class="control" id="leftControl">Précédent</span>').append('<span class="control" id="rightControl">Suivant</span>');
	$('.text-area').prepend('<div class="position"></div>');


	// Hide left arrow control on first load
	manageControls(currentPosition);

	//Crée un écouteur d'évènement de type clic sur les classes .control
	$('.control').bind('click', function () {

		// Determine la nouvelle position
		currentPosition = ($(this).attr('id') == 'rightControl') ? currentPosition + 1 : currentPosition - 1;

		if (currentPosition == numberOfSlides && retour == false) {
			currentPosition--;
			pause();
		}

		// Cache ou montre les controles
		manageControls(currentPosition);
		// Fais bouger le slide
		$('#slideInner').animate({
			'marginLeft': slideWidth * (-currentPosition)
		}, tempsTransition);
		var imgPosition = currentPosition + 1
		$(".position").html(imgPosition+ '/' +(i-1))
		
	});
	// créer les liens 
	for (var i = 1; i <= numberOfSlides; i++) {
		$('.liens').append('<a class="number" rel="' + i + '">' + i + '</a>');
		
	}
	
	$('a.number').click(function () {
		
		var image = $(this).attr('rel');
		var animation = image * 978 - 978;
			
		$("#slideInner").animate({
			
			'marginLeft': -animation
		
		});
		
 		$(".position").html(image + '/'+(i-1))

	});
	$('#slideInner .slide').each(function(index) {
		
		$(this).attr('rel', index)

	});

	// manageControls: Cache ou montre les flêches de controle en fonction de la position courante
	function manageControls(position) {
		// Cache la fleche "précédent" si on est sur le premier slide
		if (position == 0) {
			$('#leftControl').hide()
		} else {
			$('#leftControl').hide()
		}
		// Cache la fleche "suivant" si on est sur le dernier slide (et que le retour automatique n'est pas activé)
		if (position == numberOfSlides - 1 && retour == false) {
			$('#rightControl').hide();
		} else {
			$('#rightControl').show();
		}
		if (position == numberOfSlides && retour == true) {
			currentPosition = 0;
			$('#leftControl').hide();
		}
	}

	function precedent() {
		$('#leftControl').click();
		
	}

	function suivant() {
		$('#rightControl').click();
		
	}

	function start() {
		lectureEnCours = true;
		interval = setInterval(suivant, tempsAttente);
	}

	function pause() {
		lectureEnCours = false;
		clearInterval(interval);
	}

	//Si le diapo est activé 
	if (lectureAutomatique == true) {
		start();
	}
	if (affichePlayPause == true) {
		$('.slidesContainer').prepend('<img id="navDiapo" src="" alt="Navigation diaporama" />');
		if (lectureAutomatique == true) {
			$('#navDiapo').attr('src', icones['pause']);
		} else {
			$('#navDiapo').attr('src', icones['play']);
		}
		$('#navDiapo').bind('click', function () {
			if (lectureEnCours == true) {
				$(this).attr('src', icones['play']);
				pause();
			} else {
				$(this).attr('src', icones['pause']);
				start();
			}
		});
	}

	$('.control').css('display', 'none');

	$(document).keydown(function (e) {

		var code = e.keyCode ? e.keyCode : e.which;

		if (code == 37)

		{
			
			precedent();
			
			if (currentPosition < 0) {
				$('#slideInner').animate({
					'marginLeft': 0
				}, tempsTransition);
				pause();
			}

		} else if (code == 39)

		{

			suivant();
			if (currentPosition == numberOfSlides && retour == false) {
				currentPosition--;
				pause();
			}

		}
	});
	
}
function initOpacity() {
	
	$('.additional-image img').animate({'opacity' : 0.3}).hover(function() {  
        $(this).animate({'opacity' : 1});  
    }, function() {  
        $(this).animate({'opacity' : 0.3});  
    });  
	
}
function initSlideOpacity() {
	
	$('.slideshow').animate({'opacity' : 0.1});
	
	}
function initExhibitions() {
	
	var exhibition = getUrlVarsFrom(document.location.href, true)['exhibition'];
	
	if (exhibition == 'current') {
		
		$('.container-forthcoming').remove();
		$('.container-past').remove();
		
		}
	if (exhibition == 'past') {
		
		$('.container-forthcoming').remove();
		$('.container-current').remove();
		
		}
	if (exhibition == 'forthcoming') {
		
		$('.container-current').remove();
		$('.container-past').remove();
		
		}
		
}

