/******************************************  START - DOM ready events  ****************************************/
$(function() {   



	//mainWindowImgStretcher = $(window);   //background image of el partido that covers the entire browser window at all times.
	//mainWindowImgStretcher.bind("resize", resizeBg).trigger("resize");   
	
	//langImages=new Array();
	
	//startpreload();
	
	$(".sub-links").mouseleave(function(){
		$(this).hide();
	});
		
	$("a.main-link, #search-text").mouseenter(function(){
		$("a.main-link").removeClass("active");												 
		$(this).addClass("active");										 
		$(".sub-links").hide();
		$(this).siblings(".sub-links").fadeIn();
	});

	/*$('.sub-links').mouseout(function() {
	  $(".sub-links").hide();
	});
*/

	
	
	ddd = $("#masterfilms-carousel").CloudCarousel( { 
		reflHeight: 56,
		reflGap:2,
		titleBox: $('#masterfilms-title'),
		altBox: $('#masterfilms-alt'),
		xRadius:300,				
		yRadius:70,
		xPos: 470,
		yPos: 150,
		FPS:30,
		autoRotate: 'left',		
		autoRotateDelay: 3000,
		speed:0.15,
		mouseWheel:true,
		bringToFront:true	
	});	
	
	var d = ddd.find('img');
	d.each(function(i, obj){
		$(obj).error(function(){
			$(this).attr('src','/img/image_missing.jpg');
		});
	});
	
	
	$('.ajax-call').click(function(e) { e.preventDefault(); openLinkInAjax(e); });   // for mention legales
	
	
	var searchInput = $('#searchinput');
    searchInput.keyup(function(event) {
        if (event.keyCode == 13) {
        	searchInput.form().submit();
        }
    });
	
	prepareVidClip();



	categorymenu = $("#accordion");
	if ( categorymenu.length ) {		
		categorymenu.parent().css({'visibility':'visible'});
		categorymenu.accordion({
			active: true,
			autoHeight: false,
			navigation: true
		});
	}
	
	
	setContactForm();

	/*createcssmenu();*/


	
});	
/******************************************  END - DOM ready events  ******************************************/

var menuids=new Array("verticalmenu01") //Enter id(s) of UL menus, separated by commas
var submenuoffset=-2 //Offset of submenus from main menu. Default is -2 pixels.

function createcssmenu(){
	for (var i=0; i<menuids.length; i++){
	  var ultags=document.getElementById(menuids[i]).getElementsByTagName("ul")
		for (var t=0; t<ultags.length; t++){
		var spanref=document.createElement("span")
			spanref.className="arrowdiv"
			spanref.innerHTML="&nbsp;&nbsp;"
			ultags[t].parentNode.getElementsByTagName("a")[0].appendChild(spanref)
		ultags[t].parentNode.onmouseover=function(){
		this.getElementsByTagName("ul")[0].style.left=this.parentNode.offsetWidth+submenuoffset+"px"
		this.getElementsByTagName("ul")[0].style.display="block"
		}
		ultags[t].parentNode.onmouseout=function(){
		this.getElementsByTagName("ul")[0].style.display="none"
		}
		}
	  }
}

////////////////////////////////////////////////////////////////////////////



///////////////////////////////////////////////////////////////////////////


function updateVidPlayer(videopath, playme) {
	
	if ((navigator.userAgent.match(/iPhone/i) != null) || (navigator.userAgent.match(/iPad/i) != null) || (navigator.userAgent.match(/iPod/i) != null)) {
	
		if (typeof masterfilmVidPlayer === 'undefined') {
			masterfilmVidPlayer  = jwplayer("player1");		
		}
    	var vidname = videopath.split(/(\.[^.]*$|$)/);
		if (vidname[1] == '.m4v') {
	  		videopath = { file: '/img/categories_videos/' + videopath }; 
		} else {
	  		videopath = { file: '/img/categories_videos/' + videopath }; 		
		}
	} else {

			if (typeof masterfilmVidPlayer === 'undefined') {
				masterfilmVidPlayer  = jwplayer("player1");		
			}
	    	var vidname = videopath.split(/(\.[^.]*$|$)/);
			if (vidname[1] == '.flv' || vidname[1] == '.m4v') {
		  		videopath = { file: videopath, streamer: 'rtmp://master.fms3.zonepro.com/videos/', provider: 'rtmp', bufferlength: 3, volume: 90 }; 
			} else {
		  		videopath = { file: videopath, streamer: 'rtmp://master.fms3.zonepro.com/videos/', provider: 'rtmp', bufferlength: 3, volume: 90 }; 		
			}
		}
	
	masterfilmVidPlayer.load(videopath);
	if (playme) masterfilmVidPlayer.play(true);
}


