/* ============================== Gestion des transitions ============================== */
/* Function transition ()
 * @param : type ('cube' => cube flip)
 * @param : going_forward (true, false)
 * @param : html (string) : content of the page
 * @param : fond (string, false) : Background image of the new page, the string represents the value of the css class
 * @param : jump1 (integer, false) : Horizontal Jump before transition in pixels
 * @param : jump2 (integer, false) : Horizontal Jump after transtion in pixels
 */
function transition(type, going_forward, html, fond, jump1, jump2) {
	if (!transitions_in_progress) { // Vérification qu'il n'y à pas de transition déjà en cours
		if (jump1) { executeJump(jump1); } //Repositionne le scroll avant la transition
		transitions_in_progress = true; // mark that a transition is now in progress
		createPage(idlePageId, html, fond, going_forward);
		switch(type) {
			case 'Cube':
			Cube(type, going_forward, html, fond, jump2);
			break;
		}
	}
}
var oldPage;
var newPage;
var pages_container;
function Cube(type, going_forward, html, fond, jump){
	var duration = '1s';
	// Création de la nouvelle page

	pages_container = $('pages_container');
	
	oldPage = $('page_'+activePageId);
	var oldStyle = oldPage.style;
	
	newPage = $('page_'+idlePageId);
	var newStyle = newPage.style;
	
	oldStyle.zIndex = 0;
	var containerWidth = pages_container.offsetWidth + 'px';
	oldStyle.width = containerWidth;
	oldStyle.top = '0px';
	
	if (context.areTransformsSupported) {
		oldStyle.webkitTransitionProperty = 'none'; // disable
	    // This also makes sure that we start with an identity matrix to avoid initial performance problem
	    oldStyle.webkitTransform = translateOp(0, 0);
	    oldStyle.webkitBackfaceVisibility = '';
	} else {
		oldStyle.display = 'none';
	}
	
	// Make sure that container is constraining the transitions for overflow content
    pages_container.style.overflow = 'hidden';
    pages_container.style.position = 'relative';
    
    if (context.areTransformsSupported) {
    	// Reset
        newStyle.webkitTransitionProperty = 'none'; // disable
        // This also makes sure that we start with an identity matrix to avoid initial performance problem
        newStyle.webkitTransform = translateOp(0, 0);
        newStyle.webkitBackfaceVisibility = '';
        
        // This overcomes a clipping problem
        pages_container.parentNode.style.zIndex = 0;
    }
    //newStyle.width = null;
    newStyle.width = containerWidth;
    newStyle.position = 'relative';
    newStyle.display = 'block';
    
    //pages_container.style.height = Math.max(oldPage.offsetHeight, newPage.offsetHeight) + 'px';
    
    if (context.areTransformsSupported) {
    	oldStyle.position = 'absolute';
		pages_container.style.webkitPerspective = '800';
	    oldStyle.webkitBackfaceVisibility = 'hidden';
	    oldStyle.webkitTransformOrigin = going_forward ? '100% 50%' : '0% 50%';
	    newStyle.webkitBackfaceVisibility = 'hidden';
	    newStyle.webkitTransformOrigin = going_forward ? '0% 50%' : '100% 50%';
	    
	    var factor = going_forward ? 1 : -1;
	    var dimension = parseInt(containerWidth);
	    
	    newStyle.webkitTransitionProperty = 'none'; // disable
	    newStyle.webkitTransform = rotateOp('Y', factor*90) + ' translateZ(' + dimension + 'px)';
	    
	    addDelayedTransitionCallback(function() {
	            setupTransition(oldStyle, '-webkit-transform', duration, 'ease-in-out', 'webkitTransform', rotateOp('Y', factor*-90) + ' translateZ(' + dimension + 'px)');
	            setupTransition(newStyle, '-webkit-transform', duration, 'ease-in-out', 'webkitTransform', 'rotateY(0deg) translateZ(0px)');
	        });
	        
	    // Register a callback for the end of the animation for clean up and/or resets
	    oldPage.addEventListener('webkitTransitionEnd', transitionEnded, false);
    } else {
    	transitionEnded();
    }
}

