function isInternalUrl(url) {
	var extLinkPattern = /^http|mailto/ ;
	var thisSitePattern = new RegExp(document.getElementsByTagName('base')[0].getAttribute('href'));
	
	if (!extLinkPattern.test(url) & url != '#' & url != undefined) {
	  return true;
	} else if (thisSitePattern.test(url)){
		return true;
	} else {
		return false;
	}
}

function cufonReplace() {
	Cufon.replace('#tagline, .masthead_caption, #secondarynav');
	Cufon.replace('#mainnav', { hover:true });
	Cufon.replace('#body_text h1', { letterSpacing: '0.5px'} );
}


(function( $ ){

	//cufonReplace();
	var pageTypes = {
		"Section Parent Page" : 'genpage-content',
		"Section Page" : 'genpage-content',
		"Home Page": "homepage-content"
	}
	
	var animationSpeed = 800;
	
	$.fn.whichDirection = function(active, clicked) {
	  // iterate through the items to the left of the ACTIVE item. 
	  // if the CLICKED item is in that list, clickedIsToTheLeft = TRUE.
	  
	  var clickedIsToTheLeft = false;
	  var currentLength = 1;
	  
	  while(!clickedIsToTheLeft && currentLength) {
	    
	    active = active.prev();

	    if (active.html() == clicked.html()) {
	      clickedIsToTheLeft = true;
	    }
	    currentLength = active.length; 
	  }
	  
	  if (clickedIsToTheLeft) {
	    return 'left';
	  } else {
	    return 'right';
	  }
	    
	};
	
  $.fn.fadeToLeft = function(parameters) {
    var options = { 
      callback: function() {},
      extraslide: 0
    }; 
    
    $.extend(options, parameters);
    return this.each(function() {
      var $this = $(this);
      $this.css({'height':$this.css('height')});
      $this.animate({'margin-left': '-'+($this.width() + options.extraslide)}, animationSpeed, 'linear', function() { options.callback(); });
    });
  };

  $.fn.fadeToRight = function(parameters) {
    var options = { 
      callback: function() {},
      extraslide: 0
    }; 
    $.extend(options, parameters);
    return this.each(function() {
      var $this = $(this);
      $this.css({'height':$this.css('height')});
      $this.animate({'margin-left': ($this.width() + options.extraslide)}, animationSpeed, 'linear', function() { options.callback(); });
    });
  };

  $.fn.smoothfadeToLeft = function(parameters) {
    var options = { 
      callback: function() {},
      extraslide: 0
    }; 
    $.extend(options, parameters);
    return this.each(function() {
      var $this = $(this);
      var width = $this.width();
      
      $this.css({'height':$this.css('height'), 'position':'absolute', 'top':'0', 'left':'0', 'width':width});

      $this.animate({'left': '-'+(width+ options.extraslide)}, 1000, 'easeInOutQuad', function() { options.callback(); });
    });
  };

  $.fn.smoothfadeToRight = function(parameters) {
    var options = { 
      callback: function() {},
      extraslide: 0
    }; 
    $.extend(options, parameters);
    return this.each(function() {
      var $this = $(this);
      var width = $this.width();

      $this.css({'height':$this.css('height'), 'position':'absolute', 'top':'0', 'left':'0', 'width':width});
      $this.animate({'left': (width + options.extraslide)}, 1000, 'easeInOutQuad', function() { options.callback(); });
    });
  };

  
	$.fn.linkClickHandler = function(direction) {
		return this.each(function() {
			var $this = $(this);
			var targetUrl = $this.attr('href');
			// if internal link, and not the current page, transition.
			if (isInternalUrl(targetUrl) & targetUrl != $.perception_loc) {
				pageTransition(targetUrl, direction);
			}
		});
	};
	
	function transitionToNonHomepage(data) {
	  $('#body_section').animate(
        {'top': '324px'}
    );
	}
	
	function transitionToHomepage(data) {
	  $('#body_section').animate(
        {'top': '600px'}
    );	  
	}
	
	function animateTransition(data) {
    $('#primarynav').remove();
    
    $('.mastheadimage_container').append(data.navigation);
    
    
    if ($.perception_pagetype == "homepage-content") {
      $('#body_section').addClass('hidden_body_section');

    } else {
      $('#body_section').removeClass('hidden_body_section');
    }             
    
    var the_height = $('#body_text').height() ; 
    if (the_height > 150) {
      $('.mastheadimage_container').animate({'height': 450 + the_height + 'px'}, animationSpeed);
    } else {
      $('.mastheadimage_container').animate({'height':'600px'}, animationSpeed);
    }
    
    if (parseInt($('#primarynav').css('height')) != 45){
      $('#primarynav').css($.default_properties);
    }
   
    cufonReplace();

	}
	
	function pageTransition(targetUrl,direction) {	  
	  if (direction=='right') {
	    var fun = $.fn.smoothfadeToLeft;
	  } else {
	    var fun = $.fn.smoothfadeToRight;
	  }  

    $.fn.sliderfunction =  function() {
      return fun.apply(this, arguments);
    };
	  	  
		$.ajax({
			url: targetUrl + '?action=xajax',
			success: function(data) {
				$.perception_loc = targetUrl;
				$.perception_pagetype = pageTypes[data.pagetype];
				
				$('.maincont').attr('id', $.perception_pagetype);
				var newimg = $(data.imgtag);
				
				if (newimg.attr('src') != $('#image_mask img').attr('src')) {
					$('.masthead_caption').fadeToLeft({
						callback: function() { 
							$('.masthead_caption').remove();

							$('.mastheadimage_container img').addClass('oldimg');
							var newImg = $(data.imgtag);
							
							if (direction =='right') {
							  newImg.addClass('newimg').css('left', '1024px');
							  $('.oldimg').after(newImg);
							} else {
	              newImg.addClass('newimg').css('left', '-1024px');
							  $('.oldimg').before(newImg);
							}
							
							$('#image_mask').wrapInner('<div id="the_tube" />');
							//return;
							
							$('#the_tube').sliderfunction({
							  callback:function() {
							    $('.oldimg').remove();
							    
                  newImg.unwrap().removeClass('newimg').attr('style', ' ');
                  if (data.caption) {
                    var caption = $(data.caption);
                    caption.css('margin-left', '-400px');
                    $('.caption_container').append(caption);
                    
                    caption.animate({'margin-left':'32px'}, animationSpeed);
                    
                    cufonReplace();
                  }
                  if ($.perception_pagetype != 'homepage-content') {
                    transitionToNonHomepage(data);
                  } else {
                    transitionToHomepage(data);
                  }							
							  }
							});
						}
					});
				}
        
				var newbodytext = $(data.bodytext);
				if ($('#body_text').length > 0) {
				  
				  // we need to do a chack to see if we're just removing the secondary nav. 
				  // if so, then we should fade it out with the body text.
				  
				  if (data.secondarynav == false) {
				    $('#secondarynav').fadeOut(animationSpeed, function() {
				      $(this).remove();
				      }
				    );
				  } else {
				    $('#secondarynav').remove();
				  }
				  
				  
				  $('#body_text').before(data.secondarynav);
			    cufonReplace();

				  $('#body_text').fadeOut(animationSpeed, function() {  
  				  $('#body_text').remove();
  				  
            newbodytext.hide();
            $('#body_section').append(newbodytext);
            newbodytext.fadeIn(animationSpeed);        
            
            animateTransition(data);

  				}
  				);
				  
				} else {
				  $('#body_section').append(data.secondarynav);
				  $('#body_section').append(newbodytext);
				  
				  animateTransition(data);
				}
			}
		});
	}	
})(jQuery);

