var deviceAgent = navigator.userAgent.toLowerCase();
var isIOS = deviceAgent.match(/(iphone|ipod|ipad)/);
var isIOS4 = deviceAgent.match(/(4_)/);
var isIOS5 = deviceAgent.match(/(5_)/);

if(!isIOS)
{
Parallax={windowHeight:null,sections:null,_window:null,initialize:function(){this.sections=$("section");this._window=$(window);this.windowHeight=_window.height();this._window.bind("resize",$.proxy(this._move,this));this._window.bind("scroll",$.proxy(this._move,this))},_move:function(a){_window.trigger("scrolling");this.sections.each(function(){var c=$(this),b=_window.scrollTop();c.offset();var d=c.find("#breaker"),e=c.find("#banner");if(c.attr("id")!="welcome"){e.height();d.height();if(d.offset()!=null&&d.offset()!=undefined){c=280+(b-d.offset().top)/13;b=75-(b-d.offset().top)/6;e.css({top:c});d.css({"background-position":"center "+b+"px"})}}else if(c.attr("id")=="welcome")if(d.offset()!=null&&d.offset()!=undefined){var f=c.find("#stripes");c=(b-d.offset().top)/8;var j=242-(b-d.offset().top)/4;b=-70-(b-d.offset().top)/8;d.offset();e.css({top:c});f.css({top:j});d.css({"background-position":"center "+b+"px"})}});a.preventDefault()}};
} else {
	Parallax = {
		initialize:function()
		{
			$("#welcome #breaker").css({"background-position": "50% -70px"});
			$("#welcome #breaker").css({"background-attachment": "scroll"});
			$("#earn #breaker").css({"background-position": "50% -70px"});
			$("#earn #breaker").css({"background-attachment": "scroll"});
			$("#redeeming #breaker").css({"background-position": "50% -70px"});
			$("#redeeming #breaker").css({"background-attachment": "scroll"});
			$("#tiers #breaker").css({"background-position": "50% -70px"});
			$("#tiers #breaker").css({"background-attachment": "scroll"});
			$("#knowledge #breaker").css({"background-position": "50% -70px"});
			$("#knowledge #breaker").css({"background-attachment": "scroll"});
			$("#promotions #breaker").css({"background-position": "50% -70px"});
			$("#promotions #breaker").css({"background-attachment": "scroll"});
		}
	};
	
	if(deviceAgent.match(/(4_)/))
	{
		$('head').prepend('<meta name="viewport" content="width=1000; initial-scale=.78; maximum-scale=.78; minimum-scale=.78; user-scalable=no;"/>');
		$('main').css({overflowX: 'hidden', widht:1000});
	} else if(deviceAgent.match(/(5_)/))
	{
		$("#main_header").css({position:'absolute', width:980, overflowX:"hidden"});
		$("#arrow").css({position:'absolute', top:87});
	}
	
	$("section").find("#divider").each(function(item){
      var self = $(this);
      var homeButton = "<a href='#welcome'>";
      homeButton += "<img src='images/ios/ios_home.png' style='position:relative; left:67%; top:32px' />";
      homeButton += "</a>";
      self.append(homeButton) 
  });
}

Tracker={initialize:function(){},track:function(a,c,b){a=="_TrackPageView"?_gaq.push(["_trackPageview",TrackAddress[b]]):_gaq.push(["_trackEvent",b])}};TrackAddress={"/welcome":"_Welcome_Page","/earn":"_Earning_Flying_Page","/earn/flying":"_Earning_Flying_Page","/earn/partners":"_Earning_Partners_Page","/earn/credit_content":"_Earning_Partners_CreditCard_Page","/earn/dining_content":"_Earning_Partners_Dining_Page","/earn/hotels_content":"_Earning_Partners_Hotels_Page","/earn/rentals_content":"_Earning_Partners_RentalCars_Page","/earn/retail_content":"_Earning_Partners_MoreWays_Page","/earn/points":"_Earning_PurchasePoints_Page","/redeeming":"_Redeeming_Flight_Page","/redeeming/redeem":"_Redeeming_HowToRedeem_Page","/redeeming/rewards":"_Redeeming_OtherRewards_Page","/redeeming/step1":"_RedeemSimulator_Step1Enter_Button","/redeeming/step2":"_RedeemSimulator_Step2Enter_Button","/tiers":"_TiersMore_Page","/knowledge":"_KnowledgeCenter_TopQuestions_Page","/knowledge/terms":"_KnowledgeCenter_Terms_Page","/knowledge/General":"_KnowledgeCenter_General_Page","/knowledge/A-List":"_KnowledgeCenter_Alist_Page","/knowledge/A-ListPrefer":"_KnowledgeCenter_AlistPreferred_Page","/knowledge/CompanionPass":"_KnowledgeCenter_Companion_Page","/promotions":"_Promotions_Page"};

