/*

13twelve vs. jQuery

This javascript is the main javascript for the sites actions.

*/

// --------------------------------------------------------------------------------------------------------------

var sustainability = function(){
  function browserTest() {
    /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ some simple browser testing */
    // are we on a Mac ?
    if (navigator.appVersion.indexOf("Mac")!=-1) {
      isMac = true;
      $('body').addClass("isMac");
    }
    function searchVersion(browser) {
      var dataString = navigator.userAgent;
      var index = dataString.indexOf(browser);
      if (index == -1) return;
      var bVersion = parseFloat(dataString.substring(index+browser.length+1));
      if (browser = "Firefox") {
        return bVersion.toString();
      } else {
        return bVersion.toString().split(".")[0];
      }
    }
    // Webkit
    isWebkit = jQuery.browser.safari;
    if (isWebkit) {
      $('body').addClass("isWebkit");
    }
    // Mozilla versioning
    isMozilla = jQuery.browser.mozilla;
    if (isMozilla) {
      $('body').addClass("isMozilla");
      version = searchVersion("Firefox") || "";
      version = version.replace(".","-");
      $('body').addClass("isMozilla"+version);
    }
    // IE versioning
    isIE = jQuery.browser.msie;
    if (isIE) {	
      version = searchVersion("MSIE") || "";
      isIE6 = (version == 6) ? true : false;
      if (isIE6) {
        ie6Helpers();
      }
    }
  }
  function replaceFonts() {
    // Cufon.replace('.fR1, .fR2', { fontFamily: 'Sabon Cufon', hover: true });
    Cufon.replace('.fR3', { fontFamily: 'Whitney Cufon' });
    Cufon.CSS.ready(function() {
      if (jQuery.browser.safari) {
        $(".fR1").each(function(){
          var h = $(this).height();
          if ( (h % 50) != 0) {
            h = Math.floor(h/50);
            $(this).find(".cufon").css("margin-top","2px");
          }
        });
      }
    });
  }
  function defaultValues() {
    // take off the default values in the sitewide search and newsletter forms
    $('#header input[type="text"], #footer input[type="text"]').each(function(){
      var initVal = $(this).val();
      //
      $(this).focus(function(){
        $(this).val("");
      });
      $(this).blur(function(){
        if ($(this).val() == "") {
          $(this).val(initVal);
        }
      });
    });

  }
  function slider(sliderContainer, sliderInner, slideAmount, itemsVisible, currentSet, budge, looping, automate, interval) {
    // set up
    var sliderContainer = sliderContainer || false; // the container to all this
    var sliderInner = sliderInner || false; // what you actually want to slide
    var slideAmount = slideAmount || false; // how much to slide the slider by
    var itemsVisible = itemsVisible || false; // how many items you can see at one go
    var currentSet = currentSet || 1; // start at the begining or half way through (not full tested 28/06/10)
    var budge = budge || 0; // budge one way or another, useful for lining up with paddings/margins/spacings
    var looping = looping || false; // at the end of the sequence, stop? or go back ground
    var automate = automate || false; // auto page? if true, will set looping to true
    var interval = interval || 5; // seconds

    if (sliderContainer && sliderInner && slideAmount && itemsVisible) {

      // house keeping
      var currentSliderPos = 0;
      var paginator = sliderContainer.parent().find("ul[class*=paginator]");
      var nextBtn = paginator.find("li.next a");
      var prevBtn = paginator.find("li.prev a");
      var maxSet = Math.ceil(sliderInner.children().length/itemsVisible);
      var reset = false; // controlled by the function for resetting the loop
      var timer = "";
      var hovering = false;
      // bubble
      var sliderMoving = false;

      // set up
      if (automate) {
        looping = true;
      }
      interval = interval * 1000;
      if (looping) {
        sliderInner.find("li:first").clone().appendTo(sliderInner);
        sliderInner.find("li:last").prev().clone().prependTo(sliderInner);
        budge = budge - slideAmount;
      }
      currentSliderPos = budge + ((currentSet - 1) * slideAmount * -1);
      sliderInner.css({ left: currentSliderPos });

      // the slider functions
      function moveSlider(direction) {
        if (!sliderMoving) {
          calculateNextPosition(direction);
          sliderMoving = true;
          sliderInner.animate({
            left: currentSliderPos
          }, 500, function(){
            if (reset) {
              currentSliderPos = budge + ((currentSet-1) * slideAmount * -1);
              sliderInner.css({ left: currentSliderPos });
            }
            sliderMoving = false;
            if (!hovering) {
              auto();
            }
          });
          updatePaginator();
        }
      }
      // calculate the next position of the slider
      function calculateNextPosition(direction) {
        if(direction == 'right') {
          if (looping && currentSet == maxSet) {
            currentSliderPos -= slideAmount;
            reset = true;
            currentSet = 1;
          } else {
            currentSliderPos -= slideAmount;
            currentSet++;
          }
        } else if (direction == 'left') {
          if (looping && currentSet == 1) {
            currentSliderPos += slideAmount;
            reset = true;
            currentSet = maxSet;
          } else {
            currentSliderPos += slideAmount;
            currentSet--;
          }
        } else {
          currentSliderPos = budge + ((direction-1) * slideAmount * -1);
          currentSet = direction;
        }
      }

      // update paginator links
      function updatePaginator() {
        if (!looping) {
          if(currentSet == 1) {
            prevBtn.addClass("disabled");
            nextBtn.removeClass("disabled");
          } else if (currentSet == maxSet) {
            nextBtn.addClass("disabled");
            prevBtn.removeClass("disabled");
          } else {
            nextBtn.removeClass("disabled");
            prevBtn.removeClass("disabled");
          }
        }
        paginator.find("li.current").removeClass("current");
        paginator.find("li").eq(currentSet-1).addClass("current");
      }

      function auto() {
        if (automate) {
          // if we're automating..
          clearTimeout(timer); // clear the timeout var, so it doesn't bubble itself into a mess
          timer = setTimeout(openNext, interval); // set the timer again
        }
      }

      function openNext() {
        moveSlider('right');
      }

      function setUpPaginator() {
        if (currentSet == 1 && maxSet == 1) {
          nextBtn.hide();
          prevBtn.hide();
          paginator.hide();
        } else {
          var pages = "";
          for (i=0;i<maxSet;i++) {
            pages = pages + '<li><a href="#">'+(i+1)+'</a></li>';
          }
          paginator.prepend(pages);
          updatePaginator();
          timer = setTimeout(auto, 50); // set the automatic swap happening

          // add some events to the slider buttons
          paginator.find("li a").click(function(e){
            e.preventDefault();
            var index = paginator.find("li a").index(this);
            if (index < maxSet && !$(this).parent().hasClass("current")) {
              moveSlider(index+1);
            }
          });
          prevBtn.click(function(e){
            e.preventDefault();
            if (looping) {
              moveSlider('left');
            } else {
              if(!$(this).hasClass("disabled")) {
                moveSlider('left');
              }
            }
          });
          nextBtn.click(function(e){
            e.preventDefault();
            if (looping) {
              moveSlider('right');
            } else {
              if(!$(this).hasClass("disabled")) {
                moveSlider('right');
              }
            }
          });
          sliderContainer.hover(function() {
            // if you hover over an Li, say your reading the content, it stops the automatic transition
            clearTimeout(timer);
            hovering = true;
          }, function() {
            // and restarts it when you roll out
            auto();
            hovering = false;
          });
        }
      }

      setUpPaginator();
    }
  }
  function refineBy() {
    $(".refine").each(function(){
      // store a few things
      var $this = $(this);
      var subLists = $(this).find("ul");
      var subListItems = subLists.find("li");
      // get an initial height
      var startHeight = $this.find("li:nth-child(2)").height();
      // and begin setting up to store the final heights - we want a smooth animation!
      var endHeights = [];
      // whats open? nothing yet!
      var currentOpen = false;
      // stop bubbling
      var animating = false;
      var sidebar_animating = false;
      // is there a tags list?
      var tagsListExists = ($(".col-170 .tags").length > 0) ? true : false;
      var tags = tagsListExists ? $(".col-170 .tags:first") : null;
      //
      var target = $("#ajax_target"); // the list where we're putting the content
      var sidebar_target = $("#sidebar_ajax_target"); // the sidebar where we're putting the content
      var paginator = null; // will be set to something shortly

      var defaultSidebar = true;

      // change the css a bit so we can make the lists draw and measure their heights
      $this.find("li:not(:first-child)").not("li li").height(startHeight).css("overflow","hidden");
      subLists.show();
      subLists.each(function(index){
        endHeights[index] = $(this).height() + startHeight + 1;
      });

      // insert a blank paginator if there isn't one
      if (($("#paginator").length < 1)) {
        $('<div id="paginator" class="paginator" style="display: none;" />').insertAfter(target);
      }
      paginator = $("#paginator");

      var checkForInitial = function(){
        if ($this.find("li.current").length >= 1) {
            
          var isType = false;
          var $current = $this.find("li.current:first");
          $clicked = $current.parent().parent().find("a:first");
          $clicked.parent().animate({
            height: endHeights[ $this.find("li a").not("li li a").index($clicked) - 1] +"px"
          }, 200, function(){
            currentOpen = $clicked.parent();
            currentOpen.addClass("current");
            
            if(currentOpen.find('a:first').attr('rel') == 'type') isType = true;
            if(isType == false) $('.col-790.bg-chevrons').addClass("refined");
            
            if($('.col-790.bg-chevrons').hasClass("refined")) {
              titleRefined.replaceWith('<div class="refined-by"><p>' + text + '</p></div>');
            }
          });
          
          $this.addClass("active");
          
          
          
          // init classes and blocks
          var titleRefined = $('h3:first', $('#sidebar_ajax_target'));
          var text = titleRefined.text();
          
          
          
          $("a.close").addClass("sidebar");
          
          txt = $('#sustainability').hasClass('library') ? 'Loading related blog items' : 'Loading related library items';
          var txt = '<span class="loading sidebar_loading_txt" style="display:none">' + txt + '</span>';
          sidebar_target.after(txt);
          
          
          
          var resultsLength = $("#ajax_target > li").length;
          if (resultsLength == 0) {
            target.append('<li style="padding: 0; margin: 0 0 20px 0; position: static;"><p>Sorry, no results found.</p></li>');
          }
          if ($("#paginator .prev").length > 0) {
            var paginatorTotalPages = $("#paginator .prev").attr("rel");
            if (paginatorTotalPages != null && paginatorTotalPages != undefined && paginatorTotalPages != "" && paginatorTotalPages > resultsLength) {
              resultsLength = paginatorTotalPages;
            }
          }
          showFilterBar($current.find("a:first").html(), resultsLength);
        } else {
          if ($(".col-170 .tags:first li.current").length >= 1) {
            $current = $(".col-170 .tags:first li.current:first");
            $this.addClass("active"); $('.col-790.bg-chevrons').addClass("refined");
            var resultsLength = $("#ajax_target > li").length;
            
            // init classes and blocks
            var titleRefined = $('h3:first', $('#sidebar_ajax_target'));
            var text = titleRefined.text();
            titleRefined.replaceWith('<div class="refined-by"><p>' + text + '</p></div>');
            $("a.close").addClass("sidebar");

            txt = $('#sustainability').hasClass('library') ? 'Loading related blog items' : 'Loading related library items';
            var txt = '<span class="loading sidebar_loading_txt" style="display:none">' + txt + '</span>';
            sidebar_target.after(txt);
            
            if (resultsLength == 0) {
              target.append('<li style="padding: 0; margin: 0 0 20px 0; position: static;"><p>Sorry, no results found.</p></li>');
            }
            if ($("#paginator .prev").length > 0) {
              var paginatorTotalPages = $("#paginator .prev").attr("rel");
              if (paginatorTotalPages != null && paginatorTotalPages != undefined && paginatorTotalPages != "" && paginatorTotalPages > resultsLength) {
                resultsLength = paginatorTotalPages;
              }
            }
            showFilterBar($current.find("a:first").html(), resultsLength);
          } else {
            $this.removeClass("active");
          }
          $this.find("li.current").removeClass("current");
        }
        }();

        function showFilterBar(filter,results) {
          if (filter.indexOf("<span>")) {
            filter = filter.replace(/<span>.*<\/span>/, "")
          }
          var insertBeforeEl = ($('#sustainability').hasClass('clients-listing')) ? $("#ajax_target").prev("h3") : $("#ajax_target");
          
          var htmlStr = '<p><strong class="hide">Refined by </strong>'+filter+' (<span>'+results+'</span> results)</p>';
          if($("#refined-by").length > 0) {
            $("#refined-by").html(htmlStr).fadeIn(200);
          } else {
            $('<div class="refined-by" id="refined-by" style="display: none;" />').insertBefore(insertBeforeEl);
            $("#refined-by").html(htmlStr).fadeIn(200);
          }
        }

        function doSidebarAjax(el, show_box) {
          if($("#sidebar_ajax_target").length > 0 && !sidebar_animating) {
            var href = (el == "reset") ? window.location.toString() : $(el).attr("href");
            var filter = $(el).html(),
            sidebar_target_parent = sidebar_target.parent(),
            sidebar_loading_txt = $('.sidebar_loading_txt'),
            txt = $('#sustainability').hasClass('library') ? 'Loading related blog items' : 'Loading related library items';
            if (href != "#" && href != undefined && href != null) {
              sidebar_target.empty();
              sidebar_animating = true;
              if (!sidebar_target.hasClass('loading')) {
                if (sidebar_loading_txt.length == 0 ) {
                  var txt = '<span class="loading sidebar_loading_txt">' + txt + '</span>';
                  sidebar_target.after(txt);
                } else {
                  if (!$(el).hasClass('close')) 
                  sidebar_loading_txt.show();
                }

                //sidebar_target.addClass('loading');
              }

              // fade out the list
              sidebar_target.animate({
                opacity: 1
              }, 200, function(){
                // do an ajax load to refresh the list
                sidebar_target.load(href+"?sidebar=true", function(responseText,textStatus,XMLHttpRequest) {
                  if (textStatus != "success") {
                    // failed? fall back!
                    window.location = href;
                  } else {
                    // bring everything back in again (and reset the bubble var)
                    //sidebar_target.removeClass('loading'); 
                    $('.sidebar_loading_txt').fadeOut('fast');
                    sidebar_target.animate({ opacity: 1 }, 200, function() { 
                      animating = false;
                      if($(".refine").hasClass('active') == false) {
                        replaceFonts(); 
                      }
                    });
                  }
                  sidebar_animating = false;
                });
              });
            }
          }
        }

        function doAjax(el, show_box) {
          // ajax function
          if($("#ajax_target").length > 0 && !animating) {
            // set up some vars for this request
            var href = (el == "reset") ? window.location.toString() : $(el).attr("href");
            var filter = $(el).html();
            var target_parent = target.parent(), loading_txt = $('.loading_txt');
            var resultsLength = 0;
            
            if($('#sustainability').hasClass('library')) var txt = 'Loading library items';
            else if($('#sustainability').hasClass('casestudies')) var txt = 'Loading case studies';
            else var txt = 'Loading blog items';
            //
            // does a href exist?
            if (href != "#" && href != undefined && href != null) {
              // set the bubbling to true so no more can happen
              animating = true;
              // fade out the refined by bar
              if ($("#refined-by").is(":visible")) {
                $("#refined-by").fadeOut(200);
              }
              // fade out the paginator if it exists
              if (paginator.is(":visible")) {
                paginator.fadeOut(200);
              }


              if (!target_parent.hasClass('loading')) {

                if (loading_txt.length == 0 ) {
                  var txt = '<span class="loading loading_txt">' + txt + '</span>';
                  if($('.casestudies-listing').length > 0) target.after(txt);
                  else target_parent.after(txt);
                } else {
                  if ($(el).hasClass('close')) loading_txt.addClass('loading_reset'); else loading_txt.removeClass('loading_reset');
                  loading_txt.fadeIn('fast');
                }
              }

              // fade out the list
              target.animate({
                opacity: 0
              }, 200, function(){
                // do an ajax load for the paginator
                paginator.load(href+" #paginator > li", function(responseText,textStatus,XMLHttpRequest) {
                  // failed? fall back!
                  if (textStatus != "success") { window.location = href; }
                });

                // do an ajax load to refresh the list
                target.load(href+" #ajax_target > li", function(responseText,textStatus,XMLHttpRequest) {
                  if (textStatus != "success") {
                    // failed? fall back!
                    window.location = href;
                  } else {
                    // look at the length of the list
                    resultsLength = $("#ajax_target > li").length;
                    // if non, say sorry
                    if (resultsLength == 0) {
                      if ( !$('#sustainability').hasClass('clients-listing') ) {
                        target.append('<li style="padding: 0; margin: 0 0 20px 0; position: static;"><p>Sorry, no results found.</p></li>');
                      }
                    } else {
                      if ( $('#sustainability').hasClass('clients-listing') ) {
                        target.prev("h3").animate({
                          opacity: 1
                        }, 200);
                      }
                    }
                    // tags and resetting doesnt show the filter bar
                    // we want the number in the refine bar to be the amount of LI's in the list
                    // or the total number of things if its larger
                    if (show_box) {
                      // check the paginator has any content
                      if ($("#paginator .prev").length > 0) {
                        // if so read the rel of the first li to get the total pages (added by the app)
                        var paginatorTotalPages = $("#paginator .prev").attr("rel");
                        // if it exists and is bigger than the amount of li's in the main list, use that
                        if (paginatorTotalPages != null && paginatorTotalPages != undefined && paginatorTotalPages != "" && paginatorTotalPages > resultsLength) {
                          resultsLength = paginatorTotalPages;
                        }
                      }
                      // fade in the filter bar
                      showFilterBar(filter,resultsLength);
                    }
                    // bring everything back in again (and reset the bubble var)
                    $('.loading_txt').hide();
                    //target_parent.removeClass('loading'); 
                    target.animate({ opacity: 1 }, 200, function() { animating = false;  });
                    if ($("#paginator > li").length > 0) {
                      paginator.fadeIn(200);
                    }
                    setMinHeights();
                    
                    var script = 'http://s7.addthis.com/js/250/addthis_widget.js?username=sustainabilityadmin&domready=1';
                    if ( window.addthis )  window.addthis = null;
                    $.getScript( script );
                    
                    if ( $('#sustainability').hasClass('clients-listing') ) {
                      sustainabilityClients(href,resultsLength);
                    }
                  }
                });
              });
              if ( $('#sustainability').hasClass('clients-listing') && $('#ajax_target_2').length > 0 ) {
                $('#ajax_target_2').animate({
                  opacity: 0
                }, 200);
                $('#ajax_target_2').prev("h3").animate({
                  opacity: 0
                }, 200);
                $('#ajax_target').prev("h3").animate({
                  opacity: 0
                }, 200);
              }
            } else {
              // no href, fall back
              window.location = href;
            }
          }
        }
        
        function sustainabilityClients(href,resultsCount) {
          if ($('#ajax_target_2').length > 0) {
            var target_2 = $("#ajax_target_2");
            target_2.load(href+" #ajax_target_2 > li", function(responseText,textStatus,XMLHttpRequest) {
              if (textStatus != "success") {
                // failed? fall back!
                window.location = href;
              } else {
                // look at the length of the list
                var resultsLength_2 = $("#ajax_target_2 > li").length;
                // if non, fade h3 out
                if (resultsLength_2 != 0) {
                  target_2.prev("h3").animate({
                    opacity: 1
                  }, 200);
                }
                target_2.animate({ opacity: 1 }, 200, function() { 
                  if(isIE) $(this).get(0).style.removeAttribute('filter');
                });
                resultsLength_2 += resultsCount;
                $("#refined-by span").text( resultsLength_2 );
                setMinHeights();    
              }
            });
          }
        }


        // btn clicks
        // selecting a filter
        $this.find("li ul li a").click(function(event){
          event.preventDefault();
          event.stopPropagation();
          // clear classes from everywhere and set new current classes
          if (tags) {
            tags.find("li.current").removeClass("current");
          }
          subListItems.removeClass("current");
          $(this).parent().addClass("current");
          $this.addClass("active"); 
          /* if different from type filter */
          var isType = false;
          if ($(this).parents('.refine').find('li.current').children().eq(0).text() != 'Type') {
            isType = true;
            $('.col-790.bg-chevrons').addClass("refined");
          }
          // ajax function
          doAjax($(this), true);
          if ($(this).hasClass("sidebar")) {
            doSidebarAjax($(this), true);
            defaultSidebar = false;
          } else {
            if (!defaultSidebar && !isType) {
              doSidebarAjax($(this), true);
            }
            defaultSidebar = true;
          }
        });

        // selecting a type of filter
        $this.find("li a:not(.close)").not("li li a").click(function(event){
          event.preventDefault();
          event.stopPropagation();
          // store which was clicked
          $clicked = $(this);

          if (currentOpen != false && !$clicked.parent().hasClass("current")) {
            // if something open and not the same one clicked, close the current one and open the next
            currentOpen.animate({
              height: startHeight+"px"
            }, 200, function(){

              $clicked.parent().animate({
                height: endHeights[ $this.find("li a").not("li li a").index($clicked) - 1] +"px"
              }, 200, function(){
                currentOpen = $clicked.parent();
              });

            });
            // house keeping of the classes
            $clicked.parent().siblings().removeClass("current");
            $clicked.parent().addClass("current");
          } else if (!$clicked.parent().hasClass("current")) {
            // if none open, open the clicked one up
            $clicked.parent().animate({
              height: endHeights[ $this.find("li a").not("li li a").index($clicked) - 1] +"px"
            }, 200, function(){
              currentOpen = $clicked.parent();
            });
            // house keeping of the classes
            $clicked.parent().siblings().removeClass("current");
            $clicked.parent().addClass("current");
          } else {
            // same clicked, close it up
            $clicked.parent().animate({
              height: startHeight+"px"
            }, 200, function(){
              currentOpen = false;
            });
            // house keeping of the classes
            $clicked.parent().removeClass("current");
          }

        });

        // close and remove the filters
        $this.find(".close").click(function(event){
          event.preventDefault();
          event.stopPropagation();
          

          
          // clear current classes from everywhere
          if (currentOpen) {
            currentOpen.animate({
              height: startHeight+"px"
            }, 200, function(){
            });
          }
          $this.find("li.current").removeClass("current");
          if (tags) {
            tags.find("li.current").removeClass("current");
          }
          $this.removeClass("active");$('.col-790.bg-chevrons').removeClass("refined");
          
          // ajax function
          if ($(this).attr("href") != '#') {
            doAjax(this, false);
            if ($(this).hasClass("sidebar")) {
              doSidebarAjax($(this), true);
              
             
              
              defaultSidebar = false;
            } else {
              if (!defaultSidebar) {
                doSidebarAjax($(this), true);
              }
              defaultSidebar = true;
            }
          }
        });

        // do tags lists clicks
        if (tagsListExists && tags) {
          tags.find("a").not(".more a").click(function(event){
            event.preventDefault();
            event.stopPropagation();
            // store which was clicked
            $clicked = $(this);
            if (!$clicked.parent().hasClass("current") && !$clicked.parent().hasClass("more")) {
              if (currentOpen) {
                currentOpen.animate({
                  height: startHeight+"px"
                }, 200, function(){
                });
              }
              $this.find("li.current").removeClass("current");
              $this.removeClass("active"); $('.col-790.bg-chevrons').removeClass("refined");
              tags.find("li.current").removeClass("current");
              $this.addClass("active"); $('.col-790.bg-chevrons').addClass("refined");
              $clicked.parent().addClass("current");
              // ajax function
              doAjax($clicked, true);
              if ($(this).hasClass("sidebar")) {
                doSidebarAjax($(this), true);
                defaultSidebar = false;
              } else {
                if (!defaultSidebar) {
                  doSidebarAjax($(this), true);
                }
                defaultSidebar = true;
              }
            }
          });
          // sort out the tags more and less links, hiding and showing the tags
          if (tags && (tags.find(".more").length > 0)) {
            var hiddenTags = tags.find("li:hidden");
            tags.find(".more a").click(function(event){
              event.preventDefault();
              event.stopPropagation();
              var $clicked = $(this);
              if(!$clicked.hasClass("extended")) {
                $clicked.fadeOut(200,function(){
                  $clicked.html("Less").addClass("extended").fadeIn(200);
                  hiddenTags.fadeIn(200);
                });
              } else {
                $clicked.fadeOut(50,function(){
                  hiddenTags.fadeOut(200, function(){
                    $clicked.html("More").removeClass("extended").fadeIn(200);
                  });
                });
              }
            });
          }
        }

      });
    }
    function toolsDD() {
      var open = false;
      $("body").click(function(event){
        if (open) {
          event.preventDefault();
          hideDD();
        }
      });
      $(window).keyup(function(event) {
        if (open && event.keyCode == 27) {
          hideDD();
        }
      })
      function hideDD() {
        open = false;
        $(".dd p").removeClass("active").next().addClass("hide");
      }
      $(".dd ul li a").click(function(event){
        event.stopPropagation();
      });
      $(".dd p").click(function(event){
        event.preventDefault();
        event.stopPropagation();
        $(this).toggleClass("active").next().toggleClass("hide");
        open = !open;
      });
    }
    function printPage() {
      if($(".media .caption").length > 0) {
        $(".media .caption").each(function(){
          var parent = $(this).parent();
          if (parent.find("img").length < 1) {
            var videoUrl = parent.find("embed").attr("src") || parent.find("param[name=movie]").attr("value") || false;
            videoUrl = (videoUrl == false) ? 'Video: ' : '<a href="'+videoUrl+'">'+videoUrl+'</a>';
            $('<p class="video-details">'+videoUrl+' <br />'+$(this).html()+'</p>').insertAfter(parent);
          }
        });
      }
      $(".print a").click(function(event){
        //event.preventDefault();
        //window.print();

      });
    }
    function googleMaps() {
      if ($("#googlemap").length > 0 && $("#address").length > 0) {
        var googlemap = $('#googlemap');
        $("#googlemap").css("width","830px").css("height","360px");
        var map;
        var address = $("#address").text();
        var address2 = "";
        if ($("#address2").length > 0) {
          address2 = $("#address2").text();
        }

        var geocoder = new google.maps.Geocoder();

        if (geocoder && address.length > 1) {

          geocoder.geocode( { 'address': address}, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {

              var $center = results[0].geometry.location,
              $position = results[0].geometry.location;
              if (googlemap.hasClass('googlemap-london')) {
                $center = new google.maps.LatLng(51.520511835812556, -0.11614501476287842);
                $position = new google.maps.LatLng(51.520511835812556, -0.11614501476287842);
              }	
              if (googlemap.hasClass('googlemap-sf'))
              $position = new google.maps.LatLng(37.78248727664818, -122.40659147500992);
              if (googlemap.hasClass('googlemap-ny'))
              $position = new google.maps.LatLng(40.703187,-73.987948);

              map = new google.maps.Map(document.getElementById("googlemap"), {
                zoom: 18,
                center: $center,
                mapTypeId: google.maps.MapTypeId.SATELLITE
              });
              var marker = new google.maps.Marker({
                map: map,
                position: $position
              });

              if (geocoder && address2.length > 1) {
                geocoder.geocode( { 'address': address2}, function(results, status) {
                  if (status == google.maps.GeocoderStatus.OK) {
                    $center = results[0].geometry.location;
                    if (googlemap.hasClass('googlemap-sf'))
                    $center = new google.maps.LatLng(37.86954747075186, -122.26649701595306);
                    if (googlemap.hasClass('googlemap-ny'))
                    $center = new google.maps.LatLng(40.703187,-73.987948);
                    var marker = new google.maps.Marker({
                      map: map,
                      position: $center
                    });
                    map.setZoom(11);
                    map.panBy(-100,46);
                  } else {
                    $("#googlemap").hide().html("<p>Geocode was not successful for the following reason: " + status+"</p>").prev().css("margin-bottom","28px");
                  }
                });
              }

            } else {
              $("#googlemap").hide().html("<p>Geocode was not successful for the following reason: " + status+"</p>").prev().css("margin-bottom","28px");
            }
          });

        } else {
          $("#googlemap").hide().prev().css("margin-bottom","28px");
        }
      } else {
        $("#googlemap").hide().prev().css("margin-bottom","28px");
      }
    }
    function setMinHeights() {
      var maxHeight = 0;
      $(".autosize").each(function(){
        var totalHeight = $(this).css("min-height","0px").height() + ($(this).css("padding-top").replace("px","") * 1) + ($(this).css("padding-bottom").replace("px","") * 1);
        maxHeight = totalHeight > totalHeight ? $(this).height() : totalHeight;
      });
      $(".autosize").each(function(){
        var minHeight = maxHeight - ($(this).css("padding-top").replace("px","") * 1) - ($(this).css("padding-bottom").replace("px","") * 1);
        $(this).css("min-height",minHeight+"px");
      });
    }
    function libraryReadMore(){
      var currentOpen = false;
      var pharagrapListExists = ($("#library_short_description_html").length > 0) ? true : false;
      var pharagrap = pharagrapListExists ? $("#library_short_description_html:first") : null;
      if (pharagrapListExists && pharagrap) {
        pharagrap.find("a").not(".readMore a").click(function(event){
          event.preventDefault();
          event.stopPropagation();
          // store which was clicked
          $clicked = $(this);
          if (!$clicked.parent().hasClass("current") && !$clicked.parent().hasClass("readMore")) {
            if (currentOpen) {
              currentOpen.animate({
                height: startHeight+"px"
              }, 200, function(){
              });
            }
            $this.find("li.current").removeClass("current");
            $this.removeClass("active");
            pharagrap.find("li.current").removeClass("current");
            $clicked.parent().addClass("current");
            // ajax function
            doAjax($clicked, true);
          }
        });
        // sort out the tags more and less links, hiding and showing the tags
        if (pharagrap && (pharagrap.find(".readMore").length > 0)) {
          var hiddenTags = pharagrap.find("li:hidden");
          pharagrap.find(".readMore a").click(function(event){
            event.preventDefault();
            event.stopPropagation();
            var $clicked = $(this);
            if(!$clicked.hasClass("extended")) {
              $clicked.fadeOut(200,function(){
                $clicked.html("Read less").addClass("extended").fadeIn(200);
                hiddenTags.fadeIn(200);
              });
            } else {
              $clicked.fadeOut(50,function(){
                hiddenTags.fadeOut(200, function(){
                  $clicked.html("Read more").removeClass("extended").fadeIn(200);
                });
              });
            }
          });
        }
      }
    }
    function servicesListHelper() {
      if ($(".listing-services").length > 0) {
        $(".listing-services li:nth-child(2n+1)").css("clear","left");
      }
    }
    function ie6Helpers() {
      $(".listing-simple a").hover(
        function () {
          $(this).find("span").css("text-decoration","underline");
        }, 
        function () {
          $(this).find("span").css("text-decoration","none");
        }
      );

      $(".press-inquiries a").hover(
        function () {
          $(this).find("p").css("text-decoration","underline");
        }, 
        function () {
          $(this).find("p").css("text-decoration","none");
        }
      );

      $(".listing-small a, .library-small a, .listing-casestudies a, .listing-themes a, .listing-team a, .listing-council a, div.item, .listing-library li, .listing-news li, .listing-search a, .listing-esp li").hover(
        function () {
          $(this).find("h3").css("text-decoration","underline");
          $(this).find(".green").css("text-decoration","underline");
          $(this).find(".more").css("text-decoration","underline");
        }, 
        function () {
          $(this).find("h3").css("text-decoration","none");
          $(this).find(".green").css("text-decoration","none");
          $(this).find(".more").css("text-decoration","none");
        }
      );
      
      /* disqus widget */
      if($('.disqus_widget').length > 0) $(".dsq-widget-meta").find('a:first').addClass('first');
      
    }

    function recentTweets() {

      if ($('#recenttweets').length == 0) return false;

      function formatTime(time_value) {
        var values = time_value.split(" ");
        return values[2] + " " + values[1] + " " + values[5];
      }

      $.getJSON("http://twitter.com/statuses/user_timeline/SustAbility.json?count=3&callback=?", function(twitters) {
        var statusHTML = [];
        for (var i=0; i<twitters.length; i++){
          var username = twitters[i].user.screen_name;
          var status = twitters[i].text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) {
            return '<a href="'+url+'">'+url+'</a>';
          }).replace(/\B@([_a-z0-9]+)/ig, function(reply) {
            return  reply.charAt(0)+'<a href="http://twitter.com/'+reply.substring(1)+'">'+reply.substring(1)+'</a>';
          });
          statusHTML.push('<li><a class="tweet_date" href="http://twitter.com/'+username+'/statuses/'+twitters[i].id+'" target="_blank">'+formatTime(twitters[i].created_at)+'</a><span>'+status+'</span> </li>');
        }
        document.getElementById('recenttweets').innerHTML = statusHTML.join('');
      });
    }
    
    
    /* -- added by antoine 01-10-2011 -- */
    function fixLinks() {
      $('li > .item').click(function(event){
        event.preventDefault();

        var url = $(this).find('a:first').attr('href');
        if(url != '' || url != '#') window.location = url;
      });
    }
    
    function disqus_callback() {
      
      if($('#sustainability').hasClass('blog-detail') || $('#sustainability').hasClass('library-detail')) {
        
        var check_disqus = setInterval(function() {
          var disqus_ready = $("#dsq-comments-title").get(0) != null;
          if (disqus_ready) {
            clearInterval(check_disqus); // remove timer

            if($('#dsq-comments').children().length > 0) {
              
              var commentText = $('#dsq-comments-title').find('h3').text(),
                  nbComments  = parseInt($("#dsq-num-posts").text());

              $('#comments_counter').empty().html( '<h4 class="fR3" >Comments (' + nbComments +')</h4>');
              Cufon.replace('#comments_counter h4', { fontFamily: 'Whitney Cufon' });
              
            } else {
              $('#comments_counter').empty().html( '<h4 class="fR3" >Comments</h4>');
              Cufon.replace('#comments_counter h4', { fontFamily: 'Whitney Cufon' });
            }
            
            if($('.dsq-h3-reactions').length > 0) {
              $('.dsq-h3-reactions').replaceWith('<div id="reactions_counter"><h4 class="fR3" >Reactions</h4></div>');
              Cufon.replace('#reactions_counter h4', { fontFamily: 'Whitney Cufon' });
            }
          }
        }, 100);
        
      }
      
      if($('.disqus_widget').length > 0) {
        var maxlength = 110;
        $(".dsq-widget-comment").each(function() {
    			var self = $(this),	text = self.text();
    			if (text.length > maxlength) self.html(text.substr(0, maxlength) + '...');
    		});
    	}
    }

    /* -- end added by antoine --*/
    