function transitionEnded(event) {
	if (transitions_in_progress) {
	    oldPage.style.display = 'none';
	    newPage.style.zIndex = 1;
	    
	    resizeContainerHeight();
        
        pages_container.style.webkitPerspective = '';
        oldPage.style.webkitTransformOrigin = '';
        newPage.style.webkitTransformOrigin = '';
        
        oldPageId = activePageId;
		activePageId = idlePageId;
		idlePageId++;
		clearPage(oldPageId, true);
		setTimeout(function () { executeDivJavascript('page_'+activePageId, context.browser == 'firefox', false); }, 300);
		transitions_in_progress = action_in_progress = false;
    }
}

// Accumulate transitions that will be executed after a 0 delay
function addDelayedTransitionCallback(callback) {
    //if (!delayedCallbacks) {
        delayedCallbacks = new Array();
        var performDelayedCallbacks = function () {
            var length = delayedCallbacks.length;
            for (var f=0; f<length; f++) {
                delayedCallbacks[f]();
            }
            delete delayedCallbacks;
        }
        setTimeout(performDelayedCallbacks, 0);
    //}
    delayedCallbacks.push(callback);
}

function setupTransition(style, property, duration, timing, propertyString, propertyValue) {
    style.webkitTransitionProperty = property;
    style.webkitTransitionDuration = duration;
    style.webkitTransitionTimingFunction = timing;
    style[propertyString] = propertyValue;
}

/* Gestion des onglets */