Nav = {
  // selected page
  lastScroll      : 0,
  currentSection  : null,
  oldSection      : null,
  currentMenuItem : null,
  oldMenuItem     : null,
  headerHeight    : null,
  arrow           : null,
  isScrolling     : false,
  defaultHeight   : {earn: 1940, redeeming: 2011},

  // initialize the navigation
  initialize : function (){
    if(window.location.hash != "")
    {
      var hash = window.location.hash
      if(hash == "#/knowledge")
        hash = "/knowledge/knowledge"
        
      Nav.gotHash = true;
      Nav.gotHashForSub = true;
    
      var sub;
      hash = hash.split("/");
      if(hash.length > 1)
      {
        sub = hash[2] || null;
        if(hash[2] == "General" || hash[2] == "CompanionPass" || hash[2] == "A-List"|| hash[2] == "A-ListPrefer")
        {
          $("#sub-knowledge").trigger("mouseenter");   
          SubNav.selectedSubItem = $("#sub-knowledge");
          $("#sub-knowledge").css("color", "#5987c6");
        }
        hash = hash[1]
      }  
       
      this.currentSection = $("#"+hash);
      
      setTimeout(function(){
        SubNav.historyThing($("#"+hash) , sub || null, 0)         
      }, 1000)

      $("#nav-"+hash).animate({ color: "#5987c6" }, 500); 
      // this.updateMenuItem("nav-"+hash);
    }
    else
    {
      this.currentSection = $("#welcome")
      $("#nav-welcome").animate({ color: "#5987c6" }, 500); 
      this.updateMenuItem("nav-welcome");
    } 
    
    this.oldSection = this.currentSection;
    // set menu items over/out states

    var scope = this;
    var d = document, w = window, documentElement = d.documentElement;
    
    // caching DOM ref
    this.headerHeight = $("#main_header").height();
    this.arrow        = $("#arrow");
    
    var menuitem = "";
    if(typeof scope.currentSection === Object)
     menuitem = scope.currentSection.attr("id");
    else
     menuitem = scope.currentSection;
    
    // Logo == home
    $("#logo").click(function(){
      //window.location.hash = "#/welcome";
      scope.findPage($("#welcome"));
    })
    
    
    $('a[id^="nav"]').each(function(e){
  
      var self  = $(this);
      var id = $(this).attr("id") || $(this).parent().attr("id");
      
      // on click, scrolls the content to the right position
      self.click(function(e){
       e.stopPropagation();
       var self  = $(this);
       var id = $(this).attr("id") || $(this).parent().attr("id"); 

        if(scope.currentMenuItem !== id)
        {
          scope.oldMenuItem = scope.currentMenuItem;
          // When i click, i don't want that "inview" event be dispactched
          scope.isScrolling = true;

          // Hello target!
          var self = $(this);

          var targetX = ($("#menu").position().left - ($("#menu").width() /2) ) + (self.position().left - 10)+ (self.width()/2);
          scope.moveArrow(targetX - 5)
          scope.oldSection = scope.currentSection;
          // Which is the section?
          scope.currentSection = self.attr("id").split("nav-").join("");

          var firstItem = $("#"+ scope.currentSection).find('a[id^="sub"]').first();
          if(firstItem.length > 0)
          {
            var id = firstItem.attr("id").split("sub-").join("");
            SubNav.resetPage($("#"+ scope.currentSection), id);
          }
  
          scope.updateMenuItem(self.attr("id"));
          
          if(!isIOS)
	          $("section #submenu").hide();

          // Ok, now we can dispatch "inview" event
          setTimeout(function(){
            scope.isScrolling = false;
            
            // Dispatch event to track new page
            Tracker.track("_TrackPageView", "Landing Page" ,"/"+ scope.currentSection);


            // EXTRA! EXTRA! 
            var hash = window.location.hash;
            var hashSection = hash.split("/");
            if(!(scope.currentSection == "knowledge" && hashSection.length >= 3))
            {
              $("#"+scope.currentSection).trigger(ENTER_PAGE);
            } 
            
          }, 1105)

        }

         // Taxi! Wanna go to this address...
        scope.findPage($("#"+ scope.currentSection));

        window.location.hash = "/"+ scope.currentSection;
        if(!isIOS)
        {
	        setTimeout(function(){
        	  if(! $("#"+id).find("#submenu").hasClass("fixed"))
    	      {
	            // var sectioname = self.attr("id").split("nav-").join("");
            	$("#"+id).find("#submenu").show();  
        	    $("#"+id).find("#submenu").addClass("fixed");  

    	      }
          
	        }, 1105);
        }
        
          // I don't wanna the default behaviour
          e.preventDefault(); 
      })
      
      self.hover(
        function(event){
          if(scope.currentMenuItem != $(this).attr("id"))
          {
            $(this).animate({ color: "#5987c6" }, 500); 
            event.preventDefault();
          }
        }, 
        function(event){
          if(scope.currentMenuItem != $(this).attr("id"))
          {
            $(this).animate({ color: "#6666" }, 500);
            event.preventDefault();
          }
        }
      );
      
    })
    
    var targetX = $("#nav-"+ scope.currentSection.attr("id")).offset().left + ($("#nav-"+ scope.currentSection.attr("id")).width() /2) -9;
    $("#arrow").css({"marginTop":"-20px"});
    $("#arrow").css({ "left": targetX - 5},0);

    $("#arrow").animate({ "marginTop": "0"},600);
 
    // when the page is resized we need to update arrow position
    $(window).bind("resize", function(){
     var self = $("#" + scope.currentMenuItem)
     if(scope.currentMenuItem)
     {
       var targetX = ($("#menu").position().left - ($("#menu").width() /2) ) + (self.position().left - 10)+ (self.width()/2);
         // scope.moveArrow(targetX)  
       }
    })
    
    
    
    
    $('section').each(function(){
      var anchor = $(this).find("#contentMask").length > 0 ? $(this).find("#contentMask") : $(this).find("#mask");
      // check which section is visible to set the new position to the arrow
      anchor.bind('inview', function (event, isVisible, visiblePartX, visiblePartY) {

        if ( ! isVisible )
        {
          
          var thisSection = $(this);
          // EXTRA! EXTRA! 
          
          $(event.target).parent().trigger(LEAVE_PAGE);
          if(thisSection.parent().attr("id") == "tiers")
          {
            thisSection.find("#close_left").trigger("click");
            thisSection.find("#close_right").trigger("click");
          }
          if(!scope.isScrolling)
          {
            var firstItem = $("#"+ scope.currentSection).find('a[id^="sub"]').first();
            if(firstItem.length >0)
            {
              if(!Nav.gotHash)
              {
                var id = firstItem.attr("id").split("sub-").join("");
                // SubNav.resetPage($("#"+ scope.currentSection), id);
              }
              else
              {
                Nav.gotHash = false;
              }
          
            }
          }
 
        }
        else if (isVisible)
        {
          $(event.target).parent().trigger(SHOW_SUB)
        }

        // If i'm scrolling because I clicked on menu, I'll not do anything here
        if(! scope.isScrolling)
        {

          var sectionId = $(event.target).parent().attr("id");
          
          // if I'm scrolling up I need to check if the bottom of next page is visible
          // otherwise, I need to check the top
          var direction = scope.lastScroll - (w.pageYOffset || documentElement.scrollTop || d.body.scrollTop) > 0 ? "bottom" : "top"
          scope.lastScroll = w.pageYOffset || documentElement.scrollTop || d.body.scrollTop
          var rightDirection = false;
          if($(this).attr("id") == "mask")
          {
            if(visiblePartY == "top" || visiblePartY == "bottom")
              rightDirection = true;
          }
          else
          {
            if(visiblePartY == direction)
              rightDirection = true
          }
          
          // is this visible? is this section already selected? Do I know if I'm seeing the top or bottom?
          if (isVisible && scope.currentSection != sectionId && rightDirection ) {

            var element = $("#nav-"+sectionId);
            var targetX   = ($("#menu").position().left - ($("#menu").width() /2) ) + (element.position().left - 10)+ (element.width()/2);
            scope.moveArrow(targetX - 5)
                      
            scope.currentSection  = sectionId;
                      
            //rollover
            element.trigger("mouseenter")
                      
            //update menu item reference
            scope.updateMenuItem("nav-"+sectionId);
                    
                    
            // EXTRA! EXTRA! 

            $(event.target).parent().trigger(ENTER_PAGE)

                      
            // Dispatch event to track new page
            Tracker.track("_TrackPageView", "Landing Page" ,"/"+ scope.currentSection);
            var hash = window.location.hash.split("/");
            
            if(!Nav.gotHashForSub)
            {
                if(sectionId != hash[1] && SubNav.isScrolling)
                  window.location.hash = "/" + sectionId;              
            }
            else
            {
                Nav.gotHashForSub = false;
            }
            
                        
            $(event.target).parent().trigger(SHOW_SUB); 
          }
          
        }
        
      });
    });
  },
  
  // scroll to the page
  findPage : function(section, time){
    // Let's keep this info for latter
    var oldSection ="";
    
    // if(time == null || time == undefined)
      // time = 0;
    
    if(typeof Nav.oldSection =="object")
      oldSection = Nav.oldSection.attr('id'); 
    else
      oldSection = Nav.oldSection; 

    var difference = 0;
    if(oldSection == "earn")
    {
        difference = Nav.defaultHeight.earn-$("#" + oldSection).height();
    } else if(oldSection == "redeeming")
    {
        difference = Nav.defaultHeight.redeeming-$("#" + oldSection).height();
    }

    var _target;
    
    if(section.find("#contentMask").find("#content").offset()!=null)
      _target = Math.floor(section.find("#contentMask").find("#content").offset().top - this.headerHeight) + 1;
    else
      _target = 0;
    
    

    var scope = this;
    var d = document, w = window, documentElement = d.documentElement;
    var _currentTop = (w.pageYOffset || documentElement.scrollTop || d.body.scrollTop);
    if(_currentTop != _target)
    {
        $('html, body').animate({scrollTop:_target}, 650, "easeOutCubic", function(){
          section.trigger(SHOW_SUB); 
          Nav.isScrolling = false;
        });
    }
    else
    {
      Nav.isScrolling = false;
    }
     Nav.oldSection = Nav.currentSection; 
  },
  
  // Update reference of selected menu item
  updateMenuItem : function(item)
  {

    // turn off the old menu item
    if(this.currentMenuItem != null && this.currentMenuItem != item )
    {
       var oldMenuItem = $("#"+ this.currentMenuItem);
       this.currentMenuItem = null;
       oldMenuItem.trigger("mouseleave");
    } 

    // update reference
    this.currentMenuItem = item;
    
  },
  
  moveArrow : function(to)
  {
      // Fly little arrow, fly!
      this.arrow.stop().animate({ left:to, marginTop:0  }, 1000, "easeInOutExpo" );    
  }
}








var userAgent = navigator.userAgent.toLowerCase(); 
$.browser.chrome = /chrome/.test(navigator.userAgent.toLowerCase());