function setCategoryMenu(catIndex, subIndex) {
	var subMapArry = [0,0,0,0,0,0,1,0,1,2,3,4,0,1,2,0,1,2,3];
	categorymenu.accordion( "activate" , --catIndex );
	var a = $('.ui-accordion-content-active:eq(0) a:eq('+ subMapArry[subIndex] +')');
	a.addClass('current');
}

function setVidGalleryFocus(vidIndex) {
		gallery.gotoIndex(--vidIndex);
}


function setVerticalGreenBar(cssClassName) {
		$('.vid-player-green-bg:eq(0)').addClass(cssClassName);
}


function setContactForm() {
	var r = $('#contactForm');
	if (r.length) {	
		$.validator.setDefaults({
			//submitHandler: function() { alert("submitted!"); }
			submitHandler: function() { r.submit(); }
		});

		// validate signup form on keyup and submit
		r.validate({
			rules: {
				firstname: {
					required: true,
					minlength: 2
				},
				lastname: {
					required: true,
					minlength: 2
				},
				company: {
					required: true
				},			
				email: {
					required: true,
					email: true
				},
				commentary: {
					required: true,
					minlength: 2
				},
			},
			messages: {
				firstname: {
					required: "S'il vous plaît saisir votre nom",
					minlength: "Votre nom doit être composé d'au moins 2 caractères"
				},
				lastname: {
					required: "S'il vous plaît entrer votre prénom",
					minlength: "Votre prénom doit être composé d'au moins 2 caractères"
				},
				company: {
					required: "S'il vous plaît entrez votre société"
				},			
				email: "S'il vous plaît entrer une adresse email valide",
				commentary: {
					required: "S'il vous plaît entrer vos commentaires",
					minlength: "Vos commentaires doivent comporter au moins 2 caractères"
				},
			}
		});

	
	}
}

function vidLabelOnHover() {
	var r = $('.thumbnails-container ul.thumbs li');	
	
	vidlabelHover = $('#video-label-hover');		
	if (r.length) {	
		  r.mouseenter(function(){
				$.doTimeout( 'hover', 250, function(elem){
					var img = $(elem).children(":first");
					var s = '';
					if (img.attr('annonceur') != "") {
						s  = '<span class="categorylabels-title">Annonceur :</span><span class="categorylabels-desc">' + img.attr('annonceur') + '</span>';
						s += '<span class="categorylabels-title">Agence :</span><span class="categorylabels-desc">' + img.attr('agence') + '</span>';
					} else {
						s  = '<span class="categorylabels-title">Client :</span><span class="categorylabels-desc">' + img.attr('client') + '</span>';						
						s += '<span class="categorylabels-title">Titre :</span><span class="categorylabels-desc">' + img.attr('titre') + '</span>';						
					}					
					
					if ( jQuery.trim(s) == '') s = '&nbsp;';
					vidlabelHover.hide().html(s).fadeIn('fast');		
				}, this);
		  })
		  .mouseleave(function(){
			vidlabelHover.fadeOut('fast');
			$.doTimeout( 'hover' );
		  });
	}
	
}


function updateVidAssoc(atag) {
	deleteAllVidAssoc();
	addVidAssoc(atag);		
}