var durationFlip = '0.65s';
var checkedForEnded;
var tabNumber;
var oldTab;
var newTab;
var tabs_container;
var oldViewAnimationName;
var newViewAnimationName;
var miniHidden = false;
function switchTab(number) {
	//alert('switch number : '+number+'- activeTab : '+context.activeTab+' - posterVisible: '+context.posterVisible);
	tabNumber = number;
	var fromRight = true;
	if (arguments.length==2) {
		var fromRight = false;
	}
	if (tabNumber != context.activeTab) {
		context.posterVisible = false;
		if (number === 0) {
			context.posterVisible = true;
			$('petiteImg').style.display = 'none';
			addClassName($('coverImg'), 'coverVisible');
			miniHidden = true;
		} else if (miniHidden) {
			$('petiteImg').style.display = 'block';
			removeClassName ($('coverImg'), 'coverVisible');
			miniHidden = false;
		}
		context.oldTab = context.activeTab
		checkedForEnded = false;
		tabs_container = $("tabs_container");
		tabs_container.style.width = '100%';
	    newTab = $("tab_"+tabNumber);
	    var newStyle = newTab.style;
	    oldTab = $("tab_"+context.activeTab);
	    var oldStyle = oldTab.style;
	    // Reset some settings
	    oldStyle.zIndex = 0;
        
        // This is especially important for reverse since the original value of 'top' is 'auto', which for a view lower in the document flow means that it will come after the newly restored view. Hence, let's set it to a right value before newView is put to 'relative' again.
        oldStyle.top = '0px';
        
        if (context.areTransformsSupported) { // Vérification que ce type de transition est bien supporté
		    oldStyle.webkitTransitionProperty = 'none'; // disable
		    // This also makes sure that we start with an identity matrix to avoid initial performance problem
		    oldStyle.webkitTransform = translateOp(0, 0);
		    oldStyle.webkitBackfaceVisibility = '';
        } else {
        	oldStyle.display = 'none';
        }
	    // Make sure that container is constraining the transitions for overflow content
    	tabs_container.style.overflow = 'hidden';
    	
    	var computedStyle = document.defaultView.getComputedStyle(tabs_container, null);
	    if ((computedStyle.getPropertyValue('position') != 'absolute') && (computedStyle.getPropertyValue('position') != 'relative')) {
	        // Assume 'static' since we don't support 'fixed'. 'relative' is less obtrusive then.
	       tabs_container.style.position = 'relative';
	    }
	    if (context.areTransformsSupported) { // Vérification que ce type de transition est bien supporté
		    //Reset
		    newStyle.webkitTransitionProperty = 'none'; // disable
	    	// This also makes sure that we start with an identity matrix to avoid initial performance problem
	    	newStyle.webkitTransform = translateOp(0, 0);
	    	newStyle.webkitBackfaceVisibility = '';
	    	
	    	// This overcomes a clipping problem
	        tabs_container.parentNode.style.zIndex = 0;
	    } else {
	    	var i=1;
			while($('tb_'+i)) {
				if (tabNumber === 0) {
					if (i === 1) {
						addClassName($('tb_'+i), 'selected');
					} else {
						removeClassName($('tb_'+i), 'selected');
					}
				} else {
					if(i === tabNumber){
						addClassName($('tb_'+i), 'selected');
					} else {
						removeClassName($('tb_'+i), 'selected');
					}
				}
				i++;
			}
	    }
        // Before the new view comes in, remove any previously hard-coded inline value that would have crept in when it was transited out. Because the transition is happening in a container and we are reinstating the position to be 'relative', the new view will resize itself to react to orientation changes (if any).
       
        newStyle.width = null;
    	newStyle.position = 'relative';
    	newStyle.display = 'block';
    	if (context.areTransformsSupported) { // Vérification que ce type de transition est bien supporté
	    	// If the new view is too short to fit the whole view port height, this will even show the Safari toolbar before the transition happens
		    oldStyle.position = 'absolute';
		    
		    //Dynamic container to make flip smoother
		    tabs = $("tabs");
		    
		    // Workaround an animation perspective problem
		    tabs_container.removeChild(tabs);
	        tabs_container.appendChild(tabs);
		    
		    // Tag it
		    tabs.setAttribute('apple-transition-flip-push-container', 'true');
		    // Spec says that overflow:hidden and preserve-3d don't mix.
		    tabs.setAttribute('style', 'position: relative; top: 0; left: 0; overflow: visible; z-index: 0; -webkit-transform-style: preserve-3d;');
		    
		    oldStyle.webkitAnimationDuration = durationFlip;
		    oldStyle.webkitAnimationTimingFunction = 'ease-in-out';
		    oldViewAnimationName = fromRight ? 'dashcode-transition-flip-right-old-view' : 'dashcode-transition-flip-left-old-view';
		    addClassName(oldTab, oldViewAnimationName);
		    
		    newStyle.webkitAnimationDuration = durationFlip;
		    newStyle.webkitAnimationTimingFunction = 'ease-in-out';
		    newViewAnimationName = fromRight ? 'dashcode-transition-flip-right-new-view' : 'dashcode-transition-flip-left-new-view';
		    addClassName(newTab, newViewAnimationName);
		    
			tabs.style.webkitAnimationDuration = durationFlip
		    tabs.style.webkitAnimationTimingFunction = 'ease-in-out';
		    addClassName(tabs, 'dashcode-transition-flip-container-pushback');
		    tabs_container.style.webkitAnimationDuration = durationFlip
		    tabs_container.style.webkitAnimationTimingFunction = 'ease-in-out';
		    addClassName(tabs_container, 'dashcode-transition-flip-container');   
		
		    // Register a callback for the end of the animation for clean up
		    tabs_container.addEventListener('webkitAnimationEnd', animationEnded, false);
    	} else {
    		// Preload des images
			if (tabNumber > 0) { 
				eval("preloadImages(images"+tabNumber+", '"+tabNumber+"ip', 0);"); 
			}
    	}
    	context.activeTab = tabNumber;
    	// Bidouille pour récupérer le nom de l'onglet actif en fonction du numéro de la page et du numéro de l'onglet
    	if (context.pagePath == 'ChoixFilm') {
			if (context.activeTab == 1) {
				context.tab = 'affiche';
			} else if (context.activeTab === 2) {
				context.tab = 'nouveau';
			} else {
				context.tab = 'preferes';
			}
		} else if (context.pagePath == 'ProfilFilm') {
			if (context.activeTab == 1) {
				context.tab = 'infos';
			} else if (context.activeTab === 2) { 
				context.tab = 'seances';
			} else {
				context.tab = 'avis';
			}
		} else if (context.pagePath == 'ProfilSalle') {
			if (context.activeTab == 1) {
				context.tab = 'lieu';
			} else  { 
				context.tab = 'infos';
			}
		}
	}
}

