
(function($) {
  // global closure and $ portability

  $(document).ready( function() {
     
     var initialAnchor = $.anchor();
     
     var panelAnchor;
     
     
     // record the document title - we'll append the panel title to this as they are scrolled to
     var documentTitle = document.title;

     var caseStudyImageUrlBase = "/images/case_studies/";
     
    /* -- Panel Scroller Setup -- */

    // -- Supporting functions

    var updateScrollerButtonPosition = function() {
      $('.scroller_previous').css( 'left', (( $(window).width() - 850 ) / 2 ) - 25 );
      $('.scroller_next').css( 'left', (( $(window).width() - 850 ) / 2 ) + 790 );
    };

	var updateSubNavigation = function(panel) {
	
	  var snid = $(panel).metadata().subNavId;
	
	  if (!snid) {
		var navid = $(panel).attr("id").replace("panel", "nav");
	
		if (navid && navid != "") {
		  snid = 'ul.sub_nav #' + navid;
		}
	  }
	
	  if (snid) {
		var subNavItems = $(snid);
	
		$('ul.sub_nav li').removeClass("on");
	
		if (subNavItems.length > 0) {
		  subNavItems.addClass("on");
		}
	  }
	};


	var scrollToAnchor = function(anchor, instant) {
      if (anchor != "") {
        var panels = $('#panel_' + anchor);

        if (panels.length > 0) {
          $(panels).closest(".scroller").scrollerTo(panels[0], instant);
        } else {
          return false;
        }

        return true;
      }

      // the anchor was empty, or the panel was not found
      return false;
    };
 
  
    // -- Setup button positioning and click events

    updateScrollerButtonPosition();

    $('.scroller_next')
     .click( function(event) {
       $(event.target).closest(".scroller").scrollerNext();
     });

    $('.scroller_previous')
    .click( function(event) {
      $(event.target).closest(".scroller").scrollerPrevious();
    })
    .hide();
    
    
    // -- Setup the scroller, and event bindings
    $('.scroller').scroller();

    
    // scroll to the anchor instantly (if available)
    scrollToAnchor($.anchor(), true);
    
    
    

    //alert($.anchor());
    
    $('.scroller').bind("scroller.beforescroll", function(event, item, instant) {
      // show the panel title so that the content is masked in the old panel
      // also, make sure that any existing animations are stopped, and opacity is reset first (prevents bugs with quick scrolling multiple times leaving panel content exposed)
  
      // remove transparency from all panels
      $(this).find(".panel_transparent").removeClass("panel_transparent");
      
      // remove any feature background
      var bgClass = $(item).metadata().bgClass;
      
      if (bgClass) {
          $('#bg_feature').removeClass(bgClass).hide();
      }

      // hide any revealed panels and close buttons
      $(item).closest(".panel").removeClass("panel_current").find(".panel_close").hide().end().find(".panel_reveal_content:visible").hide();
  
      // blank the title while scrolling
      $('#page_title').html("&nbsp;");
      $(item).find(".panel_title").stop().css("opacity", 1).show();	  
      $(this).find(".scroller_previous,.scroller_next").hide();
    });

    $('.scroller').bind("scroller.afterscroll", function(event, item, instant) {
      var duration = "fast";
      
      
      $(item).addClass("panel_current");
      
      // show all other panel titles (fixes a few issues with initial load)
      $(this).find(".panel_title").not($(item).find(".panel_title")).show();
      
      // add transparent class if "transparent" is true in the meta
      if ($(item).metadata().transparent) {
        $(item).addClass("panel_transparent");
      }
      
      // update the page title from the content of the panel title in the new panel
      
      var title = $(item).find("h2:first").html();

      // update the page title
      $('#page_title').show().html( title );



      // update the window title
      if (!$(item).is(":first-child")) {
        document.title = title + " - " + documentTitle;
      } else {
        document.title = documentTitle;
      }
      
      // update the feature background (if available, and specified found in the meta)
      
      var bgClass = $(item).metadata().bgClass;
      
      if (bgClass) {
        setTimeout( function() { $('#bg_feature').hide().addClass(bgClass).fadeIn(instant || $.fadeDuration()); }, instant || $.browser.msie ? 0 : 200 );
        
      }
      
      // fade out the panel title so that the content shows through for the new panel
      $(item).find(".panel_title").fadeOut({ duration: duration});

      // show both previous/next buttons initially (one may be hidden by a "limit" event later)
      $(this).find('.scroller_previous,.scroller_next').show();
      
      // update the navigation state
      updateSubNavigation(item);
      
      // update the hash (ooooh polished!)
      document.location.hash = $(item).attr("id").replace("panel_", "");
      
      panelAnchor = document.location.hash;
      
      // track the location in Google Analytics
      pageTracker._trackPageview(document.location.pathname + document.location.hash.replace("#", ""));
	  
	  // added oct 3, 2011
	  if( !($('ul#nav').hasClass('inside')) ){
		addPrevNextButtons();
	  }
      
    });

	// added oct 3, 2011
	// adding the previous and next buttons, triggered by scroller.afterscroll and #nav li.a click
	// creating previous and next buttons between main pages, e.g., about to services, etc. */
		
	var addPrevNextButtons = function(t,f){
		currLi = $('#nav > li.on');
		currNavClass = $('#nav > li.on').attr('id');
		if(t){
			var currentId = $('ul#nav').data('currentID');
			currNavClass = t.parent().attr('id');
			if(currentId != currNavClass){return false;}
			currLi = t.parent();
		}
		else{
			$('ul#nav').data('currentID',currNavClass);
		}
		currSubLi = $('#nav > li > ul > li.on');
		nextLink = currLi.next('li').children('a').attr('href');
		prevLink = currLi.prev('li').children('a').attr('href');
		currLink = currLi.find('a').attr('href');
		nextLinkText = currLi.next('li').children('a').html();
		prevLinkText = currLi.prev('li').children('a').html();
		$('#scroller').find('.nextButton, .prevButton').remove();
		
		var prevButtonAnimate = function(){
			$('.prevButton').animate({left: '-18px'}, 750, function(){
				$('.prevButton').animate({left:'-36px'}, 500);
			});	
		}
		var nextButtonAnimate = function(){
			$('.nextButton').animate({right: '0'}, 750, function(){
				$('.nextButton').animate({right: '-18px'}, 500);
			});	
		}
			
		// adding the previous tab
		if ( $('#nav >li:first').hasClass('on')  && !($('li.on li').hasClass('on')) ){
			$('#scroller').append('<a class="prevButton ' + currNavClass + '" href="/"> Home</a>');
			prevButtonAnimate();
		}				
		else if( ((!$('a').hasClass('prevButton')) && prevLink && !($('li.on li').hasClass('on'))) || t&&!f ){
			if(prevLink){
				$('#scroller').append('<a class="prevButton ' + currNavClass + '" href="' + prevLink + '">' + prevLinkText + '</a>');
			}
			else{
				$('#scroller').append('<a class="prevButton ' + currNavClass + '" href="/"> Home</a>');
			}
			prevButtonAnimate();	
		}
		else{
			$('#scroller').find('.prevButton').remove();
		}		
		
		// adding the next tab
		if( ((!$('a').hasClass('nextButton')) && nextLink && $('li.on li:last').hasClass('on')) || f ){
			if(nextLink){
				$('#scroller').append('<a class="nextButton  ' + currNavClass + '" href="' + nextLink + '">' + nextLinkText + '</a>');
			}
			else{
				$('#scroller').append('<a class="nextButton  ' + currNavClass + '" href="/">home</a>');
			}
			nextButtonAnimate();
		}
		else if( (!$('a').hasClass('nextButton')) && !nextLink && $('li.on li:last').hasClass('on') ){ 
			$('#scroller').append('<a class="nextButton  ' + currNavClass + '" href="/">home</a>');
			nextButtonAnimate();
		}
		else if( (!$('#nav > li').hasClass('on')) ){
		    $('#scroller').append('<a class="nextButton  ' + currNavClass + '" href="' + nextLink + '">' + nextLinkText + '</a>');
			nextButtonAnimate();	
		}
		else{
			$('#scroller').find('.nextButton').remove();
		}

	}// end addPrevNextButtons

    $('.scroller').bind("scroller.afterscrolllowerlimit", function(event, item, instant) {
     // hide the previous button
     $(this).find('.scroller_previous').hide();
    }); 

    $('.scroller').bind("scroller.afterscrollupperlimit", function(event, item, instant) {
     // hide the next button
     $(this).find('.scroller_next').hide();
    }); 
	
    // create any tooltips
    
    if ($.PAGE_TOOLTIPS)
      $.each($.PAGE_TOOLTIPS, function(index, value) {
        $.tooltipCreate(value);
      });
	  
    // create any tooltips
    
    if ($.TWITTER_TOOLTIPS)
      $.each($.TWITTER_TOOLTIPS, function(index, value) {
        $.tooltipCreate(value);
      });	  
      
    // setup tooltip behaviours
    $('.tooltip_trigger').tooltip();	

    // -- Setup navigation clicks to jump to specific panels
    // -- Also, ANY link given a class of "jump" will attempt to find a panel to scroll to 
    // -- the hash anchor should be the same as for a sub-nav item, that is, the panel id without the "panel_" prefix
    
    $('ul#nav li a,a.jump').click( function(event) {

      if (scrollToAnchor($(this).anchor())) {
          // blur the link so the dotted line doesn't show

          if ($(this)[0].blur)
            $(this)[0].blur();

          event.preventDefault();
      }

    });
	
     // added oct 3, 2011
	 $('ul#nav>li>a').live('click', function() {
		addPrevNextButtons($(this));
	 });
	  $('ul#nav>li>ul>li>a').live('click', function() {
		addPrevNextButtons($(this).parent().parent(), 'flag');
	 });


    // setup clicks to reveal slide in panel content
    
    $('a.slide').click( function(event) {
      // find the panel reveal target
      
      var anchor = $(this).anchor();
      
      if (anchor != "") {
      
        // find the target
        var t = $('#panel_' + anchor);
        
        if (t.length > 0) {
          
          var panelContent = $(this).closest(".panel_content");
          
          t.css("top", - $(panelContent).outerHeight()).stop(true, true).css("top", 0).fadeIn({duration: "normal", easing: "easeOutQuart"}).queue( function() {
            $(this).closest(".panel").find(".panel_close").fadeIn("slow");
          });
        }
      }
      
      event.preventDefault();
    });
    
    // setup click to hide slide in panel content
    
    $('.panel .panel_close').click( function() {
      var button = $(this);
      // find the closest panel
      $(this).closest(".panel").find(".panel_reveal_content").stop(true, true).fadeOut({duration: "normal", easing: "easeOutQuart"}).queue( function() { button.fadeOut("fast"); } );
    });
    
    
    /* -- Anchor the Footer to the bottom -- */ 

    $(window).resize( function() {
      $('#bg').css("height", Math.max( 560, $(window).height() - 33 ));
      $('#overlay').css("height", Math.max( 568, $(window).height() - 25 ));
      updateScrollerButtonPosition();
      $(".scroller").scrollerUpdateOrigin(true);
      
    }).resize();
 
    // update the scroller to the correct place
    $(".scroller").scrollerUpdate();

    /* -- Setup the Navigation (can't QUITE use pure CSS for this any more, unfortunately) -- */ 
         
    // record the currently visible nav - this will be reverted on "nav" mouseout
    
    var subNavCurrent = $('ul.sub_nav:visible');
    
    $('ul#nav>li').mouseenter( function(event) {
      // hide all other sub navs, and turn off the on state
      $('ul.sub_nav').stop(true, true).hide().closest("li").removeClass("on");
      
      // show the sub nav for this main nav item
      $(this).find("ul.sub_nav").slideDown($(this).closest("ul#nav").hasClass("inside") ? "fast" : 0);
    });
    
    $('ul#nav').mouseenter( function() {
      $(this).addClass("inside");
    });
    
    $('ul#nav').mouseleave( function(event) {
      // remove any hovers 
      $('ul#nav>li a').removeClass("hover");
      $(this).removeClass("inside");
      
      // show the default sub nav
      $('ul.sub_nav').stop(true, true).hide();
      subNavCurrent.show().closest("li").addClass("on");
    });

    $('ul.sub_nav').mouseenter( function() {
      // add hover class to the parent nav item
      $('ul#nav>li a').removeClass("hover");
      $(this).closest("li").find("a:first").addClass("hover");
    });
    
    // setup tabs
    
    $('.tabs').tabs();
    $('.tt_tabs').tabs();
    /* overlay - supporting functions */
    
    var hideOverlay = function() {
      $('#overlay').hide();
      $('#wrap_footer').removeClass("overlay");

      // disable other scroller
      $('.scroller').scrollerEnable();

      // restore the hash for the current panel
      if (panelAnchor) {
        document.location.hash = panelAnchor;
      }
      
      // disable overlay scroller
      $('#overlay .overlay_scroller').scrollerDisable();
    };
    
    
    var showOverlay = function(trigger) {
      $("#overlay_content").hide();
      $("#overlay_loading").show();
      
      $('#overlay').show();
      $('#wrap_footer').addClass("overlay");
      
      
        //console.log($.url.setUrl($(this).attr("href")).attr("file"));

      var overlayScroller = $('#overlay_content .overlay_scroller');

      if (overlayScroller.length > 0) {
        // an overlay scroller is currently present - destroy it, and unbind events from related elements on this page
        overlayScroller.scrollerDestroy();
        
        $('#overlay_content .overlay_scroller_next').unbind("click", overlayScrollerNextClick );
        $('#overlay_content .overlay_scroller_previous').unbind("click", overlayScrollerNextClick );
        $(window).unbind("resize", overlayWindowResize );
      }

      // now load the new overlay content
      
      document.location.hash = galleryAnchor(trigger);
      
      $("#overlay_content").load($(trigger).attr("href"), "ajax=true", function(responseText, textStatus) {
        

        if (textStatus == "success") {
          
          // hide the loading message and show the overlay (the overlay content must be visible BEFORE the scroller is initialised, for width measurement etc)
          $('#overlay_loading').hide();
          $('#overlay_content').show();

          updateOverlayScrollerButtonPosition();
          
          var overlayScroller = $('#overlay_content .overlay_scroller');
          
          if (overlayScroller.length > 0) {
          
            // a scroller is present in the loaded content, so set it up
            
            $('#overlay_content .overlay_scroller').scroller({
              itemSelector: "li.overlay_panel",
              clickSelector: "li.overlay_panel",
              viewWidth: 797
            });

			sIFR.replace(avenir, {
			  selector: 'h2.sifr',
			  wmode:'transparent',
				css: [
				'.sIFR-root { text-align:left; color:#535353; }'
				,'a { text-decoration: none; }'
				,'a:link { color: #000000; }'
				,'a:hover { color: #CCCCCC; }' 
				]
			});
			
			sIFR.replace(avenir, {
			  selector: 'p.sifr',
			  wmode:'transparent',			  
				css: [
				'.sIFR-root { text-align: left; font-weight:bold; }'
				,'a { text-decoration: none; }'
				,'a:link { background:#e4a452; color: #FFFFFF; }'
				,'a:hover { color: #4c342a; }' 
				]
			});			


            $('#overlay_content .overlay_scroller').bind("scroller.afterscrolllowerlimit", function(event, item, instant) {
             // hide the previous button
             $(this).find('.overlay_scroller_previous').hide();
            }); 

            $('#overlay_content .overlay_scroller').bind("scroller.afterscrollupperlimit", function(event, item, instant) {
             // hide the next button
             $(this).find('.overlay_scroller_next').hide();
            });

            $('#overlay_content .overlay_scroller').bind("scroller.beforescroll", function(event, item, instant) {
              $(this).find(".overlay_scroller_previous,.overlay_scroller_next").hide();
              $(item).removeClass("overlay_panel_current");
            });

            $('#overlay_content .overlay_scroller').bind("scroller.afterscroll", function(event, item, instant) {
              $(this).find(".overlay_scroller_previous,.overlay_scroller_next").show();
              $(item).addClass("overlay_panel_current");
            });

            $('#overlay_content .overlay_scroller_next').click( overlayScrollerNextClick );
            $('#overlay_content .overlay_scroller_previous').click( overlayScrollerPreviousClick ).hide();
            $(window).resize( overlayWindowResize );
  
            
            // disable other scroller
            $('.scroller').scrollerDisable();
            
          }
          
        }
        else if (textStatus == "error") {
          hideOverlay();
          alert('Sorry, this content could not be loaded. Please try again later.'); 
        } 
      });

    };
    
    var galleryAnchor = function(trigger) {
      return "gallery_" + $(trigger).basename(".php");
    };
    
    var updateOverlayScrollerButtonPosition = function() {
      $('.overlay_scroller_previous').css( 'left', (( $(window).width() - 798 ) / 2 ) - 25 );
      $('.overlay_scroller_next').css( 'left', (( $(window).width() - 798 ) / 2 ) + 740 );
    };
    
    
    /* overlay - events */
    
    var overlayWindowResize = function() {
      $('#overlay_content .overlay_scroller').scrollerUpdateOrigin(true);
      updateOverlayScrollerButtonPosition();
    };
    
    var overlayScrollerNextClick = function(event) {
      $(event.target).closest(".overlay_scroller").scrollerNext();
    };

    var overlayScrollerPreviousClick = function(event) {
      $(event.target).closest(".overlay_scroller").scrollerPrevious();
    };
    
    // -- setup gallery click to load gallery and show overlay, loading the scroller if content is loaded correctly 
    
    $('.trigger_gallery')
      .click( function(event) {
        showOverlay($(this));
        event.preventDefault();
      })
      .each( function() {
        // check if the initial anchor matches a gallery, and if so open the gallery overlay for that href
        if (galleryAnchor($(this)) == initialAnchor) {
          
          // scroll to the parent panel (if available)
          var panel = $(this).closest(".panel");
          
          if (panel.length > 0) {
            panel.closest(".scroller").scrollerTo(panel[0], true);
          }
          
          showOverlay($(this));
          
        }
      });


    $('#bt_overlay_close').click( function(event) {
      hideOverlay();
    });
    
    // setup share popup close button
    $('#tt_share_close').click( function(event) {
      $('#tt_share').revealHide();
      
      event.preventDefault();
    });
    
    // setup field hints for the email form
    $('#tt_panel_email input,#tt_panel_email textarea').fieldHint(); 
    
    $('#footer_share,#footer_twitter').show();
    
    // setup social links
    $('#tt_panel_social ul a').click( function(event) {
      event.preventDefault();

      var template = $(this).metadata().template;
      
      if (template) {
        var href = $.tmpl(template, { url: $.urlencode(document.location.href), title: $.urlencode(document.title) });
        window.open(href, "share");
      }
      
    });
    
    
    // setup the email a friend validation

    $("#form_share_email")
      .submit( function(event) {
        
        // first clear out all field hints when the field has not been filled in
        
        $('#your_name,#your_email,#friends_name,#friends_email,#personal_message').each( function(index, el) {
          
          if ($(el).val() == $(el).metadata().hint) {
            $(el).val("");
          }
          
        });
        
        // NOW run the validator
        
        if ($(this).valid()) {
          // send the ajax request
        
          $.post('/share', {
              "your_name"         : $('#your_name').val(),
              "your_email"        : $('#your_email').val(),
              "friends_name"      : $('#friends_name').val(),
              "friends_email"     : $('#friends_email').val(),
              "personal_message"  : $('#personal_message').val(),
              "url"               : document.location.href
            }, function (data, textStatus) {
              if (data == "OK") {
                $('#tt_share_form').hide();
                $('#tt_share_thankyou').show();
              } else {
                alert("Sorry, the email could not be sent. Please try again later"); 
              }
              
            }
          );
        }
        
        event.preventDefault();
        
      })
      .validate({
      
        meta: "validate", 
        onfocusout: false,
        onkeyup: false,
        onsubmit: false, // we will run valid manually, since we need to ignore field hints
      
        showErrors: function(errorMap, errorList) {
          
          if (errorList.length > 0) {
            var errors = $.map(errorList, function(value, index) {
              return value.message;
            });
          
          
            alert(errors.join("\n"));
          
            $('#your_name,#your_email,#friends_name,#friends_email,#personal_message').fieldHintUpdate("blur"); // restore field hints
          }
        }
      });
      
      
      $('#tt_share_link_again').click( function() {
          $('#tt_share_thankyou').hide();
          $('#tt_share_form').show();
          
          $('#friends_name,#friends_email').val("").fieldHintUpdate("blur");
      });
      
  
    /*
         
    $('#form_share_email').submit( function(event) {
        
        event.preventDefault();
        
        // check the fields
        
        var errors = [];
        
        if (errors.
        // post to the ajax service
        
        jQuery.post( url, [data], [callback], [type] )
        
        var friendsFirstName = $('#friends_name').val().split(" ")[0];
        
        document.location.href = "mailto:" + $('#friends_name').val() + ' <' + $('#friends_email').val() + '>?subject=Check%20out%20this%20site' + 
        '&body=Hi ' + friendsFirstName + 
        ",%0A%0AI%20thought%20you%20might%20be%20interested%20in%20this%20page%20on%20the%20Catalyst%20Group's%20web%20site:%0A" +  + "%0A%0A" + $('#personal_message').val() + "%0A%0ARegards,%0A%0A" + $('#your_name').val() + " (" + $('#your_email').val() + ")";
        
        
        $('#tt_share').revealHide();
    });
    
    */
	
	$('#closeModal').click(function(){
		$('#modal').removeClass('show');
		$('.panel_job').removeClass('show');
		return false;
	});
	$('#applyHere a').click(function(event){
		$('#modal').removeClass('show');
		$('.panel_job').removeClass('show');
		setTimeout(function(){
			window.location.reload(true);
		},0);
	});
	$('.openModal').click(function(){
		var that = $(this);
		$('#modal').addClass('show');
		displayModalContent(that); 
		$('#modalInner').scrollTop(0);
		return false;
	});
	
	var displayModalContent = function(modalContent){
		modalToOpen = modalContent.attr('href');
		modalToOpen = modalToOpen.split('#')[1];
		$('#'+modalToOpen).addClass('show');
		return false;
	}
	
	// added oct 3, 2011
	// checking if its the homepage, if it is, add the next button to the about us page
 	    var checkForHomePage = function(){
			if( ! ($('#nav >li').hasClass('on')) ){
			// this is the homepage, no nav links have the class "on"
			// so lets add the specific next button to the body of the page
		    $('#bg').wrapInner('<div id="scroller" />');
		    currLi = $('#nav > li:first');
			lastLi = $('#nav > li:last')
			nextLink = currLi.children('a').attr('href');
			nextLinkText = currLi.children('a').html();
			lastLink = lastLi.children('a').attr('href');
			lastLinkText = lastLi.children('a').html();
			$('#scroller').append('<a class="nextButton home" href="' + nextLink + '">' + nextLinkText + '</a>');
			$(window).bind("load", function() {   
				$('.nextButton').animate({right: '0'}, 750, function(){
					$('.nextButton').animate({right: '-18px'}, 500);
				});	
			});
		}
	    }();
	
	$('#contactFormSubmit #form_submit').click(function(){
		submitToCatalyst();
		submitToSalesforce();
	});
	
	/* submits of contact form */
	var submitToCatalyst = function(){
	    document.contactCatalyst.action = "/contact"
		document.contactCatalyst.submit();             // Submit the page
		return true;
	}
	var submitToSalesforce = function(){
	    document.contactCatalyst.action = "https://www.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8"
		document.contactCatalyst.submit();             // Submit the page
		return true;
	}
    
    
  }); // end document.ready 
  
})(jQuery); // end global closure