VideoPlayer = {
	openvideo : function(path, videoTitle)
	{
		var scope = this;

		
		$("#lightbox").fadeOut(0);
		$("#vp_holder").hide();
		
		if(isIOS)//4)
		{
			$("#lightbox").css({top:$(window).scrollTop()-400, height:2500});
			$("#vp_content").css({top:$(window).scrollTop()+500});
			$("#vp_closeButton").css({top:$(window).scrollTop()+500});
			$("#vp_closeButton").click(function(){scope.closevideo()});
			$("#vp_hit").click(function(){scope.closevideo()});
			
			if(isIOS5)
			{
				$("#lightbox").css({position:"absolute"});
				$("#vp_content").css({position:"relative"});
				$("#vp_closeButton").css({position:"relative"});
				

				$("#vp_holder").css({top:95});
				$("#vp_label").css({top:120});				
			
				if(window.orientation == 0 || window.orientation == 180 || window.orientation == -180)
				{
					$("#vp_closeButton").css({top:360});
					$("#vp_content").css({top:700});
				}else {
					$("#vp_content").css({top:450});
					$("#vp_closeButton").css({top:110});
				}
				
			}
		} /*else if(isIOS5)
		{
			$("#lightbox").css({top:0, height:2000});
			$("#vp_content").css({top:400});
			$("#vp_closeButton").css({top:400});
			$("#vp_closeButton").click(function(){scope.closevideo()});
			$("#vp_hit").click(function(){scope.closevideo()});
		}*/
				
		scope.videoTitle = videoTitle;
		scope.path = path;
		scope.holder = document.getElementById("vp_holder");
		
		$("#lightbox").css({visibility: 'visible'});
		

		
		if(!isIOS || isIOS4)
		{
			$("#lightbox").fadeIn('slow', function(){
					VideoPlayer.showVideo(scope)
				}
			);
		}
		else
		{
			$("#lightbox").css({visibility: "visible", display: "block"});
			VideoPlayer.showVideo(scope);
			setTimeout(function(){window.scrollTo($('body').scrollTop(), $('body').scrollTop()-2); }, 500);
		}
	}, 
	
	showVideo : function(scope){
			$("#vp_label").html(scope.videoTitle);

			if(!$.browser.msie)
			{
				
				
				scope.video = document.createElement('video');
				
				scope.holder.appendChild(scope.video);

				scope.video.controls = true;
				scope.video.width = 545;
				scope.video.height = 362;
			
				if($.browser.chrome)
				{
   					scope.video.src = scope.path+".webm";
  				} else if($.browser.mozilla)
				{
					scope.video.src = scope.path+".ogv";
  				} else {
  					scope.video.src = scope.path+".mp4";
  				}
				
				scope.video.play();

  				scope.video.addEventListener('play', function(){
					$("#vp_holder").css({visibility:'visible'});
					$("#vp_closeButton").click(function(){scope.closevideo()});
					$("#vp_hit").click(function(){scope.closevideo()});
				},false);
			} else {
				path = getDomain()+scope.path+".flv";
				image = getDomain()+"/images/common/video.jpg";
				$("#vp_closeButton").click(function(){scope.closevideo()});
				$("#vp_hit").click(function(){scope.closevideo()});
				$("#vp_holder").html('<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" class="vjs-flash-fallback" width="545" height="362" type="application/x-shockwave-flash" data="http://releases.flowplayer.org/swf/flowplayer-3.2.1.swf"><param name="movie" value="http://releases.flowplayer.org/swf/flowplayer-3.2.1.swf" /><param name="allowfullscreen" value="true" /><param name="flashvars" value=\'config={"playlist":["'+image+'", {"url": "'+path+'","autoPlay":true,"autoBuffering":true}]}\' /><div style="position: relative; top:50% ; text-align:center; color: #ccc">This website is optimized for HTML5 compatible browsers.<br/>To use Adobe Flash, please <a href="http://get.adobe.com/flashplayer/" style="color: #fff; text-decoration:underline">download here</a></div></object>');
			}
			$("#vp_holder").show();
			
  		},

	closevideo : function()
	{
		var scope = this;
		$("#vp_holder").hide();
		$("#vp_closeButton").unbind('click');
	  	$("#vp_hit").unbind('click');
	  	if(!$.browser.msie)
	  	{
	  		scope.holder.removeChild(scope.video);
			scope.video.pause();
			scope.video.src="";
			scope.video = null;
		} else 
		{
			$("#vp_holder").html("");
		}
		$("#vp_label").html("");
		$("#lightbox").fadeOut('slow', function(){$("#lightbox").css({visibility: 'hidden'})});
	}
}




