/* correctly handle PNG transparency in Win IE 5.5 & 6.
------------------------------------------------------------------------------*/
function correctPNG()
{
   var arVersion = navigator.appVersion.split("MSIE")
   var version = parseFloat(arVersion[1])
   if ((version >= 5.5) && (version < 7) && (document.body.filters)) 
   {
      for(var i=0; i<document.images.length; i++)
      {
         var img = document.images[i]
         var imgName = img.src.toUpperCase()
         if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
         {
            var imgID = (img.id) ? "id='" + img.id + "' " : ""
            var imgClass = (img.className) ? "class='" + img.className + "' " : ""
            var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
            var imgStyle = "display:inline-block;" + img.style.cssText 
            if (img.align == "left") imgStyle = "float:left;" + imgStyle
            if (img.align == "right") imgStyle = "float:right;" + imgStyle
            if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
            var strNewHTML = "<span " + imgID + imgClass + imgTitle
            + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
            + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
            + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>" 
            img.outerHTML = strNewHTML
            //alert("not visible under IE7");
            i = i-1
         }
      }
   }    
}
//window.attachEvent("onload", correctPNG);
$(function(){
/* headline
------------------------------------------------------------------------------*/
	if(!$("#news").length)
	{
		$(".home div.right").css("margin-top","0");
	}
	
/* flash
------------------------------------------------------------------------------*/
	if($("#carte").length)
	{
		if(!siteEditEnabled){
			$("#carte").flash({
				width:482,
				height:122,
				flashvars:{
					//image:"img/worldwide_presence.png",
					xml:flashBannerConfigUrl
				},
				wmode:"transparent",
				src:flashMediaUrl},{
					version:8
				}
			);
		}
	}
	
				
/* Manage logo version by language
------------------------------------------------------------------------------*/
	if($("#logo .logo img").length)
	{
		var locale = $("html").attr("lang");
		var logoTranslationLanguages = "";
		/*initLogoTranslationLanguages is defined in the file deploy.js (specific to each website) */
		if(typeof(initLogoTranslationLanguages)!='undefined' && initLogoTranslationLanguages!=null)
		{
			logoTranslationLanguages = initLogoTranslationLanguages;
		}
					
		if(logoTranslationLanguages.indexOf("'"+locale+"'") != -1 )
		{
			// rename logo
			$('#logo .logo img').attr("src",$('#logo .logo img').attr("src").replace("logo_rhodia","logo_rhodia_"+locale));
		 
		}
	}

/* manage top panels 
------------------------------------------------------------------------------*/
	$("#country, #qaccess, #sign").addClass("flottant").hide();
	$(".country a").click(function(){
		$("#qaccess, #sign, #country").hide();
		$(".sign a, .qaccess a").removeClass("close");
		if($(this).attr("class") == "close")
		{
			$($(this).attr("href")).hide();
			$(this).removeClass("close");
			$("#logo a.logo").show();
		}
		else
		{
			$($(this).attr("href")).show();
			$(this).addClass("close");
			$("#logo a.logo").hide();
		}
		$(this).blur();
		return(false);
	});
	
	$(".sign a").click(function(){
		$("#qaccess, #sign, #country").hide();
		$(".country a, .qaccess a").removeClass("close");
		if($(this).attr("class") == "close")
		{
			$($(this).attr("href")).hide();
			$(this).removeClass("close");
			$("#logo a.logo").show();

		}
		else
		{
			$($(this).attr("href")).show();
			$(this).addClass("close");
			$("#logo a.logo").hide();

		}
		$(this).blur();
		return(false);
	});
	
	$(".qaccess a").click(function(){
		$("#qaccess, #sign, #country").hide();
		$(".country a, .sign a").removeClass("close");
		if($(this).attr("class") == "close")
		{
			$($(this).attr("href")).hide();
			$(this).removeClass("close");
			$("#logo a.logo").show();
		}
		else
		{
			$($(this).attr("href")).show();
			$(this).addClass("close");
			$("#logo a.logo").hide();
		}
		$(this).blur();
		return(false);
	});
	var h = 0;
	$(".prelease a").each(function() {
		if($(this).parent().parent().attr("class")=='paddingLeft')
			h = Math.max($(this).height(), h);
	});
	$(".prelease a").each(function() {
		if($(this).parent().parent().attr("class")=='paddingLeft')
			$(this).height(h);
	});
	/*
	$("body").click(function(){
		$("h1 span").show();
		$(".country a, .sign a, .qaccess a").removeClass("close");
		$("#country, #qaccess, #sign").hide();
	});
	*/
/* faq
------------------------------------------------------------------------------*/
	$("#faq dd, #faq dt").addClass("off");
	$("#faq dt").hover(function(){
		$(this).addClass("hover");
	},function(){
		$(this).removeClass("hover");
	}).click(function(){
/*		$(this).addClass("visited"); */
		$(this).toggleClass("off");
		$(this).next().toggleClass("off");
	});
/* drop-down menu navigation
------------------------------------------------------------------------------*/
	$("#navigation li").hover(function(){
		$(this).addClass("hover");
	},function(){
		$(this).removeClass("hover");	
	});
/* text input
------------------------------------------------------------------------------*/
	var keywords = $("#keywords").val();
	$("#keywords").focus(function(){
		if($(this).val() == keywords)
			$(this).val("");
	});
	$("#keywords").blur(function(){
		if($(this).val() == "")
			$(this).val(keywords);
	});

	var searchBox = $("#searchbar #search").val();
	$("#searchbar #search").focus(function(){
		if($(this).val() == searchBox)
			$(this).val("");
	});
	$("#searchbar #search").blur(function(){
		if($(this).val() == "")
			$(this).val(searchBox);
	});	
	
	var search_in = $(".search_section form input[name='keywords']").val();
	$(".search_section form input[name='keywords']").focus(function(){
		if($(this).val() == search_in)
			$(this).val("");
	});
	$(".search_section form input[name='keywords']").blur(function(){
		if($(this).val() == "")
			$(this).val(search_in);
	});
		
	var autocompletable = $("#autocompletable").val();
	$("#autocompletable").focus(function(){
		if($(this).val() == autocompletable)
			$(this).val("");
	});
	$("#autocompletable").blur(function(){
		if($(this).val() == "")
			$(this).val(autocompletable);
	});
	
/* increase and decrease font size
------------------------------------------------------------------------------*/
	/*
	$(".sign").after('<ul class="police">'+
			'<li><a class="decrease" href="#" title="decrease the size"><img src="img/tmoins.gif" alt="decrease the character\'s size" /></a></li>'+
			'<li><a class="standard" href="#" title="standard size"><img src="img/tzero.gif" alt="standard character size" /></a></li>'+
			'<li><a class="increase" href="#" title="increase the size"><img src="img/tplus.gif" alt="increase the character\'s size" /></a></li>'+
		'</ul>');
	*/
	$("a.decrease").click(function(){
		$("body").removeClass("increase").removeClass("normal").addClass("decrease");
		$(this).blur();
		return(false);
	});
	$("a.increase").click(function(){
		$("body").removeClass("decrease").removeClass("normal").addClass("increase");
		$(this).blur();
		return(false);
	});
	$("a.standard").click(function(){
		$("body").removeClass("decrease").removeClass("increase");
		$(this).blur();
		return(false);
	});
	$(".top .cleft").addClass("bottom");
	if($("html").attr("lang") == "zh")
	{
		$("body").addClass("increase");
		$("a.decrease").click(function(){
			$(this).blur();
			return(false);
		});
		$("a.increase").click(function(){
			$(this).blur();
			return(false);
		});
		$("a.standard").click(function(){
			$(this).blur();
			return(false);
		});
	}
/* print action
------------------------------------------------------------------------------*/
	/*
		$(".pictos").prepend('<li><a class="print" href="#" title="Print"><img src="img/print.gif" alt="Print" /></a></li>');
	*/
	$(".print").click(function(){
		window.print();
		$(this).blur();
		return(false);
	});
/* 
------------------------------------------------------------------------------*/
	$("#nav>ul>li").hover(function(){
		$(this).addClass("hover");
		if($.browser.msie && $.browser.version == "6.0")
		{
			$("#content select").css("visibility","hidden");
		}
	},function(){
		$(this).removeClass("hover");
		$("#content select").css("visibility","visible");
	});
/* carousel
------------------------------------------------------------------------------*/

	$(".switch_init").removeClass("switch_init");
	
	if($("#mycarousel").length)
	{
		$("#mycarousel").jcarousel({
			scroll:1,
			start:1,
			visible:1,
			wrap:"both",
			auto:10
		});
	}
/* latest press release and events
------------------------------------------------------------------------------*/
	$(".prelease_init").removeClass("prelease_init");
	$(".prelease>ul>li").addClass("off");
	// UPDATE RHODIA
	
	$(".prelease>ul>li:first").removeClass("off").addClass("on");
	$(".prelease>ul>li>a").click(function(){
		// put off class on all LI
		$(".prelease>ul>li").removeClass("off").removeClass("on").addClass("off");
		// put on class on LI containing clicked anchor
		$(this).parent().removeClass("off").addClass("on");
		$(this).blur();
		return(false);
	});
	
/* related links
------------------------------------------------------------------------------*/
	$(".relatedLinks>ul>li").addClass("off");
	$(".relatedLinks>ul>li:first").removeClass("off").addClass("on");
	$(".relatedLinks>ul>li>a").click(function(){
		// put off class on all LI
		$(".relatedLinks>ul>li").removeClass("off").removeClass("on").addClass("off");
		// put on class on LI containing clicked anchor
		$(this).parent().removeClass("off").addClass("on");
		$(this).blur();
		return(false);
	});	
/*
------------------------------------------------------------------------------*/
	/*
									$(".news .roll").after('<ul class="navig">'+
										'<li><a id="prev" href="#"><img src="img/prev_off.gif" alt="Précédent" title="" /></a></li>'+
										'<li><a id="next" href="#"><img src="img/next_off.gif" alt="Suivant" title="" /></a></li>'+
									'</ul>')
	*/
	if($(".news .roll").length){
		$(".news .roll").cycle({ 
		    fx:     "fade", 
		    timeout: 0, 
		    speed:   1000, 
		    timeout: 10000, 
		    next:   "#next", 
		    prev:   "#prev" 
		});
	}
	$("#next, #prev").hover(function(){
			$(this).children().attr("src",$(this).children().attr("src").replace("_off","_on"));
		},function(){
			$(this).children().attr("src",$(this).children().attr("src").replace("_on","_off"));
		}).click(function(){
		$(this).blur();
	});
/*
------------------------------------------------------------------------------*/
/*
	$("#country .arrow").toggle(function(){
		$("#country").css("height","500px");
		$("#country .hide").show();
	},function(){
		$("#country .hide").hide();	
		$("#country").css("height","120px");
	});
*/
/*
------------------------------------------------------------------------------*/
	$(".profile li").click(function(){
		$(".profile li").not(this).removeClass("on");
		$(this).toggleClass("on");
		$(this).blur();
	});
/*
------------------------------------------------------------------------------*/
	$(".tabs").not(":first").hide();
	$("#tabs li").click(function(){
		$("#tabs li").removeClass("on");
		$(this).addClass("on");
		$(".tabs").hide();
		$($(this).children().attr("href")).show();
		$(this).children().blur();
		return false;
	});
/* table
------------------------------------------------------------------------------*/
  $('#content .inside td').addClass("tableothercells");
  $('#content .inside tr td:first-child').removeClass("tableothercells").addClass("tablefirstcolumn");
  $('#content .inside tr:first-child td').removeClass("tableothercells").removeClass("tablefirstcolumn").addClass("tablefirstline");    
  $('.datatable td').addClass("tableothercells");
  $('.datatable tr td:first-child').removeClass("tableothercells").addClass("tablefirstcolumn");
  $('.datatable tr:first-child td').removeClass("tableothercells").removeClass("tablefirstcolumn").addClass("tablefirstline");
/*
------------------------------------------------------------------------------*/

	if(!siteEditEnabled)
	{
		correctPNG();
	}
/*
------------------------------------------------------------------------------*/
/* popin
------------------------------------------------------------------------------*/
	$("#masque, #popin #close a, #popin a.button").click(function(){
		$("html").removeClass("popin");
		$(this).blur();
		return(false);
	});
	
	/* contaxtualization of news/events*/
	if(!siteEditEnabled){
		// initialisation
		var allowedPageTypes = ["event-index-page","pr-index-page"];
		var deniedUniverse = "news_center";
		
		// retrieve variable values fom current page
		var pageType = $("meta[name='tcmPageType']").attr("content");
		var universe = $("body").attr("class");
		if( ((pageType==allowedPageTypes[0]) || (pageType==allowedPageTypes[1]) ) && (universe != deniedUniverse)&& ($(".inside .search_results .arrows a").length) ){
			var rootHref;	
		  	// init URL base
			rootHref = $(".inside .search_results .arrows a").get(0).href;
			rootHref = rootHref.substr(0,rootHref.lastIndexOf("/")+1);
			  
			// init detail if hashname (bookmark support)
		    var initialHash = $.history.getCurrent();
			if(initialHash != '') {
				// show content detail
				showContentDetail(rootHref + initialHash);
			}
	
		
			// available for navigation (prev/next) in the browser
			$(window).history(function(e, hash){
				if(hash == '') {
					// hide content detail
					hideContentDetail();
				}
				if(hash != '') {
					// show content detail
					showContentDetail(rootHref + hash);
				}
			});
		
			// available when click on the content detail link (anchor: a)
			$(".inside .search_results .arrows a").click(function(){	
				var url = $(this).attr("href");
			    // get content detail from the detail page and load it + hide the current content
			    showContentDetail(url);
			    
			   	// calculate the hashName for the detail page
				var tab = url.split("/");
				var hachName = tab[tab.length -1];
				
				// navigate to the new keyword and change the URL in the user's browser
				$.history.add(hachName);
			 	return false;	
			});
		}
	}
	
	/* pagination group-items [business pages]*/
	/**
	 * When document has loaded, initialize pagination. 
	 */
	if(!siteEditEnabled){
		if($("#content .inside .pagedcontentindex #push").length){
			//create and insert DIVs in the html code of the page (DIV for displayed elements and DIV for pagination)
			$("<div id='searchResult'></div>").appendTo("#content .pagedcontentindex #push");
			$("<div id='Pagination' class='pagination'></div>").appendTo("#content .pagedcontentindex #push");
			 // create pagination element with options
			 var optInit =  { callback: pageselectCallback }
		     // get all elements to paginate.
		     var members = $("#content .inside .pagedcontentindex #push div.box");
		    // Create pagination element with given options.
			$("#content .inside .pagedcontentindex #push #Pagination").pagination(members.length, optInit);
			/*  ne semble pas fnctionner à tester par alex
			$("#content .inside .pagedcontentindex #push #Pagination").pagination(members.length, {
			        num_edge_entries: 10, // Number of start and end points
			        num_display_entries: 3, // Number of pagination links shown
			        items_per_page:5, // Number of items per page
			        callback: pageselectCallback       
			    });
			    */
		}
	}else{
		if($("#content .inside .pagedcontentindex #push").length){
			$("#content .inside .pagedcontentindex #push .box").show();
		}
		
	}
	
	/* pagination gallery-focus [business pages]*/
	/**
	 * Load HTML snippet with AJAX and insert it into the Hiddenresult element
	 * When the HTML has loaded, call initPaginationGallery to paginate the elements  
	 */
	if($("#content .inside .diaporama-liste").length)
	{
		initPaginationGallery();
	}



	
	/*
	------------------------------------------------------------------------------*/
	/* Auto-completion
	------------------------------------------------------------------------------*/
	if(!siteEditEnabled){
		if($("#autocompletable").length){
			var boxList = $(".pagedcontentindex #push > .box");
			if(boxList.length){			
				// first : build a hashmap with text for key and node containing whole HTML for value
				var map = new Array(boxList.length);
				var iter = 0;
				boxList.each(function(){
				  if($(this).find("a")){
				    map[iter] = { name: $(this).find("a").text(), to: $(this).get(0) };
				  }  	
				  iter = iter + 1;
				});
				// second : attach the behavior auto-complete to the field
				if(map[0]){	
					$("#autocompletable").autocomplete(map, {
							minChars: 0,
							width: 373,
							scrollHeight: 284,
							matchContains: true,
							highlightItem: false,
							scroll: true,
							// item to match (if no definition, the format item is used)
							formatMatch: function(row, i, max) {
							  return row.to.innerHTML;
								//return row.name;
							},
							// item to display under the field
							formatItem: function(row, i, max, term) {
								//return i + "/" + max + " " + row.to.innerHTML;
								//return i + "/" + max + " " + row.name;
								return row.to.innerHTML;
							},
							// item to match (if no definition, the format item is used)
							formatResult: function(row, i, max) {
								return row.name;
								//return row.to.innerHTML;
							}
						});	
					}
		
					// third : attach the redirection behavior on the choice of an item in the list
					$("#autocompletable").result(function(event, data, formatted) {
						//$(this).after("<span class='ac_loading_page'>&nbsp;</span>");
						$(this).addClass("ac_loading");
						document.location=data.to.getElementsByTagName("a")[0];
					});	
				}
			}
		}
	
	
	
	
	


});

