/**
* @author Kieran Hayes <kieran.hayes@dkd.de>
* 
*
*/

function fixSubmenuWidth(){
 //$(".submenu:first").width($(".submenu:first").width()+2);
	  //console.debug("fixing width");
	
	$subwidth = 0;
	$(".submenu > li").each(function(){
		   $subwidth += $(this).width() + 10;
	});
	
	if ($subwidth == 0) {
		return false;
	}
	if ($subwidth  > $(".submenu").width() ) {
		$(".submenu").width($subwidth+10);
	}
}



var inFocusAnimationIsRunning = 0;
var infocusSlideShowInterval;
var InFocusFadeInSpeed = 1000;
var ytplayer;
var events = [];

function inFocusSlideShow(){
	inFocusAnimationIsRunning = 1;
	if($(".switch_tabs .tabMenu li.active").next("li").find("a").length == 0){
		$(".switch_tabs .tabMenu li:first").find("a").click();
	}
	else{
		$(".switch_tabs .tabMenu li.active").next("li").find("a").click();
	}
}

function onYouTubePlayerReady(playerId) {
	ytplayer = document.getElementById("unescoYoutube");
    ytplayer.addEventListener('onStateChange', 'onytplayerStateChange');
}

function onytplayerStateChange(newState) {
	events.push('onStateChange event: Player state changed to: "' + 
			newState + '" (' + ytplayer.getPlayerState(newState) + ')');
	if ((newState == 1) || (newState == 3)) {
		inFocusAnimationIsRunning = 0;
		clearInterval(infocusSlideShowInterval);
	}
	
	if ((newState == 0) || (newState == -1)) {
		inFocusAnimationIsRunning = 1;
		infocusSlideShowInterval = setInterval("inFocusSlideShow()", 5000);
	}
}


/**
* @author Stefan Sprenger <stefan.sprenger@dkd.de>
* @since 2009-09-01
*/