SubNav = {
  currentSection  : null,
  currentMenuItem : null,
  content : null, 
  count : 0,
  hash : "",
  extraSpace: 0,
  hashEnabled : true,
  interval : null,
  selectedSubItem : null, 
  isScrolling : false,
  // initialize the navigation
  initialize : function (){

    var scope = this;

    scope.gotoPage("tiers", "tiers"); 
    scope.gotoPage("promotions", "promotions"); 

    $(window).bind('scrollstart', function(){
      $(window).unbind("hashchange");
      SubNav.isScrolling = true;
    });


    $(window).bind('scrollstop', function(e){
        $(window).bind("hashchange", scope.followHash);
        SubNav.isScrolling = false;
    })
	
    // double check to show submenu
    if(!isIOS)
    {
	    $("section").each(function(){
    	  var self = $(this);
	      self.bind(SHOW_SUB, function(){
        

        
    	    $("section").find("#submenu").removeClass("fixed");
        	$("section").find("#submenu").hide();
	        $("section").find("#page_label").removeClass("fixed");
    	    $("section").find("#page_label").hide();
        
        	var currentMajorSection = $(this);
	        if(currentMajorSection)
    	    {
        	  var menuBox = currentMajorSection.find("#submenu");
	          var label = currentMajorSection.find("#page_label");

    	      label.stop().show();
        	  menuBox.stop().show();
	          _window.bind('scroll', $.proxy(scope.moveMenu,scope));
    	    }
	      });
    	});
    }
    
    // when you show the page, it goes to the first sub
    $("section").each(function(){
      var self = $(this);
      self.bind(ENTER_PAGE, function(){


        var currentMajorSection = $(this);
        
		if(!isIOS)
        	$("section").find("#submenu").removeClass("fixed");

        if(currentMajorSection.find('a[id^="sub"]').length <= 0)
        { 
          
          return false;
        }

        SubNav.onEnterPage($(this))

        var firstItem = currentMajorSection.find('a[id^="sub"]').first();
        if(firstItem.length <=0)
          return;
    
        if(scope.count < 1)
          return false;

        var id = firstItem.attr("id").split("sub-").join("");
        
        SubNav.selectedSubItem.css("color" , "#666");

        firstItem.css("color", "#5987C6");
        SubNav.selectedSubItem = firstItem;

        var hash = window.location.hash;
        var hashSection = hash.split("/");
        if(!(hashSection[1] == "knowledge" && hashSection.length >= 3))
        scope.resetPage($(this), id);
        scope.currentSection = currentMajorSection;
      });
    });
    
    $("section").each(function(){
      var self = $(this);
      self.bind(LEAVE_PAGE, function(){
        
        // _window.unbind('scroll', $.proxy(scope.moveMenu,scope));
        var currentMajorSection = $(this);
           
        if(!isIOS)
        {
        	$(this).find("#submenu").hide();
        }
        currentMajorSection.removeClass("visible");

        scope.count = 0;
		if(!isIOS)
        {
        	if(currentMajorSection)
	        {
    	      $("section").find("#page_label").removeClass("fixed");
        	  $("section").find("#submenu").removeClass("fixed");
	          var menuBox = currentMajorSection.find("#submenu");
    	      var label = currentMajorSection.find("#page_label");

             
	         if(label)
        	 {
        	    label.stop().show();
    	        label.removeClass("fixed");
	            menuBox.stop().show();
            	menuBox.removeClass("fixed");
          	 }
		   }
        }
      
        var firstItem = $(this).find('a[id^="sub"]');
        if(firstItem.length <= 0)
          return;
        
        firstItem = firstItem.first();
        var id = firstItem.attr("id").split("sub-").join("");
        if(SubNav.selectedSubItem != null)
          SubNav.selectedSubItem.css("color" , "#666");
        
        firstItem.css("color", "#5987C6");
        SubNav.selectedSubItem = firstItem;

        if(!Nav.isScrolling)
        {
          scope.resetPage($(this), id);  
        }
                       
  
        });
    })    

  	$('a[id^="sub"]').each(function(e){
        var self = $(this);
        
        self.bind("click",function(e){

          // _window.unbind("hashchange");
          scope.hashEnabled = false;

          scope.count ++;
          $(this).css("color", "#666");
          SubNav.selectedSubItem = $(this);
          var subItems = $(this).parent().find('a[id^="sub"]');
          subItems.each(function (){
            var element = $(this);
            element.trigger("mouseleave");
          });
          
          var section = null;
          try{
            section = scope.currentSection.attr("id")
          }
          catch(e)
          {
            section = $("#"+scope.currentSection).attr("id")
          }
          
          
          var sec = $(this).parent().parent().parent().parent().parent().parent().attr("id")
          if(sec == "content")
            sec = $(this).parent().parent().parent().parent().parent().attr("id")
          else if (sec == 'main')
            sec = $(this).parent().parent().parent().parent().attr("id")

      
          var currentSubSection =  self.attr("id").split("sub-").join("");
          scope.currentSection = currentSubSection;


          scope.gotoPage(sec, scope.currentSection);
          
          var hash = window.location.hash;

          if(hash.split("/").length > 1)
            hash = hash.split("/")[1];
          
          hash = "/"+ sec + "/" + currentSubSection;
          window.location.hash = hash;

          self.css("color", "#5987c6");
          SubNav.selectedSubItem = self;
          
          Tracker.track("_TrackPageView", "Landing Page" , "/"+sec+"/"+currentSubSection);

          setTimeout(function(){
            // _window.bind("hashchange", scope.followHash);
            Nav.currentSection = sec
          }, 1100)
      })
        

    });
    
    // check section and subsection from deeplink
    var hashSection = window.location.hash.split("/");
    scope.hash = "";
    if(hashSection.length >= 2)
    {    
        scope.hash = hashSection[2];
        scope.gotoPage(Nav.currentSection.attr("id"), scope.hash)
        Nav.currentSection.find("#sub-" + scope.hash)
    }    
        
    // select the current submenu item
    $("section").each(function(item, section){
      var self = $(this);
      var subItems = self.find('a[id^="sub"]');
      var firstItem = "";
      if(subItems.length > 0)
      {
        firstItem = subItems.first();
        if(self.attr("id") == hashSection[1] && scope.hash != "" && scope.hash != undefined)
          firstItem = self.find('a[id^="sub-'+ scope.hash +'"]');
          
        var msection = self.attr("id");
        try
        {
          var sub = firstItem.attr("id").split("sub-").join("");  
        }
        catch(e)
        {
          return false;
        }
        
       scope.gotoPage(msection, sub);
        
        var subItems = $(this).find('a[id^="sub"]');
        subItems.each(function (){
          var element = $(this);

          element.hover(function(e){
              e.preventDefault();
              var name = SubNav.selectedSubItem != null ? SubNav.selectedSubItem.attr("id") : null;
              
              if(element.attr("id") != name)
                element.css("color", "#5987c6");
            }, 
            function(e){
              e.preventDefault();
              var name = SubNav.selectedSubItem != null ? SubNav.selectedSubItem.attr("id") : null;
                            
              if(element.attr("id") != name)
                element.css("color", "#666");
          });
        })

      }  
    });


    setTimeout(function(){
      _window.bind("hashchange", scope.followHash);
    }, 100)
    
  },

  gotoPage : function(mainSection, id, time){
  	if(mainSection == "knowledge")
		KnowledgeManager.currentCat = id;
		
    if(id == undefined)
       return; 
    mainSection = String(mainSection)
    var m = $("#" + mainSection);
    var content = m.find("#rightColumn");
    var contentHolder = m.find("#contentHolder");
    var duration = time||0 ;

    if(this.count > 0 && mainSection != "tiers" && mainSection != "promotions")
    {
      duration = 300;
      content.fadeOut(duration,  function () {
        loadContent(contentHolder, content, "pages/"+mainSection+"/"+id+".html");
      });
    }
    else
    {
      loadContent(contentHolder, content, "pages/"+mainSection+"/"+id+".html");
    }
	},
  
  resetPage : function (section, id){
      var scope = this;
      var content = section.find("#rightColumn");
      var contentHolder = section.find("#contentHolder");

      if( id != null)
      {
        var subItem = section.find('nav-'+ id);
      }
      else
      {
        var subItem = section.find('a[id^="sub"]').first();

      }
      

      subItem.trigger("mouseenter");        
      SubNav.selectedSubItem = subItem;
      subItem.trigger("mouseleave")
      
      content.html("<br/>");  
      content.load("pages/"+section.attr("id")+"/"+id+".html?timestamp="+ Math.random()*99999, function(){
		var height = content.height();

		if(height < _window.height())
			height = _window.height()-85; 
			

			
		contentHolder.height(height+40);
		scope.count = 0;
      });
  },
  
	moveMenu : function()
	{
		if(!isIOS)
		{
			if(Nav.currentSection != "welcome")
			{
				var currentMajorSection
				if(Nav.currentSection instanceof Object)
					currentMajorSection = Nav.currentSection;
				else
					currentMajorSection = $("#"+Nav.currentSection);
        
        
				var menuBox = currentMajorSection.find("#submenu");
				var label = currentMajorSection.find("#page_label");
				var contentOffset = parseInt(currentMajorSection.find("#contentMask").offset().top, 10);
				var areaHeight = parseInt(currentMajorSection.find("#contentHolder").height(),10);
				var height = parseInt((_window.scrollTop()-contentOffset), 10);
				var totalAreaHeight = parseInt((areaHeight-menuBox.height()-90), 10);
      

				if(menuBox.offset()!=null)
				{
					if((height > 5 && height < totalAreaHeight && menuBox.offset().top + menuBox.height() < contentOffset + areaHeight) )
					{        
						if(!menuBox.hasClass('fixed'))
							menuBox.addClass('fixed');
					}  
					else
					{  
						if(menuBox.hasClass('fixed'))
						menuBox.removeClass('fixed');
					}

					var bgHeight = 649;
      
					if(height > 5 &&  height < bgHeight)
					{
						if(!label.hasClass("fixed"))
							label.addClass("fixed"); 
					}
					else
					{
						if(label.hasClass("fixed"))
							label.removeClass("fixed");
					}        
				}
			}
		}
	},

  followHash : function (e)
  {

      e.preventDefault();
      var scope = this;
      var hash = window.location.hash.split("/");
      
      if(Nav.isScrolling)
        return

      Nav.isScrolling = true;
      if(hash.length <= 1)
        hash[1] = "welcome"
        
      SubNav.historyThing($("#"+ hash[1]), hash[2] || null, 1000)

    },
    
    historyThing : function (area, sub, time)
    {
      var scope = this;
      var areaName = "nav-"+area.attr("id")
      
      Nav.findPage(area, time);
      
      var menuItem = $("#"+areaName);
      
      menuItem.animate({ color: "#5987c6" }, 500); 
      var targetX = ($("#menu").position().left - ($("#menu").width() /2) ) + (menuItem.position().left - 10)+ (menuItem.width()/2);
      Nav.moveArrow(targetX)
      Nav.updateMenuItem(areaName)

      // if(area.attr("id") == "tiers" || area.attr("id") == "promotions" || area.attr("id") == "welcome")
        // return;
      
      var subItem;

      SubNav.currentSection = null;
      area.find('a[id^="sub"]').trigger("mouseleave");
            
      if(sub)
      {
          subItem = area.find("#sub-"+ sub);
          subItem.trigger("mouseenter");        
          // SubNav.selectedSubItem = subItem;
      }
      else
      {
        subItem = area.find('a[id^="sub"]').first()
        if(subItem != null)
        {
          var name = subItem.attr("id") || "";
          if(name.indexOf("sub-")>=0)
            sub = name.split("sub-").join("");
          else
            sub = null;

          subItem.trigger("mouseenter");        
          
          // SubNav.selectedSubItem = subItem;

        }
      }

      if(sub == "General" || sub == "CompanionPass" || sub == "A-List"|| sub == "A-ListPrefer")
      {
       subItem = area.find("#sub-knowledge");
       subItem.trigger("mouseenter");        
       // SubNav.selectedSubItem = subItem;
       area.find("#sub-knowledge").css("color", "#5987c6");
      }

      
      SubNav.gotoPage(area.attr("id"), sub)      
      Nav.currentSection = area.attr("id");

      // if(area.attr("id") == "tiers" || area.attr("id") == "promotions" || area.attr("id") == "welcome")
          // return;

      
      if(subItem)
        subItem.css("color", "#5987c6");

      area.find('a[id^="sub"]').trigger("mouseleave");
      setTimeout(function(){
        subItem.trigger("mouseenter")
        SubNav.selectedSubItem = subItem;
        area.find('a[id^="sub"]').each(function()
        {
          $(this).trigger("mouseleave");
        })
        
      }, 1100)
      
        area.find('a[id^="sub"]').trigger("mouseleave");
    },
    
    onEnterPage: function(area)
    {
      
        var scope = this;
        var areaName = "nav-"+area.attr("id")

      
       SubNav.currentSection = null;
       
       area.find('a[id^="sub"]').trigger("mouseleave")
       var hash = window.location.hash.split("/");
       sub = hash[2] || null
 
       if(sub)
       {
           subItem = area.find("#sub-"+ sub);
           subItem.trigger("mouseenter");        
           SubNav.selectedSubItem = subItem;
       }
       else
       { 
         subItem = area.find('a[id^="sub"]').first()
         if(subItem != null)
         {

           var name = subItem.attr("id") || "";
           if(name.indexOf("sub-")>=0)
             sub = name.split("sub-").join("");
           else
             sub = null;

           subItem.trigger("mouseenter");        
           SubNav.selectedSubItem = subItem;

         }
       }
       area.find('a[id^="sub"]').trigger("mouseleave")
    }
}