function deleteAllVidAssoc(atag) {
	$('#thumbs-assoc-loader').css({'display':'block'});	
	var x = $('#thumbs-assoc');
	if ( x.length == 1 ) {
		if (typeof galleryAssoc == 'object') {
			galleryAssoc.remove();
			delete galleryAssoc;
		}
		x.remove();
	}
	if (typeof thumbsAssocContainer == 'undefined') {
		thumbsAssocContainer = $('#thumbs-assoc-container');			
	}
	thumbsAssocContainer.append('<div id="thumbs-assoc" class="navigation"> <a class="pageLink prev" style="visibility: hidden;" href="#" title="Page précédente"></a> <ul class="thumbs noscript"> <li> <a class="thumb" href="#"> <img src="/img/thumb-filler.gif" /> </a> </li> </ul> <a class="pageLink next" style="visibility: hidden;" href="#" title="Page Suivante"></a> <div class="clearfix"></div> </div>');		
	
	galleryAssoc = $('#thumbs-assoc').galleriffic({
		delay:                     500,
		numThumbs:                 14,
		enableTopPager:            false,
		enableBottomPager:         false,
		imageContainerSel:         '#slideshow2',
		loadingContainerSel:       '#loading2',
		renderSSControls:          false,
		renderNavControls:         false,
		enableHistory:             false,
		autoStart:                 false,
		syncTransitions:           false,
		enableKeyboardNavigation:  false,
		defaultTransitionDuration: 100,
		onSlideChange:             function(prevIndex, nextIndex) {
			// 'this' refers to the gallery, which is an extension of $('#thumbs')
			this.find('ul.thumbs').children()
				.eq(prevIndex).fadeTo('fast', 0.35).end()
				.eq(nextIndex).fadeTo('fast', 1.0);

		},
		onPageTransitionOut:       function(callback) {
			this.fadeTo('fast', 0.0, callback);
		},
		onPageTransitionIn:        function() {
			var prevPageLink = this.find('a.prev').css('visibility', 'hidden');
			var nextPageLink = this.find('a.next').css('visibility', 'hidden');
			// Show appropriate next / prev page links
			if (this.displayedPage > 0 )
				prevPageLink.css('visibility', 'visible');

			var lastPage = this.getNumPages() - 1;
			if (this.displayedPage < lastPage)
				nextPageLink.css('visibility', 'visible');

			this.fadeTo('fast', 1.0);
		},
		clickHandler: function(e, link) {
			e.preventDefault();
			var a = $(link);
			a.attr('href','javascript:void(0)');
			a.addClass('vid-assoc-loading');
			a.children(":first").css({'opacity': '0'});				
			a.parent().unbind();
			if (a.attr('itemid')){
				if ( a.attr('itemid') != ''){
					
					window.location= '/galerie/goto_video/' + a.attr('itemid');
					return false;
				}
			} else {
				alert('thumbnail dont have any itemid attribute i dont know where to go.');
			}
		}
	});


	galleryAssoc.find('a.prev').click(function(e) {
		galleryAssoc.previousPage();
		e.preventDefault();
	});

	galleryAssoc.find('a.next').click(function(e) {
		galleryAssoc.nextPage();
		e.preventDefault();
	});	

	
}

function addVidAssoc(atag) {
	var a = $(atag), itemID = a.attr('itemID');
	if (itemID) {
	  $.getJSON("/galerie/getrelatedvideos/" + itemID, function(data) {
		if (typeof data == 'object' && data.success) {
			$.doTimeout( 'martinee', 600, function(){
				if ( galleryAssoc.data.length > 0) {
					galleryAssoc.removeImageByIndex(galleryAssoc.data.length--);								
				}
				$.each(data.related_videos, function(key, val) {
				  var titlenumber = key;
				  if ($.trim(val.thumbnail) == '') val.thumbnail = 'thumb-image-missing.jpg';
				  galleryAssoc.insertImage('<li><a class="thumb" href="javascript:void(0)" title="Vidéo #' + (++titlenumber) + '\"  client=\"' + val.client + '\" titre=\"' + val.title + '\" annonceur=\"' + val.annonceur + '\" agence=\"' + val.agence + '\"  itemID=\"' + val.video_id + '\"><img src="/img/categories_videos/thumbs/' + val.thumbnail + '\" width="69px" height="53px" /></a><div class="caption"></div></li>', key);
				});
				y = galleryAssoc.data.length;
				if (typeof checkIfVidAssocItemsFullyDisplayed  == 'number') {
						clearInterval(checkIfVidAssocItemsFullyDisplayed);
						delete checkIfVidAssocItemsFullyDisplayed;
						$('#thumbs-assoc-loader').css({'display':'none'});
				}
				checkIfVidAssocItemsFullyDisplayed = setInterval(function() {
					var x = $('#thumbs-assoc ul.thumbs li').length;
					if (x > y) {
						$('#thumbs-assoc ul.thumbs li, div.navigation a.pageLink').opacityrollover({
							mouseOutOpacity:   0.35, 
							mouseOverOpacity:  1.0,
							fadeSpeed:         'fast', 
							exemptionSelector: '.selected'
						});
						vidLabelOnHover();
						clearInterval(checkIfVidAssocItemsFullyDisplayed);
						delete checkIfVidAssocItemsFullyDisplayed;
						$('#thumbs-assoc-loader').css({'display':'none'});				
					} 
				}, 500);	
				
				
			}, true);			 
			 
		
		} else {
			alert('what the %^&%, there something wrong with the JSON.');
			return false;
		}
	  })
	} else {
		galleryAssoc.removeImageByIndex(0);				
		$('#thumbs-assoc-loader').css({'display':'none'});						
	}
	
}

