jQuery.noConflict();

var slider = '';

function adjustRoundedImages() {
	jQuery(".oms-rounded-image").each(function(){
		$this = jQuery(this);
		$this.css("width", $this.find("img").width());
		if ($this.find("img").hasClass('allWidth')) {
			$this.css("width", "100%");
			$this.find(".om-inner").css("width", "100%");
		}
	});
}

jQuery(window).load(function($) {
	adjustRoundedImages();
});

jQuery(document).ready(function($) {	

	testLoad = 0;
	
	function iframe(){
		
		if (jQuery(".pb-tab-box").length != 0) {
		
			jQuery(".pb-tabcontent.pb-hide").addClass("pb-show");
			var iFrames = jQuery('.pb-tabcontent iframe');
			
			function iResize(){
				for (var i = 0, j = iFrames.length; i < j; i++) {
					iFrames[i].style.height = iFrames[i].contentWindow.document.body.offsetHeight + 'px';
				}
				jQuery(".pb-tabcontent.pb-hide").removeClass("pb-show");
			}
			
			if (jQuery.browser.safari || jQuery.browser.opera) {
				iFrames.load(function(){
					setTimeout(iResize, 0);
				});
				
				for (var i = 0, j = iFrames.length; i < j; i++) {
					var iSource = iFrames[i].src;
					iFrames[i].src = '';
					iFrames[i].src = iSource;
				}
			}
			else {
				iFrames.load(function(){
					if (this.contentWindow.document.body.offsetHeight != 0) {
						this.style.height = this.contentWindow.document.body.offsetHeight + 'px';
					} else {
						testLoad+=1;
						if (testLoad<20) {
							iframe();
						}
					}
					jQuery(".pb-tabcontent.pb-hide").removeClass("pb-show");
				});
			}
		
		}
		
	}
	
	$( ".js-datepicker" ).datepicker({
		onChangeMonthYear: function(year, month, inst) {
			Calendar.requestEventsByMonth(year, month);
		},
		beforeShowDay: function(date) {
			
			var dateId = $.datepicker.formatDate('dd-mm-yy', date);
			var count = $('.pf-calendar-grid .pf-event[date="' + dateId + '"]').length;
			var enabled = count > 0;
			var css = '';

			return [enabled, null, null];
		},
		onSelect: function(dateText, inst) {
			var date = new Date(inst.selectedYear, inst.selectedMonth, inst.selectedDay);
			Calendar.showEventsByDate(date);
			/* Adjust Iframe for Events */
			if ($(this).parents(".pb-profileFrame").length!=0) {
				var transHeight = $(this).parents(".pb-profileFrame").height();
				if (transHeight >= $('.iframe:visible', window.parent.document).height()) {
					$('.iframe:visible', window.parent.document).height(transHeight);
				}
			}
		}

	});	
	
	//Date Picker for News/Media/Events
	$( ".js-datepicker-advanced-search" ).datepicker({
		dateFormat:'dd/mm/yy'
	});	
	
	//Slider
	(function() {
		slider = {
			stopAtEnd : true,
			delay : 3000,
			initialised : false,
			autoPlay : true,
			buildNavigation : true,
			buildArrows : true,
			resizeContents : true,
			resize : function(target) {
				if(this.initialised == true) {
					this.init(target);
				}
			},
			init : function(target) {
				this.initialised = true;
				
				var object = '';
				calendarMustWait = false;
				if(target.toLowerCase() == 'slider') {
					$('.pf-top-banner-container .oms-rounded-slider .om-br').css("margin-top","-37px");
					$('.pf-top-banner-container .oms-rounded-slider .om-bl').css("margin-top","-37px");
					$('.pf-three-columns .pf-top-banner-container .oms-rounded-slider .om-br').css("margin-top","-39px");
					$('.pf-three-columns .pf-top-banner-container .oms-rounded-slider .om-bl').css("margin-top","-39px");
					this.autoPlay = true;
					this.buildNavigation = true;
					this.buildArrows = false;
					this.resizeContents = true;
					this.onSlideBegin = function() {};
					this.onSlideComplete = function() {};
					object = '.js-slider';
				} else if(target.toLowerCase() == 'calendar'){
					this.autoPlay = false;
					this.buildNavigation = false;
					this.buildArrows = false;
					this.resizeContents = true;
					this.onSlideBegin = function() { calendarMustWait = true};
					this.onSlideComplete = function() { calendarMustWait = false};
					object = '.js-event-slider';
				}
				
				$(object).anythingSlider({
					buildArrows: this.buildArrows,
					stopAtEnd: this.stopAtEnd,
					delay: this.delay,
					autoPlay : this.autoPlay,
					onSlideBegin: this.onSlideBegin,
					onSlideComplete: this.onSlideComplete,
					buildNavigation : this.buildNavigation,
					resizeContents : this.resizeContents
				})
			}
		}
	})();
	
	//Font size + cookie
	(function() {
		var fontSizes = $('.js-font-size');
		
		var updateFontSize = function(level) {
			var size = '13px';
			var active = 0;
			
			switch (level.toLowerCase()) {
				case 'large':
					size = '14px';
					active = 1;
				break;
				case 'larger':
					size = '16px';
					active = 2;
				break;
				default:
					size = '13px';
					active = 0;
				break;
			}
			
			document.body.style.fontSize = size;	
			
			fontSizes.removeClass('pf-selected');
			$(fontSizes.get(active)).addClass('pf-selected');
			
			slider.resize('slider');
			slider.resize('calendar');
			$('.pb-strategy-points .pb-height-container').removeAttr("style");
			equalHeight($('.pb-strategy-points .pb-height-container'));
			adaptVideoBtn();
			adjustRoundedImages();
		};
		
		if($.cookie('defaultFontSize') == undefined) {
			$.cookie('defaultFontSize', 'normal', { expires: 7 , path: '/' });
		} else {
			updateFontSize($.cookie('defaultFontSize'));
		}
		
		fontSizes.click(function() {
			var level = this.rel;
			
			$.cookie('defaultFontSize', level.toLowerCase(), { expires: 7 , path: '/' });
			
			updateFontSize(level);
		});
	})();
	
	/* Add This Bug Teamsite */
	
	
	/* Dropdown styled */
	$(".js-styled").uniform();
	
	/* Calendar */
	$( ".js-datepicker" ).datepicker({ dayNamesMin: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], showOtherMonths: true });
	
	function getUrlVars() {
		var vars = {};
		var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (m, key, value) {
			vars[key] = value;
		});
		return vars;
	}
	
	/* Calendar */
	slider.init('calendar');

	$(".js-change-calendar-display option:selected").each(function () {
		$(".js-calendar-tab").addClass("pb-hide");
		$(".js-"+$(this).val()).removeClass("pb-hide");
	});
	
	$(".js-change-calendar-display").change(function() {
		$(".js-change-calendar-display option:selected").each(function () {
			$(".js-calendar-tab").addClass("pb-hide");
			$(".js-"+$(this).val()).removeClass("pb-hide");
		});
	});
	
	/* Video Btn */
	function adaptVideoBtn(){
	
	if ($(".video-btn").length!=0) {

		$(".video-btn").parent().children("img").each(function(){
			adaptToImgWidth = $(this).width();
			adaptToImgHeight = $(this).height();
			$(this).parent().children(".js-openoverlay").children(".video-btn-overlayer").width(adaptToImgWidth);
			$(this).parent().children(".js-openoverlay").children(".video-btn-overlayer").height(adaptToImgHeight);
			$(this).parent().children(".video-btn").width(adaptToImgWidth);
			$(this).parent().children(".video-btn").height(adaptToImgHeight);
			if ($(this).parent().is(".pf-video-link-container")) {
				$(this).width("100%");
			}
		});
		
		$(".video-btn").parent().children("img").load(function(){
			adaptToImgWidth = $(this).width();
			adaptToImgHeight = $(this).height();
			$(this).parent().children(".js-openoverlay").children(".video-btn-overlayer").width(adaptToImgWidth);
			$(this).parent().children(".js-openoverlay").children(".video-btn-overlayer").height(adaptToImgHeight);
			$(this).parent().children(".video-btn").width(adaptToImgWidth);
			$(this).parent().children(".video-btn").height(adaptToImgHeight);
			if ($(this).parent().is(".pf-video-link-container")) {
				$(this).width("100%");
			}
		});
	}
	
	if ($(".picture-btn").length!=0) {

		$(".picture-btn").parent().children("img").each(function(){
			adaptToImgWidth = $(this).width();
			adaptToImgHeight = $(this).height();
			$(this).parent().children(".js-openoverlay").children(".video-btn-overlayer").width(adaptToImgWidth);
			$(this).parent().children(".js-openoverlay").children(".video-btn-overlayer").height(adaptToImgHeight);
			$(this).parent().children(".picture-btn").width(adaptToImgWidth);
			$(this).parent().children(".picture-btn").height(adaptToImgHeight);
			if ($(this).parent().is(".pf-video-link-container")) {
				$(this).width("100%");
			}
		});
		
		$(".picture-btn").parent().children("img").load(function(){
			adaptToImgWidth = $(this).width();
			adaptToImgHeight = $(this).height();
			$(this).parent().children(".js-openoverlay").children(".video-btn-overlayer").width(adaptToImgWidth);
			$(this).parent().children(".js-openoverlay").children(".video-btn-overlayer").height(adaptToImgHeight);
			$(this).parent().children(".picture-btn").width(adaptToImgWidth);
			$(this).parent().children(".picture-btn").height(adaptToImgHeight);
			if ($(this).parent().is(".pf-video-link-container")) {
				$(this).width("100%");
			}
		});
	}
	
	if ($(".doc-btn").length!=0) {

		$(".doc-btn").parent().children("img").each(function(){
			adaptToImgWidth = $(this).width();
			adaptToImgHeight = $(this).height();
			$(this).parent().children(".js-openoverlay").children(".video-btn-overlayer").width(adaptToImgWidth);
			$(this).parent().children(".js-openoverlay").children(".video-btn-overlayer").height(adaptToImgHeight);
			$(this).parent().children(".doc-btn").width(adaptToImgWidth);
			$(this).parent().children(".doc-btn").height(adaptToImgHeight);
			if ($(this).parent().is(".pf-video-link-container")) {
				$(this).width("100%");
			}
		});
		
		$(".doc-btn").parent().children("img").load(function(){
			adaptToImgWidth = $(this).width();
			adaptToImgHeight = $(this).height();
			$(this).parent().children(".js-openoverlay").children(".video-btn-overlayer").width(adaptToImgWidth);
			$(this).parent().children(".js-openoverlay").children(".video-btn-overlayer").height(adaptToImgHeight);
			$(this).parent().children(".doc-btn").width(adaptToImgWidth);
			$(this).parent().children(".doc-btn").height(adaptToImgHeight);
			if ($(this).parent().is(".pf-video-link-container")) {
				$(this).width("100%");
			}
		});
	}
	
	}
	
	adaptVideoBtn();
	
	/* Overlayer */
	$(".js-openoverlay").click(function() {
		$( "#"+$(this).attr("rel") ).dialog({
			zIndex: 8001,
			modal: true,
			width: "75em",
			close: function() { if ($(".js-slider").length!=0) {$('.js-slider').data('AnythingSlider').startStop(true);} $(".pf-main-submenu").removeAttr("style"); }
		});
		if ($(".js-slider").length!=0) {$('.js-slider').data('AnythingSlider').startStop(false);}
	});
	
	/* Accessibility without mouse to submenu */
	$('.js-main-menu-list li a').focus(function() {
		$this = $(this);
		$this.parent().children(".pf-main-submenu").show();
		$this.parent("li").addClass("pf-focused");
	  	if($this.parents('.pf-main-submenu').length == 0) {
	  		$(".pf-main-submenu").hide();
			$(".pf-focused").removeClass("pf-focused");
			$this.parent("li").addClass("pf-focused");
	  		$this.parent().children(".pf-main-submenu").show();
		}
	});
	$('.pb-mainContent a:first').focus(function() {
		if (!$(this).parents().hasClass("ui-dialog")) {
			$(".pf-focused").removeClass("pf-focused");
			$(".pf-main-submenu").hide();
		}
	});
	$(".js-main-menu-list li a").click(function() {
		$this = $(this);
		$this.blur();
		$(".pf-focused").addClass("js-hovering").removeClass("pf-focused");
		$(".pf-main-submenu").css("display","");
	});
	
	/* Wait O.5sec when hovering menu */
	function addMega(){
    	$(this).addClass("js-hovering");
    }

    function removeMega(){
    	$(this).removeClass("js-hovering");
    }

    var megaConfig = {
         interval: 300,
         sensitivity: 4,
         over: addMega,
         timeout: 500,
         out: removeMega
    };

    $(".js-main-menu-list li").hoverIntent(megaConfig);
	
	/* Adjust submenu position */
	$(".pf-main-submenu").each(function(){
		$this = $(this);
		$this.css({ position: "absolute", visibility: "hidden", display: "block" });
		currentWidth = $this.find(".pf-main-submenu-content").width();
		if ($.browser.msie && $.browser.version.indexOf("7.")>-1) {$this.width(currentWidth+100)}
		$this.css({ position: "", visibility: "", display: "" });
		if ($this.find(".pf-main-submenu-content").children().size() > 2) {
			var posSubmenu = $this.parent(".og-unit").position();
			if((posSubmenu.left)<=$(".pf-page").width()/2) {
				$this.css("left",0);
			} else {
				$this.css("right",0);
			}
		} else {
			var posSubmenu = $this.parent(".og-unit").position();
			var widthSubmenu = $this.parent(".og-unit").width();
			if (posSubmenu.left < currentWidth/2-(widthSubmenu/2)) {$this.css("left",0) }
				else {
					if (posSubmenu.left >= ($(".pf-page").width() - (currentWidth+widthSubmenu/2))) {$this.css("right",0)} else
					{ $this.css("margin-left",-(currentWidth/2)+(widthSubmenu/2)) }
			}
		}
	});
	
	/* Adjust Height for all strategy boxes */
	function equalHeight(group) {
		tallest = 0;
		group.each(function() {
			thisHeight = $(this).height();
			if(thisHeight > tallest) {
				tallest = thisHeight;
			}
		});
		group.height(tallest);
	}
	equalHeight($('.pb-strategy-points .pb-height-container'));
	
	/* Print BTN */
	//$(".pb-icon-print").click(function () {
	//TM 25/01/2012: commented onclick 'cause always needs to be done for browser print to work properly
		$mainContent = $(".pb-mainColumn");
		$(".pb-mainContent .ls-fxr").children().addClass("pb-screen");
		$mainContent.removeClass("pb-screen");
		$mainContent.addClass("pb-full-width");
	//});
	
	/* Mail BTN */
	$(".pb-icon-mail").click(function () {
		addthis_open(this, 'email');
	});
	
	$(".ui-dialog-titlebar-close").click(function () {
		
	});
	
	/* Init Tabs */
	var $tabobject = $(".oms-with-tabs");
	if ($tabobject.find(".js-firstTab").hasClass('pf-activeLink')) {
		$tabobject.find(".pf-corners-tl").hide();
		$tabobject.find(".pf-tabcontent").css("-moz-border-radius", "0 12px 12px 12px");
		$tabobject.find(".pf-tabcontent").css("border-radius", "0 12px 12px 12px");
		$tabobject.find(".pf-tabcontent").css("-webkit-radius", "0 12px 12px 12px");
		$tabobject.find(".om-tl").css("background-position", "left top");
	} else {
		$tabobject.find(".pf-tabcontent").css("-moz-border-radius","12px 0 12px 12px");
		$tabobject.find(".pf-tabcontent").css("border-radius","12px 0 12px 12px");
		$tabobject.find(".pf-tabcontent").css("-webkit-radius","12px 0 12px 12px");
		$tabobject.find(".pf-corners-tr").hide();
		$tabobject.find(".om-tr").css("background-position","right top");
	}
	
	/* Tab & Profile Cookie */
	if (typeof profiles != "undefined"){
	    	for(var i=0; i < profiles.length; i++)
	    	$(".js-"+profiles[i]).addClass("pb-hide");
    	}
	

	if ($.cookie('profile') != "undefined" && $.cookie('profile') != null && $.cookie('profile') != '') {
		tabeId = $.cookie('profile');
		$(".pb-tabLink").removeClass("pb-activeLink");
		$("#" + tabeId).addClass("pb-activeLink");
		$(".pb-tabcontent").addClass("pb-hide");
		$(".js-" + tabeId).removeClass("pb-hide");
	} else {
		if (typeof profiles != "undefined"){
			$.cookie("profile", profiles[0], { expires: 7, path: '/' });
			tabeId = $.cookie('profile');
			$(".pb-tabLink").removeClass("pb-activeLink");
			$("#" + tabeId).addClass("pb-activeLink");
			$(".pb-tabcontent").addClass("pb-hide");
			$(".js-" + tabeId).removeClass("pb-hide");
		}
	}
	
    	$(".pb-tabLink").click(function () {
			var $this = $(this);
			tabeId = $this.attr('id');
			$(".pb-tabLink").removeClass("pb-activeLink");
			$this.addClass("pb-activeLink");
			$(".pb-tabcontent").addClass("pb-hide");
			$(".js-"+tabeId).removeClass("pb-hide");
			$.cookie("profile", tabeId, { expires: 7, path: '/' });
			/* Readjust iFrame */
			var transHeight = $(".iframe:visible").contents().find(".pb-profileFrame").height();
			if (transHeight >= $('.iframe:visible').height()) {
				$('.iframe:visible').height(transHeight);
			}
			/* Reload Calendar in Iframe */
			if ($(".iframe:visible").contents().find(".js-list").length!=0) {
				$(".iframe:visible").attr('src', $(".iframe:visible").attr('src'));
			}
		});
		
		$(".js-profileLink").click(function () {
        	var $this = $(this);
            profileId = $this.attr('id');
            languageId = $this.attr('language');
            url = $this.attr('url');
            $.cookie("profile", profileId, { expires: 7, path: '/' });
            Belgacom.Translations.switchLanguage(languageId,url);
        });

    	$(".pf-modtab-link").click(function () {
		var $this = $(this);
		var $tabobject = $(".oms-with-tabs");
		linkclass = $this.attr('class');
		tabeId = $this.attr('id');
		$(".pf-modtab-link").removeClass("pf-activeLink");
		$this.addClass("pf-activeLink");
		$(".pf-tabcontent").addClass("pb-hide");
		$("." + tabeId).removeClass("pb-hide");
		$tabobject.find(".pf-corners-tl").show();
		$tabobject.find(".pf-corners-tr").show();
		$tabobject.find(".pf-tabcontent").css("-moz-border-radius","12px 12px 12px 12px");
		$tabobject.find(".pf-tabcontent").css("border-radius","12px 12px 12px 12px");
		$tabobject.find(".pf-tabcontent").css("-webkit-radius","12px 12px 12px 12px");
		$tabobject.find(".om-tl").css("background-position","left -48px");
		$tabobject.find(".om-tr").css("background-position","right -48px");
		$tabobject.find(".pf-corners-tl").css("background-position","left -72px");
		$tabobject.find(".pf-corners-tr").css("background-position","right -72px");
		if (linkclass.indexOf("firstTab") > -1) {
			$tabobject.find(".pf-tabcontent").css("-moz-border-radius","0 12px 12px 12px");
			$tabobject.find(".pf-tabcontent").css("border-radius","0 12px 12px 12px");
			$tabobject.find(".pf-tabcontent").css("-webkit-radius","0 12px 12px 12px");
			$tabobject.find(".pf-corners-tl").hide();
			$tabobject.find(".om-tl").css("background-position","left top");
		}
		if (linkclass.indexOf("lastTab") > -1) {
			$tabobject.find(".pf-tabcontent").css("-moz-border-radius","12px 0 12px 12px");
			$tabobject.find(".pf-tabcontent").css("border-radius","12px 0 12px 12px");
			$tabobject.find(".pf-tabcontent").css("-webkit-radius","12px 0 12px 12px");
			$tabobject.find(".pf-corners-tr").hide();
			$tabobject.find(".om-tr").css("background-position","right top");
		}
	});
	
	/* Redimensionner Iframe, see function at top */	
	iframe();
	

		//SHARING: Generate 'addthis' links
		$("div.addthis_div").each(function(){
			$(this).removeClass("addthis_div");
			$(this).addClass("addthis_toolbox");
			$(this).addClass("addthis_default_style");
			$(this).attr("addthis:url", $(this).attr('addthis-url'));
			$(this).attr("addthis:title", $(this).attr('addthis-title'));
			var a = $('<a class="addthis_counter addthis_pill_style"></a>').appendTo($(this));
		});

		//SHARING: Generate 'facebook' links
		var bodyId = document.getElementsByTagName("body")[0];         
		var fbrootNode = document.createElement('div');
		fbrootNode.id = 'fb-root';
		bodyId.appendChild(fbrootNode);
		$("div.fblike_div").each(function(){
			$(this).removeClass("fblike_div");
			var source = this.attributes;
			var idx = '';
			var fblike = $("<fb:like></fb:like>").appendTo($(this))
			for (idx in source) {
				var attr = source[idx];
				
				if (typeof attr !== 'undefined' ) {
					fblike.attr(attr.name, attr.value);
				}
			}
		});
	
		//SHARING: include vendor javascripts
		function addJavascriptFile(jsFileName){
			var headID = document.getElementsByTagName("head")[0];         
			var newScript = document.createElement('script');
			newScript.type = 'text/javascript';
			newScript.src = jsFileName;
			headID.appendChild(newScript);
		}
		addJavascriptFile('http://s7.addthis.com/js/250/addthis_widget.js');
		addJavascriptFile('http://platform.twitter.com/widgets.js');
		//facebook's URL depends on locale (generated by SharingUtils.java and included as hidden input in XHTML)
		var facebookURLs = document.getElementsByName('facebook-connect-url');
		if (facebookURLs.length!=0 && facebookURLs[0].value.length!=0){
			//they will be all the same, add only the first
			addJavascriptFile(facebookURLs[0].value);	
		} 
		else {
			//use EN by default
			addJavascriptFile('http://connect.facebook.net/en_US/all.js#xfbml=1');
		}
		
		//include the print CSS (cannot be included by teamsite because of media="print" attribute)
		function addCSSFile(cssFileName,mediaType){
			var headID = document.getElementsByTagName("head")[0];         
			var cssNode = document.createElement('link');
			cssNode.type = 'text/css';
			cssNode.rel = 'stylesheet';
			cssNode.href = cssFileName;
			cssNode.media = mediaType;//'all', 'screen', 'print', etc.
			headID.appendChild(cssNode);
		}
		addCSSFile('assets/content/css/print.css','print');
		addCSSFile('assets/content/css/mobile.css','only screen and (max-device-width: 480px)'); 
		
		//MEDIABIN: Generate mediabin download links (extension need to be added)
		$("a.mediabinDownloadLink").each(function(){
			$(this).removeClass("mediabinDownloadLink");
			var filename = $(this).attr("filename");
			var extensionStart = filename.lastIndexOf('.');
			var extension = '';
			if (extensionStart>=0 && extensionStart<filename.length){
				extension = filename.substring(extensionStart);
			}
			$(this).attr("href", $(this).attr("href").replace("}","}"+extension));
		});				
		
		var pathname = window.location.pathname;
		var extansion = pathname.substring(pathname.length - 10, pathname.length);
		if ((pathname.indexOf("iw-preview") >= 0) && (extansion==".component")) {addCSSFile('/assets/content/css/default.css','screen');}
		
		//REMOVE EMPTY IMAGES
		$('img.removeWhenNoSrc').each(function(){
			var imgSrc = $(this).attr('src');
			$(this).removeClass('removeWhenNoSrc');
			if (imgSrc && imgSrc!=''){
				//ok
			}else{
				$(this).remove();
			}
		});
	
});