Hotels={subbrands:{wyndham:"Wyndham Hotels and Resorts<sup>@</sup><br/>Wyndham Grand Collection<sup>@</sup><br/>Wyndham Garden<sup>@</sup><br/>Wingate<sup>@</sup> by Wyndham<br/>Ramada<sup>@</sup><br/>Days Inn<sup>@</sup><br/>Super 8<sup>@</sup><br/>Baymont Inn & Suites<sup>@</sup><br/>Microtel Inn & Suites<sup>@</sup><br/>Howard Johnson<sup>@</sup><br/>Travelodge<sup>@</sup> (U.S. Hotels only)<br/>Knights Inn<sup>@</sup>",marriot:'JW Marriott<sup>@</sup><br/>EDITION<sup style="font-size:8px">SM</sup><br/>Autograph Collection<sup>@</sup><br/>Renaissance<sup>@</sup> Hotels<br/>AC Hotels by Marriott<br/>Marriott<sup>@</sup> Hotels and Resorts<br/>Courtyard by Marriott<sup>@</sup><br/>Fairfield Inn & Suites by Marriott<sup>@</sup><br/>SpringHill Suites by Marriott<sup>@</sup><br/>Residence Inn by Marriott<sup>@</sup><br/>TownePlace Suites by Marriott<sup>@</sup><br/>Marriott Vacation Club<sup>@</sup><br/>Marriott Executive Apartments<sup>@</sup>',hyatt:"Park Hyatt<sup>@</sup><br/>Andaz<sup>@</sup><br/>Grand Hyatt<sup>@</sup><br/>Hyatt Regency<br/>Hyatt Place\u2122<br/>Hyatt Summerfield Suites\u2122",spg:"Sheraton<sup>@</sup><br/>Four Points by Sheraton<sup>@</sup><br/>St. Regis<sup>@</sup><br/>Luxury Collection<sup>@</sup><br/>Le Meridien<sup>@</sup><br/>W Hotels<sup>@</sup><br/>Westin<sup>@</sup><br/>aLoft<sup>@</sup><br/>element <sup>@</sup>",choice:"Comfort Inn<sup>@</sup><br/>Comfort Suites<sup>@</sup><br/>Quality<sup>@</sup><br/>Sleep Inn<sup>@</sup><br/>Clarion<sup>@</sup><br/>Cambria Suites<sup>@</sup><br/>MainStay Suites<sup>@</sup><br/>Suburban Extended Stay<sup>@</sup><br/>Econo Lodge<sup>@</sup><br/>Rodeway Inn<sup>@</sup><br/>Ascend Collection<sup>@</sup>"},positions:{wyndham:{x:220,y:83},marriot:{x:435,y:73},hyatt:{x:295,y:250},spg:{x:220,y:330},choice:{x:220,y:208}},initialize:function(){var a=this,c=$(".flyout");c.animate({opacity:0},1,function(){c.css({visibility:"hidden"})});$('div[id^="hotel-"]').each(function(){var b=$(this),d=b.attr("id").split("hotel-").join("");a.subbrands[d]!=null&&b.css({cursor:"pointer"});b.hover(function(){var e=$("#hotel_box"),f=$("#hotels_arrow");e.html(a.subbrands[d]);if(a.subbrands[d]!=null){if(d=="hyatt"){if(f.hasClass("left_arrow")){f.removeClass("left_arrow");f.addClass("right_arrow")}}else if(f.hasClass("right_arrow")){f.removeClass("right_arrow");f.addClass("left_arrow")}f.css({top:-((50+e.height())/2)});c.css({opacity:0});c.css({left:a.positions[d].x,top:a.positions[d].y});c.css({visibility:"visible"});c.animate({opacity:1},150)}},function(){if(a.subbrands[d]!=null){c.css({opacity:0});c.css({visibility:"hidden"})}})})}};Earn={statusValue:null,fareType:null,fareLabel:null,initialize:function(){var a=$("#flying").find("#step1").find("#option-item").radioButton(),c=$("#flying").find("#step2").find("#option-item").radioButton(),b=this;a.bind("changed",function(d){b.statusValue=$(d.target).attr("data-value");if(b.statusValue==0)$("#flying").find("#step1").find("#text").html("");else b.statusValue==25?$("#flying").find("#step1").find("#text").html("A-List earns 25% more points for each dollar spent."):$("#flying").find("#step1").find("#text").html("A-List Preferred earns 100% more points for each dollar spent.");b.updateResult()});c.bind("changed",function(d){b.fareType=$(d.target).attr("data-value");b.fareLabel=$(d.target).parent().find("#label").html();b.updateResult()});$("#flying").parent().parent().parent().css({height:1160});$("#flying").parent().parent().parent().parent().css({height:1240});a.first().trigger("click");c.first().trigger("click");

setTimeout(function(){$('#earn #submenu').find('a[id^="sub"]').each(function(){if(this.id!="sub-flying"){$(this).trigger("mouseleave");}else{$(this).trigger("mouseenter");}})}, 1000);

}, updateResult:function () {
	if (this.fareType && this.statusValue) {
		var a = this.fareType * 250, c = $("#flying").find("#orangeResult").find("span"), b = $("#earn_simulator");
		if (this.statusValue == 0) {
			$("#multipleResults").hide();
			$("#singleResult").show();
			c = $("#flying").find("#singleResult").find("#result").find("span");
			b.animate({height:470}, 250);
			$.browser.mozilla ? $("#flying").find("#content").animate({height:1019}, 250) : $("#flying").find("#content").animate({height:1015}, 250)
		} else {
			$("#multipleResults").show();
			$("#singleResult").hide();
			$("#multipleResults").find("#plusMod").find("#percentageLabel").html(this.statusValue + "%");
			if (this.statusValue == 100) {
				$("#multipleResults").find("#plusMod").find("#label").html("(A-LIST PREFERRED BONUS)");
				$("#multipleResults").find("#plusMod").find("#label").css({marginBottom:35});
				$.browser.mozilla ? $("#flying").find("#content").animate({height:1184}, 250) : $("#flying").find("#content").animate({height:1180}, 250);
				b.animate({height:690}, 250)
			} else {
				$("#multipleResults").find("#plusMod").find("#label").html("( A-LIST BONUS )");
				$("#multipleResults").find("#plusMod").find("#label").css({marginBottom:20});
				$.browser.mozilla ? $("#flying").find("#content").animate({height:1164}, 250) : $("#flying").find("#content").animate({height:1160}, 250);
				b.animate({height:610}, 250)
			}
			$("#flying").parent().parent().parent().css({height:1310});
			$("#flying").parent().parent().parent().parent().css({height:1400});
			c = $("#flying").find("#multipleResults").find("#orangeResult").find("span")
		}
		var d = $("#flying").find("#results").find("#operand").first().find("#giganticLabel"), e = $("#flying").find("#results").find("#operand").first().find("#label"), f = this.fareType, j = this.fareLabel, h = $("#flying").find("#blueResult").find("span");
		h.delay(550).animate({opacity:1}, 150);
		h.html("");
		h.animate({opacity:0}, 1, function () {
			h.html(removeDot($().numberFormat(a)) + " Pts.")
		});
		h.animate({opacity:1}, 150);
		var g = Math.ceil(this.statusValue / 100 * a + a);
		c.animate({opacity:0.01}, 150, function () {
			c.html(removeDot($().numberFormat(g)) + " Pts.")
		});
		c.delay(550).animate({opacity:1}, 150);
		if (d.html() != f + " Pts.") {
			d.animate({opacity:0.01}, 150, function () {
				d.html(f + " Pts.");
			});
			d.delay(550).animate({opacity:1}, 150, function() { $(this).css('filter', 'none') });
			e.animate({opacity:0.01}, 150, function () {
				e.html("( " + j + " )")
			});
			e.delay(550).animate({opacity:1}, 150)
		}
	}
}};
Partners = {initialize:function () {


	if(isIOS4)
	{
		$(".credit_content_block").each(function(){$(this).height(165)});
		$(".credit_content_block").last().height(185);
		$("#credit_content").height(1120);
	}


var a=this;$("#partners").find("#slider1").find("#real_slider").slider({range:"min",value:0,min:0,max:1E4});$("#partners").find("#slider2").find("#real_slider").slider({range:"min",value:0,min:0,max:100});$("#partners").find("#slider3").find("#real_slider").slider({range:"min",value:0,min:0,max:1500});$("#partners").find("#slider4").find("#real_slider").slider({range:"min",value:0,min:0,max:25});$("#partners").find("#slider5").find("#real_slider").slider({range:"min",value:0,min:0,max:30});$("#partners").find('div[id^="slider"]').bind("slide",function(c,b){var d=$(this).attr("id").substring(1,7);a["updateS"+d](c,b,a)});$("#partners").find('div[id^="slider"]').bind("slidechange",function(c,b){var d=$(this).attr("id").substring(1,7);a["updateS"+d](c,b,a)});$("#partners").find('div[id^="slider"]').each(function(){$(this).slider("value",1)})

setTimeout(function(){$('#earn #submenu').find('a[id^="sub"]').each(function(){if(this.id!="sub-partners"){$(this).trigger("mouseleave");}else{$(this).trigger("mouseenter");}})}, 1000);

},



updateResult:function(){Tracker.track("_TrackEvent","On Click","_Earning_Shopping_Simulator_Slider");var a=0;$("#partners").find('div[id^="item"]').each(function(){var c=$(this).find("#result").find("#label").html().split(" Pts.").join("");c=c.split(",").join("");a+=parseInt(c,10)});$("#partners").find("#results").find("#result").find("#totalLabel").html(this.ptsOrPoints(a))},updateSlider1:function(a,c,b){a=$("#item1").find("#valueLabel");var d=$("#item1").find(".ui-slider-handle");a.css({left:235+(d.position().left-a.width()/2)});a.html("$"+removeDot($().numberFormat(c.value)));$("#item1").find("#result").find("#label").html(b.ptsOrPoints(c.value*12));b.updateResult()},updateSlider2:function(a,c,b){a=$("#item2").find(".ui-slider-handle");var d=$("#item2").find("#valueLabel");d.css({left:235+(a.position().left-d.width()/2)});d.html(c.value+" times");$("#item2").find("#result").find("#label").html(b.ptsOrPoints(c.value*600));b.updateResult()},updateSlider3:function(a,c,b){a=$("#item3").find(".ui-slider-handle");var d=$("#item3").find("#valueLabel");d.css({left:235+(a.position().left-d.width()/2)});d.html("$"+removeDot($().numberFormat(c.value)));$("#item3").find("#result").find("#label").html(b.ptsOrPoints(c.value*36));b.updateResult()},updateSlider4:function(a,c,b){a=$("#item4").find(".ui-slider-handle");var d=$("#item4").find("#valueLabel");d.css({left:235+(a.position().left-d.width()/2)});d.html(c.value+" times");$("#item4").find("#result").find("#label").html(b.ptsOrPoints(c.value*600));b.updateResult()},updateSlider5:function(a,c,b){a=$("#item5").find(".ui-slider-handle");var d=$("#item5").find("#valueLabel");d.css({left:235+(a.position().left-d.width()/2)});d.html(c.value+" times");$("#item5").find("#result").find("#label").html(b.ptsOrPoints(c.value*600));b.updateResult()},ptsOrPoints:function(a){return a>0?removeDot($().numberFormat(a))+" Pts.":removeDot($().numberFormat(a))+" Points"}};Tabs={currentSection:null,currentMenuItem:null,offsets:{credit:0,dining:-771,hotels:-1542,rentals:-2310,retail:-3080},currentItem:null,initialize:function(){$("#tabs_menu");var a=this;$(".tab_menu_item").each(function(){var c=$(this);c.bind("click",function(){a.setContent($(this).attr("id"))});c.hover(function(){$(this).attr("id")!=a.currentMenuItem.attr("id")&&$(this).css({backgroundPosition:"0px -41px"})},function(){$(this).attr("id")!=a.currentMenuItem.attr("id")&&$(this).css({backgroundPosition:"0px 0px"})})});fixButtons();if($.browser.msie){$("#credit_content").fadeOut().hide();$("#dining_content").fadeOut().hide();$("#hotels_content").fadeOut().hide();$("#rentals_content").fadeOut().hide();$("#retail_content").fadeOut().hide()}a.setContent("credit")},setContent:function(a){var c=$("#"+a),b=$("#"+c.attr("id")+"_content");if(b!=this.currentSection){var d=b.height();a=this.offsets[a];this.currentMenuItem!=null&&this.currentMenuItem.css({backgroundPosition:"0px 0px"});c.css({backgroundPosition:"0px -41px"});$("#tabMask").animate({height:d},330,"easeInOutCirc");if($.browser.msie){this.currentSection!=null&&this.currentSection.hide();b.show();b.fadeIn();$("#earn").find("#contentHolder").height(b.height());$("#earn .partnersFix").height(b.height()+655);$("#earn .subContent").height(b.height()+245);$("#earn #partners").height(b.height()+345);$("#earn").find("#contentMask").height(b.height()+740)}else{$("#tabContent").animate({left:a},330,"easeInOutCirc");$("#earn").find("#content").height(d+745);$("#earn #partners #content").height(d+545);$("#earn").find("#contentMask").height(d+740)}this.currentMenuItem=c;this.currentSection=b;Tracker.track("_TrackPageView","Landing Page","/earn/"+this.currentSection.attr("id"))}}};AList={init:function(){AList=$.extend(AList,AbstractKnowledge);AList.name="A-List";this.initialize()}};AbstractKnowledge={initialize:function(){$("#back_kc").click(function(){window.location.hash="/knowledge/knowledge"});$(".questionHeader").each(function(){$(this).height(30);var a=$(this).find("#questionTitle")[0];a=$.browser.mozilla?a.textContent:a.innerText;a.length<70&&$(this).height(10);$(this).click(function(c){c.stopPropagation();$(this);$(this).parent().find(".questionBody").css("display")!="block"&&$(this).parent().height("100%");c=$(this).parent().find("#plus").find("img");c.attr("src").indexOf("plus")>=0?c.attr("src","images/knowledge/knowledge/minus.png"):c.attr("src","images/knowledge/knowledge/plus.png");$(this).position();$(this).parent().position();$("#knowledge").find("#contentMask").find("#content").offset();$(this).position();$(this).parent().position();$(this).parent().find(".questionBody").toggle(40,function(){if($(this).css("display")=="block"){var b=$(this).parent().position().top+$(this).parent().find(".questionBody").height()+$(this).parent().find("#questionTitle").height()+$("#knowledge").find("#bottomContent").scrollTop();$(this).parent().find(".questionBody").find("#questionText").height()>$(this).parent().find(".questionBody").find("#questionMedia").height()?$(this).parent().find(".questionBody").height($(this).parent().find(".questionBody").find("#questionText").height()):$(this).parent().find(".questionBody").height($(this).parent().find(".questionBody").find("#questionMedia").height());b>$("#knowledge").find("#bottomContent").height()-194&&$("#knowledge").find("#bottomContent").animate({scrollTop:b},1E3)}})})})}};CompanionPass={init:function(){CompanionPass=$.extend(CompanionPass,AbstractKnowledge);CompanionPass.name="Companion Pass";this.initialize()}};