function openLinkInAjax(e) {
	e.preventDefault();
	var linkObj = $(e.target);
	$.lightbox( linkObj.attr('href'),{
			'width'      : 720,
			'height'     : 550,
			'modal'      : 1,
			'method'     : 'POST',			
			'autoresize' : true				  
		}	  
	);
}


function prepareVidClip() {
	var r =  $('#masterfilms-carousel img[name]');
	if (r.length) {
		var c = $('.vid-container:eq(0)');
		r.each(function(){
			var vidname = this.name.split(/(\.[^.]*$|$)/);
			var width = 398;
			var height = 257;			
			var imagename = this.name;
			var imgNewId = vidname[0];
			var newHTML = '';
			
			if (vidname[1] == '.flv' || vidname[1] == '.m4v') {
				var browser=navigator.appName;
				var b_version=navigator.appVersion;
				var version=parseFloat(b_version);
				
				extra1 = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0" width="'+width+'" height="'+height+'">';
				extra2 = '</object>';
				
				temp = 	'<div style="width:'+width+'px;height:'+height+'">'+extra1+'<embed'
				+'		src="/img/player.swf"'
				+'		width="'+width+'"'
				+'		height="'+height+'"'
				+'		allowscriptaccess="never"'
				+'		allowfullscreen="false"'
				+'		flashvars=autostart=true&repeat=true&height='+height+'&width='+width+'&file=/img/'+imagename+'&searchbar=false&showicons=false&shownavigation=false&showdigits=false&usefullscreen=false&wmode=opaque'
				+'		/>'+extra2+'</div>';
		
				newHTML = newHTML + '<div id="'+ imgNewId +'" class="vid-clips">';
				newHTML = newHTML += temp;
				newHTML = newHTML + '</div>';
			} else {
				temp = 	'<img src="/img/categories_videos/gif/'+ this.name +'" width="318" height="204" onerror="javascript:loaddefimages(this);" >';
		
				newHTML = newHTML + '<div id="'+ imgNewId +'" class="vid-clips">';
				newHTML = newHTML += temp;
				newHTML = newHTML + '</div>';
			}
			c.append(newHTML);							

		});
		
	}

}


function loaddefimages(obj) { 
	$(obj).attr('src','/img/image_missing.jpg');
}    


function resizeBg() {
	if (typeof $bg == 'undefined') {
		  $bg = $("#bg-img-stretcher");
		  $aspectRatio = null;
	} 				
	aspectRatio      = $bg.width() / $bg.height();				
	if ( (mainWindowImgStretcher.width() / mainWindowImgStretcher.height()) < aspectRatio ) {
		$bg
			.removeClass()
			.addClass('bg-img-stretcher-height');
	} else {
		$bg
			.removeClass()
			.addClass('bg-img-stretcher-width');
	}
				
}	


//      check if carousel is fully loaded.
//		xxxx = 1;
//		checkCarouselIsLoaded = setInterval(function() {
//			if (document.getElementsByClassName('reflection').length >= 1) {
//				console.log('loaded');
//				clearInterval(checkCarouselIsLoaded);			  
//			} else {
//				console.log(xxxx++);	  
//			}
//		}, 100);	