$(document).ready(function() {
  $(".printPage").click(function() {
    window.print();
    return false;
  });
  
//check for iPad
  if(navigator.platform == "iPad") {
	$("#quickThemeSelector input.submit").css("background", "grey");
	$("#quickThemeSelector input.submit").css("padding", "0");
	$("#quickThemeSelector input.submit").css("width", "auto");
	$("#search input.submit").css("background", "grey");
	$("#search input.submit").css("padding", "0");
	$("#search input.submit").css("width", "auto");
  }

  $(".bookmark").click(function() {

    var Text = document.title;
    var URL = self.location.href;

    if (window.sidebar.addPanel) { // firefox
      window.sidebar.addPanel(Text, URL, "");
    } 
    else if(window.opera && window.print) { // opera
      var elem = document.createElement('a');
      elem.setAttribute('href', URL);
      elem.setAttribute('title', Text);
      elem.setAttribute('rel', 'sidebar');
      elem.click();
    } 
    else if(document.all) { // ie
      window.external.AddFavorite(URL, Text);
    }

        return false;
  });
      
      $(".bigFont").click(function() {
        changeTaille(2);
      });

      $(".smallFont").click(function() {
        changeTaille(-2);
      });

      /* Quicktheme selector */
      $("#quickThemeSelector select").change(function(){
        if($(this).val().length>0) 
        $(this).parents("form").submit();
      });

      $("#quickThemeSelector > form").submit(function(){
          return ($("#quickThemeSelector select").val().length>0);
        });

      /* In Focus Navigation */


      $(".switch_tabs div.content_tab").not(":first").hide();
      
      if($(".switch_tabs div.content_tab").length < 2){
        $(".switch_tabs ul.tabMenu").remove();
      }
      else{
        $(".switch_tabs ul.tabMenu").html("");
        $(".switch_tabs div.content_tab").each(function(i)
        {
          i++;
          $(this).attr("id", "inner_tab_focus_" + i);
          
          $(".switch_tabs ul.tabMenu").append("<li class='tooltip_"+i+"'><a href='"+ "#inner_tab_focus_" + i +"'>"+i+"</a></li>");
          var tooltipTitle = $(this).find("h3").html();
          
          if($(this).find("img").length>0){
            var tooltipImageSrc = $(this).find("img").attr("src");
            
            var tooltipImage = "<img src='"+$(this).find("img").attr("src")+"' with='83' height='69' align='top' style='margin-top:10px;display:block' />";
          }
          else{
            var tooltipImage = "";
          }
          
          $(".switch_tabs ul.tabMenu li.tooltip_"+i).qtip({
             content: {text: tooltipTitle + tooltipImage},
             style: {
               width: 115,
               tip: 'bottomMiddle',
               name: 'light',
               color: '#595959',
               border: {
                 color: '#3F95C3'
               }
             },
             position: {
                corner: {
                   target: 'topMiddle',
                   tooltip: 'bottomMiddle'
                }
             }
          });
        }
      );
        
      }
      
    $(".switch_tabs ul.tabMenu li:first").addClass("active");

    $(".switch_tabs .content_tab").hide();
    $(".switch_tabs").each(function() {
      $(this).find('.content_tab:eq(0)').show();
    });

    $(".switch_tabs .tabMenu a").click(function(){ 
      var activeContent = $(this.hash);
      $(this).parents('.switch_tabs').find('.content_tab:visible').fadeOut(InFocusFadeInSpeed, function(){activeContent.fadeIn(InFocusFadeInSpeed);});
      $(this).parent().siblings().removeClass('active');
      $(this).parent().addClass('active');
      this.blur();
      return false;
    });
    
    /* Starting the In Focus slideshow */
    
    if (inFocusAnimationIsRunning == 0){
      infocusSlideShowInterval = setInterval("inFocusSlideShow()", 10000);
    }
    
    /* Restarting the In Focus slideshow after mouseout */
    $("#blockFocusTabs").mouseout(function(){
      
      if (inFocusAnimationIsRunning == 0){
        InFocusFadeInSpeed = 2000;
        infocusSlideShowInterval = setInterval("inFocusSlideShow()", 10000);
      }
    });
    
    /* Stoping the In Focus slideshow on mouseover */
    $("#blockFocusTabs").mouseover(function(){
      InFocusFadeInSpeed = 500;
      clearInterval(infocusSlideShowInterval);
      inFocusAnimationIsRunning = 0;
    });
    
    $("#blockFocusTabs").mouseout(function(){
    	ytplayer = document.getElementById("unescoYoutube");
    	if (ytplayer) {    		
    		if (typeof document.getElementById("unescoYoutube").getPlayerState == "function") {
    			ytState = ytplayer.getPlayerState();
    			
    			if (ytState == 1) {
    				clearInterval(infocusSlideShowInterval);
    				inFocusAnimationIsRunning = 0;
    			}
    			
    			if ((ytState == 0) || (ytState = -1) ) {
    				inFocusAnimationIsRunning = 1;
    			}
    			
    		}
    	}
    });
    
    

    
    
  // /* In Focus qTip */
  // $(".switch_tabs .tabMenu li a").qtip({
  //    
  //    
  //    style: "dark",
  //    position: {
  //       corner: {
  //          target: 'topMiddle',
  //          tooltip: 'bottomMiddle'
  //       }
  //    }
  // });
  // 
  // 
    
    /* Fix for sitemap */
    
    $("dt.title_map").each(function(i){
      var pos = i+1;
      $(this).find("a:first").attr("href", "#inner_tab_siteMap_" + pos);
      $(this).next("dd").attr("id", "inner_tab_siteMap_" + pos);      
    });
    
    
    $("dt.title_map a").click(function(){
      
      var src = $(this).find("img:first").attr("src");
      src = "fileadmin/unesco/" + src;
      $(this).find("img:first").attr("src", src);
    });
    
    $("#sidebar .subcr h2").next("div.content").each(function(i){
        if($(this).find("a:visible, strong").length == 0){
            $(this).prev("h2").hide();
            $(this).hide();
        }
        
    });
  
  /* Showing Calendat in Sidebar */
  var cal = $("#sidebar div.content iframe");
  if(cal.length>0){
    cal.parents("div.content").show().prev("h2").show();
  }
    
  setTimeout("fixSubmenuWidth()", 1);
  
  /* Social Bookmarks */
  	$("body").click(function(){
		  $("#bookmark-content").hide();
		});

	 $("a.share").click(function(){
     $(this).next("#bookmark-content").toggle();
     return false;
	 });
	 
	 
	 /* Tip a friend link */
	 
	 $("#actionsList a.send").click(function(){
	    
	    var w = window.open($(this).attr('href'), 'tipafriend', 'width=620,height=550,scrollbars=no,resizable=yes');
      w.focus();     
	    return false;
	    
	 });
	 
   if( $("#tip-to-friend").length>0){
     $("a.lnk_topPage").hide().prev("br").hide();
   }
   
   
   /* unesco.org homepage link in correct language */
   
   $("#siteName").next("p").find("a:contains(unesco.org)").click(function(){

     if(window.location.href.match(/unesco.org\/(\w\w)\//)==null){
       return true;
     }
     else{
       window.location.href = "http://"+location.host+ "/" + window.location.href.match(/unesco.org\/(\w\w)\//)[1] + "/"
       return false;
     }

   });
   
   /* Remove Arrow from file Links */
   //$("div.relatedContent ul li a[href*=pdf]").parent("li").css("backgroundImage", "none");
   $("body").append('<div id="unesco_gallery" style="display: none">'+
       '<a class="prev" style="flo">&laquo;</a>'+ 
       '<a class="next">&raquo;</a>'+ 
       '<div class="info"><br />'+
       '<img class="progress" src="fileadmin/unesco/images/ajax-loader.gif" />'+
   '</div>');
   if($(".photo-gallery .csc-textpic-imagecolumn a.lightbox").length>0){
   
     $(".photo-gallery .csc-textpic-imagecolumn a.lightbox").overlay({ 
        
         
         // each trigger uses the same overlay with the id "gallery" 
         target: '#unesco_gallery', 

         // optional exposing effect 
         expose: '#f1f1f1' 

     // let the gallery plugin do its magic! 
     }).gallery({ 
       
         autohide: false,
         // the plugin accepts its own set of configuration options 
         speed: 400 
     });
   }
   //Javascript Flash detection
   //http://www.featureblend.com/license.txt
   var FlashDetect=new function(){var self=this;self.installed=false;self.raw="";self.major=-1;self.minor=-1;self.revision=-1;self.revisionStr="";var activeXDetectRules=[{"name":"ShockwaveFlash.ShockwaveFlash.7","version":function(obj){return getActiveXVersion(obj);}},{"name":"ShockwaveFlash.ShockwaveFlash.6","version":function(obj){var version="6,0,21";try{obj.AllowScriptAccess="always";version=getActiveXVersion(obj);}catch(err){}
   return version;}},{"name":"ShockwaveFlash.ShockwaveFlash","version":function(obj){return getActiveXVersion(obj);}}];var getActiveXVersion=function(activeXObj){var version=-1;try{version=activeXObj.GetVariable("$version");}catch(err){}
   return version;};var getActiveXObject=function(name){var obj=-1;try{obj=new ActiveXObject(name);}catch(err){obj={activeXError:true};}
   return obj;};var parseActiveXVersion=function(str){var versionArray=str.split(",");return{"raw":str,"major":parseInt(versionArray[0].split(" ")[1],10),"minor":parseInt(versionArray[1],10),"revision":parseInt(versionArray[2],10),"revisionStr":versionArray[2]};};var parseStandardVersion=function(str){var descParts=str.split(/ +/);var majorMinor=descParts[2].split(/\./);var revisionStr=descParts[3];return{"raw":str,"major":parseInt(majorMinor[0],10),"minor":parseInt(majorMinor[1],10),"revisionStr":revisionStr,"revision":parseRevisionStrToInt(revisionStr)};};var parseRevisionStrToInt=function(str){return parseInt(str.replace(/[a-zA-Z]/g,""),10)||self.revision;};self.majorAtLeast=function(version){return self.major>=version;};self.minorAtLeast=function(version){return self.minor>=version;};self.revisionAtLeast=function(version){return self.revision>=version;};self.versionAtLeast=function(major){var properties=[self.major,self.minor,self.revision];var len=Math.min(properties.length,arguments.length);for(i=0;i<len;i++){if(properties[i]>=arguments[i]){if(i+1<len&&properties[i]==arguments[i]){continue;}else{return true;}}else{return false;}}};self.FlashDetect=function(){if(navigator.plugins&&navigator.plugins.length>0){var type='application/x-shockwave-flash';var mimeTypes=navigator.mimeTypes;if(mimeTypes&&mimeTypes[type]&&mimeTypes[type].enabledPlugin&&mimeTypes[type].enabledPlugin.description){var version=mimeTypes[type].enabledPlugin.description;var versionObj=parseStandardVersion(version);self.raw=versionObj.raw;self.major=versionObj.major;self.minor=versionObj.minor;self.revisionStr=versionObj.revisionStr;self.revision=versionObj.revision;self.installed=true;}}else if(navigator.appVersion.indexOf("Mac")==-1&&window.execScript){var version=-1;for(var i=0;i<activeXDetectRules.length&&version==-1;i++){var obj=getActiveXObject(activeXDetectRules[i].name);if(!obj.activeXError){self.installed=true;version=activeXDetectRules[i].version(obj);if(version!=-1){var versionObj=parseActiveXVersion(version);self.raw=versionObj.raw;self.major=versionObj.major;self.minor=versionObj.minor;self.revision=versionObj.revision;self.revisionStr=versionObj.revisionStr;}}}}}();};FlashDetect.JS_RELEASE="1.0.4";
   
   
  
  
  $(".flash-player").each(function(){
    
     if(FlashDetect.majorAtLeast(9)==false && navigator.platform != "iPad"){
        $(this).html('<b>This content requires Flash</b><p>To view this content, JavaScript must be enabled, and you need the latest version of the Adobe Flash Player.</p><p><a href="http://www.adobe.com/go/getflashplayer"><img src="fileadmin/unesco/images/get_flash_player.gif" alt="Download Adobe Flash Player" align="top" style="margin-right:5px" title="Download Adobe Flash Player"  border="0" />Click here to download the latest Flash Player.</a> </p>');
    }
    
  })
  
   
  });//document.ready
 