KnowledgeManager = {
  hasInstance : false,
  searchResultData : [],
  data : [],
  views : 0,
  questionDOM : null,
  count : 0,
  currentCat : "", 
  initialize : function (){
    var scope = this;
    
    this.questionDOM = $(document.createElement('div'));
    this.questionDOM.addClass("question");
    this.questionDOM.append('<div class="questionHeader"><div id="plus"><img src="images/knowledge/knowledge/minus.png"/></div><div id="questionTitle"></div><div id="questionIcon"><img src="images/knowledge/knowledge/common/video_icon.png"/></div></div><br/><br/><div class="questionBody"><div id="questionMedia"></div></div>');

    fixButtons();
  },
   
  getContent : function (category)
  { 
    var obj = null;
    var data = KnowledgeManager.data;
    for(var n in data)
    {
        for(var i in data[n].sub_areas)
        {
          if(category == data[n].sub_areas[i].area_title)
          {
          	KnowledgeManager.currentCat = category;
            obj = data[n].sub_areas[i];
            break;
          }  
        }
    }
    
    return obj;
  }
  
}


function handleHTML(content)
{
  content = content.split("[ul]").join("<ul>");
  content = content.split("[/ul]").join("</ul>");
  content = content.split("[li]").join("<li>");
  content = content.split("[/li]").join("</li>");

  content = content.split("\n").join("</br>");
  content = content.split("[bold]").join("<b>");
  content = content.split("[/bold]").join("</b>");
  content = content.split("[italic]").join("<em>");
  content = content.split("[/italic]").join("</em>");
  content = content.split("®").join("<sup>&reg;</sup>");
  content = content.split("[lighter]").join("<span id='question_lighter'>");
  content = content.split("[/lighter]").join("</span>");
  
  return content;
}





