/*
 * @file: ahold-ar.js
 * @ver : 3
 * @date : 10.03.2010:12:43 : ver 3 : Upldated some lightbox calls, also added one to be called on anchors with class 'lightit'
 * @date : 09.03.2010:18:36 : ver 2 : Added feature to add classes to popup window title
 * @date : 16.11.2009:14:54 : ver 1
 */

var evantimer;
$(document).ready(function() {
      
      UBar.init();          //initialise UtilityBar
      Accordion.init();     //initialise Accordion
      FontResizer.init();   //initialise FontResizer
      leftNavHeightAdjuster(); //adjust the leftnav's height
      ZoomIt.init();          // initialise the zooming box features, use class=''
	  Util.external();
	  Util.lightit(); 	//enable lightboxing of images
});

        /* sifr calls */
        //configure the object
        var sifrTGLight = { src: '/assets/sifr/sifr_TRADEGOTHICLIGHT.swf' };
        var sifrTGBold = { src: '/assets/sifr/sifr_TRADEGOTHICBOLD.swf' };
        sIFR.useStyleCheck = true; //this is a hack for safari/opera and adds a dummy <div class="sIFR-dummy"> at the bottom of the page

        //active
        //sIFR.activate(cochin, rockwell);
        sIFR.activate(sifrTGLight);
		sIFR.activate(sifrTGBold);



        //apply to the element
        sIFR.replace(sifrTGLight, {
          selector: 'h1',
          css: '.sIFR-root { background: transparent; color: #035791; font-weight:100; }',
          wmode:'transparent',
          ratios: [9, 1.16, 16, 1.09, 24, 1.06, 37, 1.04, 74, 1.02, 1.01]
        });
        

      
        sIFR.replace(sifrTGBold, {
          selector: '.highlight-fig p.large',
          css: '.sIFR-root { background: transparent; color: #ffffff; font-weight:100;  leading:-5; text-align: left; font-size: 40px; }',
		  tuneHeight: '-12',
          wmode:'transparent',
          ratios: [6, 1.66, 7, 1.49, 9, 1.37, 10, 1.24, 12, 1.2, 13, 1.13, 14, 1.1, 18, 1.08, 29, 1.05, 49, 1.03, 74, 1.02, 1.01]
        });
        
      


		 sIFR.replace(sifrTGBold, {
          selector: '.highlight-fig p.small',
          css: '.sIFR-root { background: transparent; color: #BAE3FF; font-weight:100;  leading:-5; text-align: left; font-size: 15px }',
          wmode:'transparent',
          ratios: [9, 1.16, 16, 1.09, 24, 1.06, 37, 1.04, 74, 1.02, 1.01]

        });

		 sIFR.replace(sifrTGBold, {
          selector: '.intro-quote-content p',
          css: '.sIFR-root { background: transparent; color: #a4a4a4; font-weight:normal; font-style:italic; text-align: left; font-size: 20px;}',
          wmode:'transparent',
          ratios: [9, 1.16, 16, 1.09, 24, 1.06, 37, 1.04, 74, 1.02, 1.01]

        });

		 
		
         sIFR.replace(sifrTGBold, {
          selector: '.accordion-content p.large-fig',
          css: '.sIFR-root { background: transparent; color: #035791; font-weight:normal;  leading:-5; text-align: left; font-size: 40px;  }',
		  tuneHeight: '-8',
          wmode:'transparent',
          ratios: [6, 1.41, 8, 1.31, 9, 1.19, 10, 1.14, 13, 1.11, 21, 1.07, 37, 1.04, 74, 1.02, 1.01]
        });

        

		 sIFR.replace(sifrTGBold, {
          selector: '.accordion-content p.small-fig',
          css: '.sIFR-root { background: transparent; color: #035791; font-weight:normal;  leading:-5; text-align: left; font-size: 13px;  }',
          wmode:'transparent',
           ratios: [9, 1.16, 16, 1.09, 24, 1.06, 37, 1.04, 74, 1.02, 1.01]
        });


    //Utilities Bar & Panel Object
    var UBar = {

                init: function(){

                    UBar.adjustUtilityLayerHeight('#utilitiesLayer');
                    UBar.enableUBarScroll('#utilitiesbar');
                    UBar.enableUtilityBarMousing('#utilitiesbar');
                    UBar.enableUtilityBarClicking();
                    
                    //on home page popup out the utility bar for once.
                    if($('#wallpaper.home-page').length > 0 ){
                       UBar.openUtilityBar("#utilitiesbar");
                       window.setTimeout(UBar.closeUtilityBar,5000);
                    }
                    
                    UBar.closePanel();

                   //enable ESC key for closing the panel and hiding the utility bar
                    $(document).keyup(function(event){
                        if (event.keyCode == 27) {
                           //alert('escaped!');
                            UBar. closeUtilityBar();
                            UBar.hideAllPanels();
                        }
                    });

                }, //init()



                // -------------------------------------------------------------------------
                // adjusts the height of the layer to the full height of the page
                // otherwise its only as tall as the visible area
                adjustUtilityLayerHeight: function(ULayerId){
                      var pageHeight = $(document).height() + 10;
                      $(ULayerId).css('height',pageHeight);
                },  //adjustUtilityLayerHeight()



                // -------------------------------------------------------------------------
                // enables page scroll detection
                // and adjustment of Ulitity bar & panels to the new top-right position
                enableUBarScroll : function(UBarId){

                    //get the curent top position of the utilities bar
                    var top = $(UBarId).offset().top;

                    var UBarElement = $(UBarId);
                    var UPanelElement = $("#utilitiesPanel");

                    //detect page scroll and
                    //scroll the utilitybar to the same top position
                    $(window).scroll(function (event) {

                        
                        // how much has the window been scrolled up/down
                        var y = $(this).scrollTop();
                        // add the pixels scrolled to current top position
                        var ntop = top+y;
                        // bring the utility bar to new top position ( top +- scroll )

                       UBarElement.stop().animate({'top':ntop},{duration:1000});            //adjust the bar on page scroll
                       UPanelElement.stop().animate({'top':ntop},{duration:1000}); //adjust the panel on page scroll

                    });

                }, //enableUBarScroll()


                closingTimer: 0,
                autoHidingFlag: true,

                // -------------------------------------------------------------------------
                // enables utilitybar animations on mouseover and mouseout
                enableUtilityBarMousing:function(UBarId){

                    //scroll out the utility bar on mouseover
                    $(UBarId).mouseover(function(){
                       window.clearTimeout(UBar.closingTimer);
                       UBar.openUtilityBar(UBarId);

                    });

                    //hidein the utility bar on mouseout
                    $(UBarId).mouseout(function(){
                       // console.log('closingTimer:'+UBar.closingTimer+typeof(UBar.closingTimer));
                           //when autohiding has not been disbaled
                           if(UBar.autoHidingFlag === true )     {
                                UBar.closingTimer =  window.setTimeout(UBar.closeUtilityBar,1000);
                           }
                    });

                },  //enableUtilityBarMousing()


                // -------------------------------------------------------------------------
                //Clears the timeout set for menu hiding, so that menu is not auto hidden
                disableUBarAutoHiding:function(){
                     window.clearTimeout(UBar.closingTimer);
                },


                // -------------------------------------------------------------------------
                // scrolls out (opens) the utilitiesbar, making both icons and text visible
                openUtilityBar: function(UBarId){
                   var marginright = $(UBarId).css('margin-right');
                   //console.log(marginright);
                   if(marginright === "-146px" ){
                        //bring it out
                        $(UBarId).animate({marginRight:'-1px'},{duration:500, easing:'easeOutBack'});
                    }
                },

               // -------------------------------------------------------------------------
               // scrolls in (closes) the utilitiesbar, leaves only the icons to be visible
                closeUtilityBar: function() {
                    $('#utilitiesbar').animate({marginRight:'-146px'},{duration:500, easing:'easeInBack'});
                },  //close UtilityBar()

                // -------------------------------------------------------------------------
                // handles clicks on various Utility Bar options
                enableUtilityBarClicking:function(){

                     $('#utilitiesbar li a').click(function(e){

                        var whichOption = $(this).parent().attr('class');
                        var whichPageInIframe = $(this).attr('href');
                        var panelWindowTitle = $(this).attr('title'); //if title specified, get the title
                        if (panelWindowTitle == ""){
                            panelWindowTitle = $(this).html(); //if no title specified, get the html text
                        }
                        //console.log(whichOption);

                       //close/hide any already open panel
                       UBar.hideAllPanels();

                       switch(whichOption){
                           case 'UBbuildReport':
                               UBar.showPageInPanel(whichPageInIframe,panelWindowTitle,'iconReport'); // use this when an iframe has tobe loaded in the panel
                               //UBar.showPanel('#idofSpecificPanelWindow'); - use this when a window within the same page is to be loaded
                               break;
                            case 'UBdownloads' :
                               //UBar.showPageInPanel(whichPageInIframe,panelWindowTitle);
                               UBar.showPageInPanel(whichPageInIframe,panelWindowTitle,'iconDownloads');
                               //UBar.showPanel('#downloadCenter');
                               break;
                            case 'UBcharting' :
                                UBar.showPageInPanel(whichPageInIframe,panelWindowTitle,'iconCharting');
                                break;
                            case 'UBbasket' :
                                UBar.showPageInPanel(whichPageInIframe,panelWindowTitle,'iconBasket');
                                //UBar.showPanel('#printBasket');
                                break;
                            case 'UBadd' :
                                UBar.showPageInPanel(whichPageInIframe,panelWindowTitle,'iconAdd');
                                break;
                            case 'UBprint':
                                window.print();
                                break;
                            case 'UBfeedback':
                                UBar.showPageInPanel(whichPageInIframe,panelWindowTitle,'iconFeedback');
                                //UBar.showPanel('#feedbackForm');
                                break;
                            case 'UBbookmark' :
                                UBar.Bookmark();
                                break;
                            case 'UBcompare':
                                UBar.showPageInPanel(whichPageInIframe,panelWindowTitle,'iconCompare');
                                //UBar.showPanel('#comparison');
                                break;
                           default:
                               break; 
                       }//click

                        e.preventDefault();
                        return false;

                     })

              }, //enableUtilityBarClicking()

              showChartingTool:function(){
                    UBar.showPanel('#chartingTool');
              }, // showChartingTool()

              showFeedbackForm:function(){
                    UBar.showPanel('#feedbackForm');
              }, //showFeedbackForm


              // -------------------------------------------------------------------------
              // Bookmarks the pages in IE/FF
              // version 1.271109,
              // status: works fine in IE6, IE8, FF3.5.0, Safari 4+, Opera10+
              Bookmark: function(){

                     var title= document.title;
                     var url = location.href;

                     if(window.external && document.all) { // IE
                             ptitle = '"'+document.title+'"'; //becuase IE needs quotes
                             window.external.AddFavorite(url,ptitle);
                     }else {
                         if(window.sidebar.addPanel){ // Firefox
                                    window.sidebar.addPanel(title, url, '');
                         }else{ //unsupported browsers
                                    alert('Please press \'CTRL+D\' to bookmark this page in your browser.');
                         }
                     }
              }, //Bookmark


              //UtilityPanels related functions

              // -------------------------------------------------------------------------
              //accepts the id of the panel to show
              //shows it
              showPanel:function(panelId){
                  // console.log('nnnnclosingTimer:'+UBar.closingTimer+typeof(UBar.closingTimer));

                   //disable UtilityBar autohiding/set it to false
                   UBar.autoHidingFlag = false
                    window.clearTimeout(UBar.closingTimer); //disable already set times

                   //hide all the open panels
                    //UBar.hideAllPanels();

                    //enable the shadow layer
                    UBar.showShadowLayer();
                    $('#utilitiesLayer').show();//makes the panels layer visible
                    //show the panel window
                    $(panelId).show();
                    pngfix();
                    

              },//  showPanel

              // -------------------------------------------------------------------------
              //Makes the panel visible and loads the page specified in a URL
              //parameter: url of the page to load in an iframe in the panel
              showPageInPanel:function(pageURL,pageTitle,iconClass){
                  // console.log('nnnnclosingTimer:'+UBar.closingTimer+typeof(UBar.closingTimer));

                    //remove the existing icon class if it exists
                     var lastIconKlass =  $('#panelTitle').attr('class');
                     if(lastIconKlass != 'undefined' ){
                            $('#panelTitle').removeClass(lastIconKlass);
                     }

                     //add the new icon class if supplied
                     if( typeof(iconClass)!= 'undefined' ){
                            $('#panelTitle').addClass(iconClass);
                     }

			  
				  
                    if(pageTitle){
                            //if any title has been specified in the title to the page, display that title, otherwise display default 'Ahold'
                            $('#panelTitle').html(pageTitle);
                    }else{
                            $('#panelTitle').html('Ahold'); // This is needed as the title is modified multiple times by other Utility bar options
                    }

                    //disable UtilityBar autohiding/set it to false
                    UBar.autoHidingFlag = false
                    window.clearTimeout(UBar.closingTimer); //disable already set times

                    //enable the shadow layer
                    //alert('begin shadowing');
                    UBar.showShadowLayer();

                    //show the panel window
                    //alert('loading iframe');
                    $('#panelIframe').attr({'src':pageURL}); //set the page in the panel
                    //alert('show utilities layer');
                    $('#utilitiesLayer').show();  //makes the panels layer visible
                    //alert('showing standard panel');
                    $('#standardPanel ').show(); //show the relevant panel

              },//  showPanel

              // -------------------------------------------------------------------------
              //Hides the panel and does some cleanups
              closePanel:function(){
                        $('#utilitiesPanel .closePanel a').click(function(e){
                            //$('#utilitiesPanel .panel').css({'visibility':'hidden'});
                            UBar.hideAllPanels();// $('#utilitiesPanel .panel').hide();
                            $('#panelIframe').attr({'src':'/blank.html'});
                            //close the utility bar
                            UBar.closeUtilityBar();
                            e.preventDefault();
                            return false;

                        });
              },// hidePanels
              // -------------------------------------------------------------------------
              //simply hides all the panels
              hideAllPanels: function()  {
                  $('#utilitiesPanel .panel').hide();
                  $('#utilitiesLayer').hide();
                  UBar.autoHidingFlag = true; //re-enable auto hiding

                  //hide the shadowwindow
                    UBar.hideShadowLayer();
              },


                // -------------------------------------------------------------------------
                // add the shadowLayer to the page, if it does not exist
                // fade it to 20% opacity
                showShadowLayer: function(){
                      if( $('#shadowLayer').length == 0 ){
                            var pageHeight = $(document).height() + 10;
                            //$('#shadowLayer').css('height',pageHeight);

                           //var elem = '<div id="shadowLayer" style="height:'+pageHeight+'px; display:none; ">.</div>';
                           // var elem = "<div id='shadowLayer' style='height:"+pageHeight+"px; display:block; position:fixed '>.</div>";
                           // var elem = '<div id="shadowLayer" style="height:'+pageHeight+'px; display:block; position:fixed">&nbsp;</div>';
                           // var elem = '<div id="shadowLayer" style="height:100%;display:block;">&nbsp;</div>';
                           // var elem = "<div id='shadowLayer' style='height:100%; width:100%'>&nbsp;</div>";
                           // var elem = "<div id='shadowLayer'>.</div>";
                            
                            //alert('after height adjustmet');
                           // $('body').prepend(elem);
                           // $('#shadowLayer').css('background-color','#f00');
                           // alert('s layer added');
                           
                          // $('#shadowLayer').fadeTo(0,0.2).show();
                            // adjust the shadow layer to cover the whole page ( including the invisible part )
                            
                            var elem = '<div id="shadowLayer">&nbsp;</div>'
                            $('body').append(elem);
                            $('#shadowLayer').css('height',pageHeight).show();

                       }else{
                           ///alert('shadowing');
                          // $('#shadowLayer').show();
                           //$('#shadowLayer').fadeTo('fast',0.2);
                          // $('#shadowLayer').css('height', pageHeight).show();
                         // $('#shadowLayer').css('height', pageHeight);
                          $('#shadowLayer').show();
                          //$('#shadowLayer').fadeTo('fast',0.2);
                       }
                      // $('#shadowLayer').fadeTo('slow',0.5)
                }, //showShadowLayer()


                // -------------------------------------------------------------------------
                //fade the shadwLayer to 0% opacity
                hideShadowLayer: function(){
                       // $('#shadowLayer').fadeTo('fast',0);
                        $('#shadowLayer').hide(); 
                     //$('#shadowLayer').fadeOut('fast');

                } //hideShadowLayer()

        };//UBar



        //Accordion functions

        var Accordion = {

                init:function(){

                    // Assign event listener to accorion title/header clicks
                     $('.accordion li h2').click(function(e){

                            var contentBoxClass = $(this).next().attr('class');
                            if(contentBoxClass == "accordion-content"){ // if accordion-content element exists
                                   if($(this).parent().hasClass('open')){ //if it is already open, close it
                                       Accordion.closeItem($(this));
                                   }else{ //if closed, open it
                                       Accordion.openItem($(this));
                                   }
                            }//if


                     });//

                },

                //closes only the supplied accordion item
                //pass the header element
                closeItem:function(elem){
                    elem.parent().removeClass('open');//change the style of the container list item
                   

                }, //closeItem

                //opens only the supplied accordion item
                //pass the header element
                openItem:function(elem){
                    elem.parent().addClass('open'); // change the style of the container list item
                }//openItem



        }//Accordion




            /*
             * font resizing related functions
             * requires: cookie functions
             * ------------------------------------------------------------------------
             */

            var FontResizer = {

                init: function(){
                    FontResizer.loadLastFontSize(); //on page load, load the last fontsize
                    FontResizer.fontBarClicker();   //listen to clicks on fontsize changer
                },

                //load the last-set font size
                loadLastFontSize: function() {
                    var size;

                    size = readCookie('AholdReportFontSize'); //read the size cookie
                    if (size == null) {
                        size = 0;
                    }

                    FontResizer.setFontSize(size);  //set the font size to cookie value
                },//loadLastFontSize();

                //accepts values : 0,1,2
                //sets the relevant font class to the body element
                setFontSize: function(size){
                    switch (size) {
                        case 0:
                        case "0":
                           FontResizer.reClassBody('zx');
                            break;
                        case 1:
                        case "1":
                           FontResizer.reClassBody('zxl');
                            break;
                        case 2:
                        case "2":
                            FontResizer.reClassBody('zxxl');
                            break;
                    } //switch

                },//setFontSize()

                // adds class to page body
                reClassBody: function (newClass){
                        $('body').removeClass('zx zxl zxxl');
                        $('body').addClass(newClass);
                },



                //enables click events
                fontBarClicker:function(){
                     $('#fontSizeLinks .small').click(function(e) {
                         FontResizer.changeToFontSize(0);
                         e.preventDefault();
                         return false;
                     });//click small

                     $('#fontSizeLinks .medium').click(function(e) {
                           FontResizer.changeToFontSize(1);
                           e.preventDefault();
                           return false;
                     });//click medium

                     $('#fontSizeLinks .large').click(function(e) {
                            FontResizer.changeToFontSize(2);
                            e.preventDefault();
                            return false;
                     });//click large

                }, //fontbarClicker();

                //changes the font-size on the page and sets the cookie
                changeToFontSize: function(n){
                            if(typeof n == 'undefined'){
                                n = 0; // set to zero if no font size supplied otherwise it is 'undefined'
                            }

                            FontResizer.setFontSize(n);
                            createCookie('AholdReportFontSize', n);
                            return
                }//changeToFontSize()


            } //FontResizer

            /*
             *  cookie function
             *  functions to create, read, erase cookies
             *  Ref : http://www.quirksmode.org/js/cookies.html
            */

            function createCookie(name, value, days) {
                if (days) {
                    var date = new Date();
                    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
                    var expires = "; expires=" + date.toGMTString();
                }else{
                     var expires = "";
                }
                document.cookie = name + "=" + value + expires + "; path=/";
            }

            function readCookie(name) {
                var nameEQ = name + "=";
                var ca = document.cookie.split(';');
                for (var i = 0; i < ca.length; i++) {
                    var c = ca[i];
                    while (c.charAt(0) == ' ') c = c.substring(1, c.length);
                    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
                }
                return null;
            }


            // font resizing related functions end -----------------------------------------------


            function leftNavHeightAdjuster(){

                //get the primary content container height
                var pcHeight = $('#primary-content').height();

                //current leftnav height
                var currentLeftNavHeight =  $('#leftnav').height();
                var adjustedLNH = currentLeftNavHeight + 20; // adjustedLeftNavHeight

                //change the leftnav height only when it is smaller than the primary-content container
                if(pcHeight > adjustedLNH){
                       var newLeftNavHeight = pcHeight - 20 // 13+13 as the rounded corners at top and bottom, - 6 pixels for adjustments
                        //alert(newLeftNavHeight);
                        $('#leftnav').height(newLeftNavHeight);
                }


            }//leftNavHeightAdjuster()



            function leftNavHeightAdjuster111(){

                //get the primary content container height
                //var pcHeight = $('#primary-content').height();
                var pcHeight = document.getElementById('primary-content').offsetHeight;

                //alert(pcHeight);
                //current leftnav height
                var currentSidebarHeight =  $('#sidebar').height();

                //change the leftnav height only when it is smaller than the primary-content container
                if(pcHeight > currentSidebarHeight){
                    $('#sidebar').height(pcHeight);
                    $('#leftnav').height(pcHeight-30);
                }

            }//leftNavHeightAdjuster()


            //ZoomIt functions
            var ZoomIt = {

                init:function(){

                    $('.zoomit').click(function(e){
                        var boxToShow = $(this).attr('href');
                        ZoomIt.showInCenteredPanel(boxToShow);
                    });
                    ZoomIt.activateCloseButton();

                }, //init()

                activateCloseButton: function(){
                    $('#zoomPanelsLayer .closePanel a').click(function(e){
                        ZoomIt.hideZoomedBoxes();
                        e.preventDefault();
                        return false;
                    });
                },

                showInCenteredPanel:function(BoxToShow){
                    //alert(BoxToShow);
                    if( $(BoxToShow).length > 0 ){

                           if( $('#shadowLayer').length == 0 ){
                                var elem = '<div id="shadowLayer">&nbsp;</div>'
                                $('body').append(elem);
                           }
                           $('#shadowLayer').show();
                           $('#zoomPanelsLayer').show();
                           $(BoxToShow).show();
                    }

                }, // showInCenteredPanel()

                hideZoomedBoxes:function(){
                     $('#zoomPanelsLayer .panel').hide();
                     $('#zoomPanelsLayer').hide();
                     $('#shadowLayer').css('height','100%').hide();

                }  //hideZoomedBox

            }//ZoomIt
			
			//miscellanoes utilities
			var Util = {
			
				/**
				 * function that opens links with class name in a new window
				 * Instead of going straight to that page.
				 */
				external: function(){
					
					$("a.external_link,a.external").click(function(e){

						exiturl = "/misc/lbsiteexit?link="+$(this).attr('href');

						UBar.showPageInPanel(exiturl,'Site Exit','siteExit');
						e.preventDefault();
						
				      });
				
					$("a.notes_link").click(function(e){
						orig_url = $(this).attr('href');
						if(orig_url.indexOf("?") > 0) {
							notelink = orig_url+"&hide=1";
						} else {
							notelink = orig_url+"?hide=1";
						}
						
						if(window.top==window) {
							UBar.showPageInPanel(notelink,'Notes to financial statements','iconDefault');
							e.preventDefault();
						} else {
							$(this).attr('target',"_top");
							//$(this).attr('href',notelink);
							//alert(notelink);
							//alert(document.location);
							//window.location = notelink;
//							document.location = notelink;
//							e.preventDefault;

						}
						
				      });
				
				},//external
				lightit:function(){
					$("a.lightit").click(function(e){
						loadUrl = $(this).attr('href');
						if(typeof(loadUrl) != 'undefined' ){
							UBar.showPageInPanel(loadUrl,'Ahold','iconDefault');
						}
						e.preventDefault();
					});
				
				}//lightit
				
			
			}