function launch_hyphenator() {
  Hyphenator.config({ minwordlength : 10, defaultlanguage: 'en' });
  Hyphenator.run();
}


$(document).ready(function(){
  browserTest();
  refineBy();
  replaceFonts();
  defaultValues();
  fixLinks();
  disqus_callback();
  if ($(".hyphenate").length > 0) launch_hyphenator();
  
  /*libraryReadMore();*/
  toolsDD();
  printPage();
  setMinHeights();
  servicesListHelper();
  if ($("#newsletter_form")) {
    
    var formNewsletter = $("#newsletter_form");
    var error_mess = formNewsletter.find('.error');
    var success_mess = formNewsletter.find('.thanks');
    
    $("#newsletter_form").submit(function() {
      
      success_mess.hide();
      error_mess.hide();
      
      var formAction = formNewsletter.attr("action"), str = formNewsletter.serialize();
      
      //<![CDATA[
      var serialized = str + "&action=" + formAction;
      // ]]>
      
      $.ajax({
        url: "/proxy",
        type: "POST",
        data: serialized,
        success: function(data){
          if (data.search(/invalid/i) != -1) {
            error_mess.show();
            success_mess.hide();
          }
          else {
            success_mess.show();
            error_mess.hide();
          }
          
          _gaq.push(['_trackEvent', 'Newsletter Sign-Up', 'Footer', document.title]);
        }
      });
      return false;
    });
    

  }
  $("#footer .top a").click(function(event){
    event.preventDefault();
    $.scrollTo("#sustainability", 250);
  });
  $("sup.footnote a").click(function(event){
    event.preventDefault();
    var href = $(this).attr("href");
    if (href.length > 1) {
      $.scrollTo(href, 250);
    } else {
      window.location = href;
    }
  });
  $("a[href^=http]").attr('target','_blank');
  //
  // sliders
  //
  // homepage
  slider($(".home .media:first"), $(".home .media:first .slider"), 710, 1, 1, 0, false, true, 5);
  
  // Engaging Skateholders
  slider($(".engaging-stakeholders .slider-quotes"), $(".engaging-stakeholders .slider"), 270, 1, 1, 0, false, true, 10);
  //
  // maps on the contact pages
  googleMaps();
  // Login page
  $(".login input[name=email]:first").focus();

  recentTweets();
});
}();