Search={data:null,initialize:function(){this.data=KnowledgeManager.searchResultData;var a,c,b=$("#knowledge").find("#questionsContent");$("#searchButton").click(function(){KnowledgeManager.doSearch($("#searchInput").val())});$("#searchInput").keydown(function(f){if(f.keyCode=="13"){KnowledgeManager.doSearch($("#searchInput").val());f.preventDefault()}});if(this.data.length==0)$("#knowledge").find("#questionsContent").append("<span class='kc_videoLabel'>No results found</span>");else{b.animate({opacity:"0.01"},0);for(var d=0;d<this.data.length;d++){a=this.data[d];c=KnowledgeManager.questionDOM.clone();c.find("#questionTitle").html(handleHTML(a.question_title));c.find(".questionBody").append(handleHTML(a.question_body));c.find(".questionHeader").click(function(){$(this).parent().find(".questionBody").css("display")!="block"&&$(this).parent().height("100%");$(this).parent().find(".questionBody").toggle(150,function(){if($(this).css("display")!="block")if($(this).parent().find("#questionTitle").height()>20){$(this).parent().find(".questionHeader").height(25);$(this).parent().height(32)}else if($(this).parent().find("#questionTitle").height()<=20){$(this).parent().height(20);$(this).parent().find(".questionHeader").height(9)}})});if(a.media)if(a.media[0].type=="video"){var e=c.find("#questionMedia");e.html("<a href='#'><img src='"+a.media[0].thumb+"' /> </a>");e.attr("video",a.media[0].url);e.attr("videoTitle",a.media[0].title);e.click(function(f){VideoPlayer.openvideo($(this).attr("video"),$(this).attr("videoTitle"));f.preventDefault();f.stopPropagation()});c.find("#questionMedia").show();c.find("#questionIcon").show()}else{if(a.media[0].type=="image"){c.find("#questionMedia").html("<img src='"+a.media[0].url+"' />");c.find("#questionMedia").show()}else c.find("#questionMedia").hide();c.find("#questionIcon").hide()}else{c.find("#questionMedia").hide();c.find("#questionIcon").hide()}c.css("display","");b.append(c)}setTimeout(function(){$(".questionHeader").trigger("click");$("#questionsContent").delay(100).animate({opacity:"1"},200)},50)}}};


AListPrefer={init:function(){AListPrefer=$.extend(AListPrefer,AbstractKnowledge);AListPrefer.name="A-List Preferred";this.initialize()}};var knowledge={currentSub:"Top Questions",hasInstance:false,initialize:function(){$(".kc_card").each(function(){$(this).click(function(){SubNav.count++;window.location.hash="/knowledge/"+$(this).attr("data-page");Tracker.track("_TrackPageView","Landing Page","/knowledge/"+$(this).attr("data-page"))})})}};



Redeem={multiplier:0,points:0,airFare:0,



initialize:function()
{

var a=this,c=$("#flights").find("#step3").find("#option-item").radioButton();c.bind("changed",function(b){a.multiplier=$(b.target).attr("data-value");a.updateResult()});
$("#flights").find("#learnMore").click(function(b){b.stopPropagation();b.preventDefault();window.location.hash="/redeeming/redeem"});$("#flights").find("#enterStep2").click(function(){a.updateResult();Tracker.track("_TrackEvent","On Click","_RedeemSimulator_Step2Enter_Button")});
$("#flights").find("#step2").find("input").focusin(function(){$(this).val("")});$("#flights").find("#step2").find("input").focusout(function(){$(this).val().length==0&&$(this).val("$200")});$("#flights").find("#step2").find("input").keydown(function(b){if(!(b.keyCode==46||b.keyCode==8||b.keyCode==37||b.keyCode==39||b.keyCode>=96&&b.keyCode<=105))if(b.keyCode<48||b.keyCode>57)b.preventDefault()}).keyup(function(){var b=$(this).val();if(b.length>=1&&b!="$"){b=b.split("$").join("");b=removeDot($().numberFormat(b));$(this).val("$"+b)}});
c.first().trigger("click");

if(isIOS)
{
	if($('#redeeming #contentHolder').height()!=1218)
	{
		setTimeout(function(){$('#redeeming #contentHolder').css({height:1218});}, 500);
	}
	$('.customInput').css({top:0, left:30, background: 'none', height:40, width:100});
}


setTimeout(function(){$('#redeeming #submenu').find('a[id^="sub"]').each(function(){if(this.id!="sub-flights"){$(this).trigger("mouseleave");}else{$(this).trigger("mouseenter");}})}, 1000);

fixButtons()

},

updateResult:function(){var a=$("#flights").find("#step2").find("input").val();if(a.indexOf("$")>=0)a=a.split("$").join("");if(a.indexOf(",")>=0)a=Number(a.split(",").join(""));var c=this.multiplier*a;$("#flights").find("#step4").find("#operand").last().find("#giganticLabel").html(removeDot($().numberFormat(this.multiplier)));$("#flights").find("#step4").find("#operand").first().find("#giganticLabel").html("$"+removeDot($().numberFormat(a)));$("#flights").find("#result").find("span").html(removeDot($().numberFormat(c))+" Pts.");$("#flights").find("#result").css("font-size","32px");$("#flights").find("#result").find("span").height();$("#flights").find("#result").css("font-size","32px")}};