/**************************** global functions ******************************/	

/* contaxtualization of news and events*/
function showContentDetail(url){
	$("#content .inside").removeClass("inside").addClass("insidehidden");
	$("body").css("cursor","progress");
	$("#content .insidehidden").hide();
	$("<div class='detailtmp'></div>").appendTo("#content");
	$("#content .detailtmp").load(url + " #content .inside", function(){
		$("body").css("cursor","default");	
	});
}
function hideContentDetail(){
	$("#content div.detailtmp").remove();
	$("#content .insidehidden").removeClass("insidehidden").addClass("inside");	
	$("#content .inside").show();
}

/**
 * Callback function that displays the content.
 *
 * Gets called every time the user clicks on a pagination link.
 *
 * @param {int}page_index New Page index
 * @param {jQuery} jq the container with the pagination links as a jQuery object
 */
function pageselectCallback(page_index, jq){
	  // get number of  the entire elements inside the div block named "push" 
	  var allMembers = $("#content .inside .pagedcontentindex #push div.box");
	  // get number of dislplayed element "visibility = true" 
	  var insertedMembers = $("#content .inside .pagedcontentindex #push #searchResult div.box");
	  // get number of hidden elements to paginate "elements with visibility = false"
	  var membersLength = allMembers.length - insertedMembers.length;
	  
	// Define number of elements per pagination 
	  var items_per_page = 10;
	  var max_elem = Math.min((page_index+1) * items_per_page, membersLength);
	 
	  var newcontent = '';
	  // Iterate through a selection of the content and build an HTML string
	  for(var i=page_index*items_per_page;i<max_elem;i++)
	  {
	    //newcontent += $('#content .inside #push div.box:eq('+i+')').clone();
	    newcontent += '<div class="box">' + $('#content .inside .pagedcontentindex #push div.box:eq('+i+')').html()+ '</div>';
	  }
	  // Replace old content with new content
	  $('#content .inside .pagedcontentindex #push #searchResult').html(newcontent);
	  return false;
      }
 
/**
 * Callback function that displays the content.
 *
 * Gets called every time the user clicks on a pagination link.
 *
 * @param {int}page_index New Page index
 * @param {jQuery} jq the container with the pagination links as a jQuery object
 */
function pageselectCallbackGallery(page_index, jq){
	// get hidden element with its index
    var new_content = $('#content .inside .diaporama div.box:eq('+page_index+')').clone();
    // display the got element in to the specified block with has been created dynamically
    $('#searchResultGallery').empty().append(new_content);
    return false;
}

/**
 * Callback function for the AJAX content loader.
 */
function initPaginationGallery() {
    // get the number of entire elements to witch we have to apply pagination
	var num_entries = $('#content .inside .diaporama div.box').length;
    // Create pagination element
    $("#diaporama-pagination").pagination(num_entries, {
        num_edge_entries: 1, // Number of start and end points
        num_display_entries: 3, // Number of pagination links shown
        items_per_page:1, // Number of items per page
        callback: pageselectCallbackGallery        
    });

 }