$(function() {	
	$.perception_loc = window.location.href;
	$.perception_pagetype = $('div.maincont').attr('id');
	var primarynav = $('#primarynav');
	
	$.default_properties = {
		'height': '42px'
	};
		
	var open_pane_properties = {
	  'height': primarynav.css('height')
	};

	primarynav.css($.default_properties);
	
	if ($.perception_pagetype = 'homepage-content') {
	  $('.hidden_body_section').css('top','600px');
	}

//	primarynav.hover(function() {
//        if (!$(this).hasClass('transitioning')) {
//			$(this).addClass('transitioning');
//			$(this).animate(open_pane_properties, { 
//				duration: 'fast',
//				complete: function() { $(this).removeClass('transitioning'); }
//			});
//			
//		}
//	},function() {
//		if (!$(this).hasClass('transitioning')) {
//			$(this).addClass('transitioning');
//			$(this).animate($.default_properties, { 
//				duration: 'fast',
//				complete: function() { $(this).removeClass('transitioning'); }
//			});
//		}
//	}); //.css({'background-color':'white'});
	
    	primarynav.live('mouseenter', function() {
		if (!$(this).hasClass('transitioning')) {
			$(this).addClass('transitioning');
			$(this).animate(open_pane_properties, { 
				duration: 'fast',
				complete: function() { $(this).removeClass('transitioning'); }
			});
			
		}
	}).live('mouseleave', function() {
		if (!$(this).hasClass('transitioning')) {
			$(this).addClass('transitioning');
			$(this).animate($.default_properties, { 
				duration: 'fast',
				complete: function() { $(this).removeClass('transitioning'); }
			});
		}
	});

    
    
    
    
	$('a').live('click', function(e) {
	  if (isInternalUrl($(this).attr('href'))) {
	    e.preventDefault();
	  }
	  var clickedLinkParent;
	  if ($(this).parent().hasClass('firstlevel')) {
	    clickedLinkParent = $(this).parent();
	  } else {
	    clickedLinkParent = $(this).parent().parent().parent();	  
	  }
	  
	  var activeLink = $('#mainnav > .active');

	  var direction = $.fn.whichDirection(activeLink, clickedLinkParent);

	  $(this).linkClickHandler(direction);
	});
	
	
});