Tiers = {
    initialize: function () {
    	if(!$.browser.msie)
    	{
	        $("#popupRight").fadeOut('slow', function () {
    	        $("#popupRight").css({
        	        visibility: "hidden"
            	});
	        });
    	    $("#popupLeft").fadeOut('slow', function () {
        	    $("#popupLeft").css({
	           	    visibility: "hidden"
    	        });
        	});

	        $("#linkLeft").click(function (e) {
    	        $("#popupRight").fadeOut('slow', function () {
        	        $("#popupRight").css({
            	        visibility: "hidden"
	                });
    	        });

        	    $("#popupLeft").css({
            	    visibility: "visible"
	            });
    	        $("#popupLeft").fadeIn('slow');
        	});
	        $("#linkRight").click(function (e) {
    	        $("#popupLeft").fadeOut('slow', function () {
        	        $("#popupLeft").css({
            	        visibility: "hidden"
                	});
	            });
    	        $("#popupRight").css({
        	        visibility: "visible"
            	});
	            $("#popupRight").fadeIn('slow');
    	    });

        	$("#close_left").click(function (e) {
            	$("#popupLeft").fadeOut('slow', function () {
                	$("#popupLeft").css({
                    	visibility: "hidden"
	                });
    	        });
        	});
	        $("#close_right").click(function (e) {
    	        $("#popupRight").fadeOut('slow', function () {
        	        $("#popupRight").css({
            	        visibility: "hidden"
                	});
	            });
    	    });
		} else {
			$("#popupRight").css({visibility: "hidden"});
			$("#popupLeft").css({visibility: "hidden"});
			$("#linkLeft").click(function (e) {
				$("#popupRight").css({visibility: "hidden"});
				$("#popupLeft").css({visibility: "visible"});
			});
			$("#linkRight").click(function (e) {
				$("#popupRight").css({visibility: "visible"});
				$("#popupLeft").css({visibility: "hidden"});
			});
			$("#close_left").click(function (e) {
				$("#popupRight").css({visibility: "hidden"});
				$("#popupLeft").css({visibility: "hidden"});
			});
			$("#close_right").click(function (e) {
				$("#popupRight").css({visibility: "hidden"});
				$("#popupLeft").css({visibility: "hidden"});
			});
		}

        if ($.browser.chrome || $.browser.msie) {
            $("#titleRight4").css({
                letterSpacing: -1
            });
        } else {
        	$("#titleRight4").css({
                letterSpacing: -.5
            });
        }
    }
}

AbstractKnowledge = {

  initialize : function(){
    var scope = this;

     
    $("#back_kc").click(function(){
      window.location.hash = "/knowledge/knowledge"
    })
    	
    var qc = 0;

    $(".questionHeader").each(function(){

      $(this).height(30);
      var title = $(this).find("#questionTitle")[0];
      if(!$.browser.mozilla)
        title = title.innerText;
      else 
       title = title.textContent;

      if(title.length < 90)
      {
        $(this).height(10); 
      }

		if(KnowledgeManager.currentCat == "General")
		{			
			if(qc == 4)
			{
				$(this).height(24); 		
			}
		}
		
		if(KnowledgeManager.currentCat == "accountAccess")
		{			
			if(qc == 2)
			{
				$(this).height(24); 		
			}
		}		
		
		qc++;

      $(this).click(function(e){
        
        e.stopPropagation();
        
        var self = $(this);
        if($(this).parent().find(".questionBody").css("display")!= "block")
          $(this).parent().height("100%");

        var image = $(this).parent().find("#plus").find("img");
        if(image.attr("src").indexOf("plus") >= 0)
        {
          image.attr("src", "images/knowledge/knowledge/minus.png")
        }
        else
        {
          image.attr("src", "images/knowledge/knowledge/plus.png")
        }


        var _target = $(this).position().top + $(this).parent().position().top +  Math.floor($("#knowledge").find("#contentMask").find("#content").offset().top - 160);
        var _localtarget = $(this).position().top + $(this).parent().position().top; 
      
        $(this).parent().find(".questionBody").toggle(40, function(){

          if($(this).css("display") == "block"){
              
              var questionOffset = $(this).parent().position().top + $(this).parent().find(".questionBody").height() + $(this).parent().find("#questionTitle").height() + $("#knowledge").find('#bottomContent').scrollTop();
              
              if($(this).parent().find(".questionBody").find("#questionText").height() > $(this).parent().find(".questionBody").find("#questionMedia").height())
                $(this).parent().find(".questionBody").height($(this).parent().find(".questionBody").find("#questionText").height());
              else
                $(this).parent().find(".questionBody").height($(this).parent().find(".questionBody").find("#questionMedia").height());
                        
              if(questionOffset > $("#knowledge").find('#bottomContent').height() - 194 )
               $("#knowledge").find('#bottomContent').animate({scrollTop:questionOffset}, 1000);
          }

        });
    })

  });


  }


}

PurchasePoints = {
	initialize : function()
	{
		var height = 1240;
		var contentHolder = $("#earn").find("#contentMask");
	
		//if(height < _window.height())
		//	height = _window.height()+10; 
			
		contentHolder.height(height);
		
//		log(contentHolder, height);
	}
}



$(function(){ENTER_PAGE="enter_page";TRACK_PAGE="track_page";LEAVE_PAGE="page_changed";SCROLLER="scrolling";SHOW_SUB="show_submenu";DATA_LOADED="data_loaded";try{_window=$(window);Tracker.initialize();Parallax.initialize();Nav.initialize();SubNav.initialize();fixButtons();removeFontsTag()}catch(a){}});function log(){window.console&&console.log(arguments)}function removeDot(a){if(a.indexOf(".")>=0)a=a.split(".").join("");return a}function loadContent(a,c,b){c.detach();a.append(c);c.load(b,function(){var d=c.height();if(d<$(window).height())d=$(window).height()-85;a.animate({height:d+40},300);c.fadeIn("slow")})}function getBgHeight(a){var c=0;a='<img id="tempImg" src="'+a.css("background-image").replace("url","").replace("(","").replace(")","").replace('"',"").replace('"',"")+'"/>';$("body").append(a);$("#tempImg").hide();c=$("#tempImg").height();$("#tempImg").remove();return c}function getDomain(){var a=window.location.href;a=a.split("#");a=a[0].split("6a992d5529f459a44fee58c733255e86.html");a=a[0].split("index.html");return a[0]}function fixButtons(){$(".common_button").each(function(){var a=$(this),c=a.find("#button_left_part"),b=a.find("#button_right_part"),d=a.find("#button_body");a.unbind("mouseenter");a.unbind("mouseleave");a.unbind("mouseup");a.unbind("mousedown");a.bind("mouseenter",function(){$(this);c.removeClass("left_off");c.addClass("left_on");b.removeClass("right_off");b.addClass("right_on");d.removeClass("body_off");d.addClass("body_on")});a.bind("mouseleave",function(){$(this);c.removeClass("left_on");c.addClass("left_off");b.removeClass("right_on");b.addClass("right_off");d.removeClass("body_on");d.addClass("body_off")});a.bind("mouseup",function(){$(this).css({marginTop:"-=1px"})});a.bind("mousedown",function(){$(this).css({marginTop:"+=1px"})})})}function removeFontsTag(){$("#mti_wfs_colophon")[0]!=undefined?$("#mti_wfs_colophon").css({display:"none"}):setTimeout(removeFontsTag,100)}$("#knowledge-terms").click(function(){Tracker.track("_TrackEvent","On Click","_KnowledgeCenter_Terms_Page")});


$("#welcome_1").click(function(){window.location.hash="#/earn";Tracker.track("_TrackEvent","On Click","_WelcomeEarn_Button")});$("#welcome_2").click(function(){window.location.hash="#/redeeming";Tracker.track("_TrackEvent","On Click","_WelcomeRedeem_Button")});$("#welcome_3").click(function(){window.location.hash="#/tiers";Tracker.track("_TrackEvent","On Click","_WelcomeTier_Button")});$("#sign_up").click(function(){window.open("http://www.southwest.com/rapidrewards/emails", "_blank");Tracker.track("_TrackEvent","On Click","_WelcomeSignUp_Button")});