// Callback for end of animation
function animationEnded(event) {
	if (!checkedForEnded) {
		oldTab.style.display = 'none';
		newTab.style.zIndex = 1;
		resizeContainerHeight();
		removeClassName(oldTab, oldViewAnimationName);
		removeClassName(newTab, newViewAnimationName);
		removeClassName(tabs_container, 'dashcode-transition-flip-container');
		checkedForEnded = true;
		var i=1;
		while($('tb_'+i)) {
			if (tabNumber === 0) {
				if (i === 1) {
					addClassName($('tb_'+i), 'selected');
				} else {
					removeClassName($('tb_'+i), 'selected');
				}
			} else {
				if(i === tabNumber){
					addClassName($('tb_'+i), 'selected');
				} else {
					removeClassName($('tb_'+i), 'selected');
				}
			}
			if (i>10) break;
			i++;
		}
		// Preload des images
		if (tabNumber > 0) {
			eval("preloadImages(images"+tabNumber+", '"+tabNumber+"ip', 0);"); 
		}
		// Au besoin : chargement de la publicité
		if (tabNumber>1) {
			// Vérification que la publicité n'a pas déjà été chargéé pour l'onglet courant :
			if ($('AutourPubOrange'+context.tab).innerHTML == '') {
				// Création de l'url de pub
				var qsp = { 'pagePath' : 'PubliciteOrange',
						'reste' : '_'+context.uid,
						'noqs' : true };
				var urlPub = getUrl(qsp);
				
	    		var marqueur = '280080157428'; // Marqueur estat
	    		var master = '230030157427'; // Marqueur master estat
	    		var niveau1 = 'IPCFRA'; // Charte + Langue
	    		var niveau2 = 'PAR'; // Paris est la ville par défaut
	    		var niveau3 = 'CIN'; // Thème
	    		
	    		if (context.pagePath == 'ChoixFilm') {
					if (context.activeTab == 1) { //A l'affiche
						var niveau4 = 'ACinap'+context.pagePath;
					} else if (context.activeTab === 2) { // nouveau
						var niveau4 = 'NCinap'+context.pagePath;
					} else { // préférés
						var niveau4 = 'PCinap'+context.pagePath;
					}
				} else if (context.pagePath == 'ProfilFilm') {
					var niveau4 = 'E'+extractCodeResteFromReste(context.reste);
				} else if (context.pagePath == 'ProfilSalle') {
					var niveau4 = 'L'+extractCodeResteFromReste(context.reste);// PagePath
				}
				// Récupération de la publicité et appel au script estat pour notifier de la page vue
	    		getPubAndEstat(urlPub, 'AutourPubOrange'+context.tab, tabNumber, marqueur, master, niveau1, niveau2, niveau3, niveau4)
			} // Sinon : la pub est déja chargée pour cet onglet
		}
	}
}

function switchPoster() {
	if (!context.posterVisible) {
		switchTab(0);
	} else {
		if (!context.oldTab) { context.oldTab = 1; }
		switchTab(context.oldTab);
	}
}

function hidePoster() {
	if (context.posterVisible) {
		switchPoster();
	}
}

function translateOp(xPixels, yPixels) {
    return 'translate(' + xPixels + 'px, ' + yPixels + 'px)';
}

function rotateOp(axis, degree) {
    return 'rotate' + axis + '(' + degree + 'deg)';
}