// Define cookie get/set functions
var createCookie = function(name,value,days) {
    if ( days ) {
        var date = new Date();

        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    } else {
        var expires = "";
    }
    document.cookie = name+"="+value+expires+"; path=/";
}
var readCookie = function(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for ( var i = 0; i < ca.length; i++ ) {
        var c = ca[i];
        while ( c.charAt(0) == ' ' ) c = c.substring(1, c.length);
        if ( c.indexOf(nameEQ) == 0 ) return c.substring(nameEQ.length,c.length);
    }
    return null;
}
var eraseCookie = function(name) {
    createCookie(name,"",-1);
}

/* -------------------------------------- SSO -------------------------------------- */
// utility function to retrieve an expiration date in proper 
// format; pass three integer parameters for the number of days, hours, 
// and minutes from now you want the cookie to expire (or negative 
// values for a past date); all three parameters are required, 
// so use zeros where appropriate 
function getExpDate(days, hours, minutes) { 
    var expDate = new Date(); 
    if (typeof days == "number" && typeof hours == "number" && 
        typeof minutes == "number") { 
        expDate.setDate(expDate.getDate() + parseInt(days)); 
        expDate.setHours(expDate.getHours() + parseInt(hours)); 
        expDate.setMinutes(expDate.getMinutes() + parseInt(minutes)); 
        return expDate.toUTCString(); 
    } 
} 
// utility function called by getCookie() 
function getCookieVal(offset) { 
    var endstr = document.cookie.indexOf (";", offset); 
    if (endstr == -1) { 
        endstr = document.cookie.length; 
    } 
    return decodeURI(document.cookie.substring(offset, endstr)); 
} 
// primary function to retrieve cookie by name 
function getCookie(name) { 
    var arg = name + "="; 
    var alen = arg.length; 
    var clen = document.cookie.length; 
    var i = 0; 
    while (i < clen) { 
        var j = i + alen; 
        if (document.cookie.substring(i, j) == arg) { 
            return getCookieVal(j); 
        } 
        i = document.cookie.indexOf(" ", i) + 1; 
        if (i == 0) break; 
    } 
    return ""; 
} 
// store cookie value with optional details as needed 
function setCookie(name, value, expires, path, domain, secure) { 
    document.cookie = name + "=" + encodeURI(value) + 
        ((expires) ? "; expires=" + expires : "") + 
        ((path) ? "; path=" + path : "") + 
        ((domain) ? "; domain=" + domain : "") + 
        ((secure) ? "; secure" : ""); 
} 
// remove the cookie by setting ancient expiration date 
function deleteCookie(name,path,domain) { 
    if (getCookie(name)) { 
        document.cookie = name + "=" + 
            ((path) ? "; path=" + path : "") + 
            ((domain) ? "; domain=" + domain : "") + 
            "; expires=Thu, 01-Jan-70 00:00:01 GMT"; 
    } 
}

sso_email = null;
sso_user = null;

// shows/hides the login/logout, register/myaccount links and comment form
jQuery(function($) {
  
  $('#comment-form').attr('class', 'hidden');
  
  if(document.location.hostname == 'www.scenedaily.com') {  
    sso_login = function(subscriber) {
      sso_email = subscriber.email; 
      sso_user = subscriber;
      if(sso_email != null) {
        $('#user-nav .logout').removeClass('hidden').addClass('visible');
        $('#user-nav .my-account').removeClass('hidden').addClass('visible');
        $('#user-nav .login').addClass('hidden');
        $('#user-nav .register').addClass('hidden');
        //$('#community-nav .last-child').before('<li><a href="http://community.scenedaily.com/profiles/'+sso_user.login+'">My Profile</a></li>');
        //$('#comments .abuse').removeClass('hidden').addClass('visible');
        $('#comment-login').addClass('hidden');
        $('#comment-form').removeClass('hidden').addClass('visible');
        $('#comment-form').append('<input type="hidden" name="email" value="'+sso_email+'"/>');
        $('#comment-form').append('<input type="hidden" name="name" value="'+sso_user.login+'"/>');
        $('b#name').html(sso_user.login);
        $('#logged-in-links').removeClass('hidden').addClass('visible');
        $('#logged-out-links').addClass('hidden');
      } 
    }

    $.ajax({
      'dataType' : 'json', 
      'url' : 'http://www.scenedaily.com/templates/sso_login',
      'data' : {'token':getCookie('scene'),'rand':Math.random()*100000},
      'success' : sso_login
    })
  }
});

/* -------------------------------------- NAVIGATION -------------------------------------- */
jQuery(function($) {
  jQuery.event.add(window, "load", toggleNavItems);
  jQuery.event.add(window, "resize", toggleNavItems);
  
  // these are <li>'s that are in the main nav
  
  var tracks = $('#site-nav li.tracks');
  var illustrated = $('#site-nav li.illustrated');
  var store = $('#site-nav li.store');
  var classifieds = $('#site-nav li.classifieds');
  var tweets = $('#site-nav li.tweets');
  var archive = $('#site-nav li.archive');
  var cartoon = $('#site-nav li.cartoon');
  var fantasy = $('#site-nav li.fantasy');

  // static HTML for the same var's above...was trying to avoid cloning and appending
  // not sure if even matters performance-wise.
  var moreOpen = '<li class="more"><a href="#">More<span></span></a> <ul class="subnav">';
  var moreClose = '<li></li></ul></li>';
  var moreTracks = '<li class="tracks"><a href="http://www.scenedaily.com/races/tracks/">Tracks</a></li>';
  var moreIllustrated = '<li class="illustrated"><a href="http://nascarillustrated.scenedaily.com">NASCAR Illustrated</a></li>';
  var moreStore = '<li class="store"><a href="https://store.scenedaily.com/">Store</a></li>';
  var moreClassifieds = '<li class="classifieds"><a href="https://classifieds.scenedaily.com/">Classifieds</a></li>';
  var moreTweets = '<li class="racin-tweets"><a href="http://twitter.scenedaily.com/">Racin\' Tweets</a></li>';
  var moreArchive = '<li class="archive"><a href="http://www.scenedaily.com/news/archive">News Archive</a></li>';
  var moreCartoon = '<li class="cartoon"><a href="http://www.scenedaily.com/stockcartoons/">StockCartoon</a></li>';
  var moreFantasy = '<li class="fantasy"><a href="http://www.scenedaily.com/fantasy">Fantasy</a></li>';
  
  // Takes the var's directly above and joins them together. more is appended to #site nav
  // which is the main nav on the site. More needs to be more dynamic and only render the <li> in the more
  // <li>'s <ul class="subnav"> it's it's main nav item has been hidden from #site-nav 
  var more = moreOpen + moreIllustrated + moreStore + moreClassifieds + moreArchive + moreTweets + moreCartoon + moreFantasy + moreClose;
  $(more).appendTo('#site-nav');
  
  // The <li>'s in the main nav are hidden or shown depending on how wide the browser window is. 
  // If the browser window is small enough that all the nav <li>'s don't fit then they are
  // hidden and a more <li> is rendered with the nav items rendered in it's dropdown.
  function toggleNavItems() 
  {    
      var browserWindow = $(window).width();
      if(browserWindow > 800 && browserWindow <= 1105){
          //$(fantasy, cartoon, archive, tweets, classifieds, store, illustrated).hide();
          //$('.more, .more .illustrated, .more .store, .more .classifieds, .more .archive, .more .racin-tweets, .more .cartoon, .more .fantasy').show();
          $(fantasy).hide();
          $(cartoon).hide();
          $(archive).hide();
          $(tweets).hide();
          $(classifieds).hide();
          $(store).hide();
          $(illustrated).hide();
          $('.more').show();
          $('.more .illustrated').show();
          $('.more .store').show();
          $('.more .classifieds').show();
          $('.more .archive').show();
          $('.more .racin-tweets').show();
          $('.more .cartoon').show();
          $('.more .fantasy').show();
      } else if (browserWindow > 1105 && browserWindow <= 1160){
          $(fantasy).hide();
          $(cartoon).hide();
          $(archive).hide();
          $(tweets).hide();
          $(classifieds).hide();
          $(store).hide();
          $(illustrated).show();
          $('.more').show();
          $('.more .illustrated').hide();
          $('.more .store').show();
          $('.more .classifieds').show();
          $('.more .archive').show();
          $('.more .racin-tweets').show();
          $('.more .cartoon').show();
          $('.more .fantasy').show();
      } else if ( browserWindow > 1160 && browserWindow <= 1245){
          $(fantasy).hide();
          $(cartoon).hide();
          $(archive).hide();
          $(tweets).hide();
          $(classifieds).hide();
          $(store).show();
          $(illustrated).show();
          $('.more').show();
          $('.more .illustrated').hide();
          $('.more .store').hide();
          $('.more .classifieds').show();
          $('.more .archive').show();
          $('.more .racin-tweets').show();
          $('.more .cartoon').show();
          $('.more .fantasy').show();
      } else if ( browserWindow > 1245 && browserWindow <= 1345){
          $(fantasy).hide();
          $(cartoon).hide();
          $(archive).hide();
          $(tweets).hide();
          $(classifieds).show();
          $(store).show();
          $(illustrated).show();
          $('.more').show();
          $('.more .illustrated').hide();
          $('.more .store').hide();
          $('.more .classifieds').hide();
          $('.more .archive').show();
          $('.more .racin-tweets').show();
          $('.more .cartoon').show();
          $('.more .fantasy').show();
      } else if ( browserWindow > 1345 && browserWindow <= 1440){
          $(fantasy).hide();
          $(cartoon).hide();
          $(archive).hide();
          $(tweets).show();
          $(classifieds).show();
          $(store).show();
          $(illustrated).show();
          $('.more').show();
          $('.more .illustrated').hide();
          $('.more .store').hide();
          $('.more .classifieds').hide();
          $('.more .archive').show();
          $('.more .racin-tweets').hide();
          $('.more .cartoon').show();
          $('.more .fantasy').show();
      } else if ( browserWindow > 1440 && browserWindow <= 1550 ){
          $(fantasy).hide();
          $(cartoon).hide();
          $(archive).show();
          $(tweets).show();
          $(classifieds).show();
          $(store).show();
          $(illustrated).show();
          $('.more').show();
          $('.more .illustrated').hide();
          $('.more .store').hide();
          $('.more .classifieds').hide();
          $('.more .archive').hide();
          $('.more .racin-tweets').hide();
          $('.more .cartoon').show();
          $('.more .fantasy').show();
      } else if ( browserWindow > 1550){
          $(fantasy).show();
          $(cartoon).show();
          $(archive).show();
          $(tweets).show();
          $(classifieds).show();
          $(store).show();
          $(illustrated).show();
          $('.more .illustrated').hide();
          $('.more .store').hide();
          $('.more .classifieds').hide();
          $('.more .archive').hide();
          $('.more .racin-tweets').hide();
          $('.more .cartoon').hide();
          $('.more .fantasy').hide();
          $('.more').hide();
      } 
  }
  
  $.fn.hoverIntent = function(f,g) {
  	// default configuration options
  	var cfg = {
  		sensitivity: 7,
  		interval: 100,
  		timeout: 0
  	};
  	// override configuration options with user supplied object
  	cfg = $.extend(cfg, g ? { over: f, out: g } : f );

  	// instantiate variables
  	// cX, cY = current X and Y position of mouse, updated by mousemove event
  	// pX, pY = previous X and Y position of mouse, set by mouseover and polling interval
  	var cX, cY, pX, pY;

  	// A private function for getting mouse position
  	var track = function(ev) {
  		cX = ev.pageX;
  		cY = ev.pageY;
  	};

  	// A private function for comparing current and previous mouse position
  	var compare = function(ev,ob) {
  		ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
  		// compare mouse positions to see if they've crossed the threshold
  		if ( ( Math.abs(pX-cX) + Math.abs(pY-cY) ) < cfg.sensitivity ) {
  			$(ob).unbind("mousemove",track);
  			// set hoverIntent state to true (so mouseOut can be called)
  			ob.hoverIntent_s = 1;
  			return cfg.over.apply(ob,[ev]);
  		} else {
  			// set previous coordinates for next time
  			pX = cX; pY = cY;
  			// use self-calling timeout, guarantees intervals are spaced out properly (avoids JavaScript timer bugs)
  			ob.hoverIntent_t = setTimeout( function(){compare(ev, ob);} , cfg.interval );
  		}
  	};

  	// A private function for delaying the mouseOut function
  	var delay = function(ev,ob) {
  		ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
  		ob.hoverIntent_s = 0;
  		return cfg.out.apply(ob,[ev]);
  	};

  	// A private function for handling mouse 'hovering'
  	var handleHover = function(e) {
  		// next three lines copied from jQuery.hover, ignore children onMouseOver/onMouseOut
  		var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget;
  		while ( p && p != this ) { try { p = p.parentNode; } catch(e) { p = this; } }
  		if ( p == this ) { return false; }

  		// copy objects to be passed into t (required for event object to be passed in IE)
  		var ev = jQuery.extend({},e);
  		var ob = this;

  		// cancel hoverIntent timer if it exists
  		if (ob.hoverIntent_t) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); }

  		// else e.type == "onmouseover"
  		if (e.type == "mouseover") {
  			// set "previous" X and Y position based on initial entry point
  			pX = ev.pageX; pY = ev.pageY;
  			// update "current" X and Y position based on mousemove
  			$(ob).bind("mousemove",track);
  			// start polling interval (self-calling timeout) to compare mouse coordinates over time
  			if (ob.hoverIntent_s != 1) { ob.hoverIntent_t = setTimeout( function(){compare(ev,ob);} , cfg.interval );}

  		// else e.type == "onmouseout"
  		} else {
  			// unbind expensive mousemove event
  			$(ob).unbind("mousemove",track);
  			// if hoverIntent state is true, then call the mouseOut function after the specified delay
  			if (ob.hoverIntent_s == 1) { ob.hoverIntent_t = setTimeout( function(){delay(ev,ob);} , cfg.timeout );}
  		}
  	};

  	// bind the function to the two event listeners
  	return this.mouseover(handleHover).mouseout(handleHover);
  };

  // config for the nav
  var config = {    
     sensitivity: 3, // number = sensitivity threshold (must be 1 or higher)    
     interval: 10,  // number = milliseconds for onMouseOver polling interval    
     over: doOpen,   // function = onMouseOver callback (REQUIRED)    
     timeout: 100,   // number = milliseconds delay before onMouseOut    
     out: doClose    // function = onMouseOut callback (REQUIRED)    
  };

  function doOpen() {
    $(this).addClass("hover");
    $('.subnav',this).fadeIn(100);
  };

  function doClose() {
    $(this).removeClass("hover");
    $('.subnav',this).fadeOut(100);
  };

  $("#site-nav li").hoverIntent(config);
  $("#user-nav li").hoverIntent(config);
  $('#user-nav li.login a').click(function(){ return false; }); 
  $('#navigation li:last-child').addClass('last-child');
  
  // fading menu
  //$(window).scroll(function(){
  //  var scrollTop = $(window).scrollTop();
  //  if(scrollTop != 0)
  //    $('#navigation').stop().animate({'opacity':'0.1'},400);
  //  else	
  //    $('#navigation').stop().animate({'opacity':'1'},400);
  //});
  //$('#navigation').hover(
  //  function (e) {
  //    var scrollTop = $(window).scrollTop();
  //    if(scrollTop != 0){
  //      $('#navigation').stop().animate({'opacity':'1'},400);
  //    }
  //  },
  //  function (e) {
  //    var scrollTop = $(window).scrollTop();
  //    if(scrollTop != 0){
  //      $('#navigation').stop().animate({'opacity':'0.1'},400);
  //    }
  //  }
  //);

  // nice labels
  $("#nav-login label").inFieldLabels();
  $("#nav-search label").inFieldLabels();
  
  // resizes the search box
  $('#nav-search input').focusin(function(){
    $(this).animate({width: "185px"}, 500 );
  });
  $('#nav-search input').focusout(function(){
    $(this).animate({width: "55px"}, 500 );
  });
  
  // validates the login
  if ( $('#nav-login').length > 0 ) {
    $('#nav-login').validate({
    	rules: {
    		login: {
    			required: true
    		},
    		password: {
    			required: true,
    			minlength: 6
    		}
    	},
    	messages: {
  	    login: {
	        required: "You can't leave your username blank"
  	    },
        password: {
          required:  "You can't leave your password blank",
          minlength: "Your password must be at least 6 characters"
        }
    	}
    });
  }
  
  // tmp event tracking on the main nav
  $("#site-nav a").click(function(){
		pageTracker._trackEvent('Main Nav', $(this).attr('title'), $(this).attr('href'));
	});
});

/* -------------------------------------- HOMEPAGE SLIDER -------------------------------------- */
jQuery(function($){
    var theInt = null;
    var $crosslink, $navthumb;
    var curclicked = 0;

    theInterval = function(cur){
    	clearInterval(theInt);
	
    	if( typeof cur != 'undefined' )
    		curclicked = cur;
	
    	$crosslink.removeClass("active");
    	$navthumb.eq(curclicked).parent().addClass("active");
    		$(".stripNav ul li a").eq(curclicked).trigger('click');
	
    	theInt = setInterval(function(){
    		$crosslink.removeClass("active");
    		$navthumb.eq(curclicked).parent().addClass("active");
    		$(".stripNav ul li a").eq(curclicked).trigger('click');
    		curclicked++;
    		if( 5 == curclicked )
    			curclicked = 0;
		
    	}, 4000);
    };

    $(function(){
        if ( $("#primary-news-slider").length > 0 ) {
    	    $('#primary-news-slider').codaSlider();
    	}
    	//$("#promotions-slider").codaSlider();
	
    	$navthumb = $(".nav-thumb");
    	$crosslink = $(".cross-link");
	
    	$navthumb
    	.click(function() {
    		var $this = $(this);
    		theInterval($this.parent().attr('href').slice(1) - 1);
    		return false;
    	});
	
    	theInterval();
    });
})

/* -------------------------------------- COOKIES -------------------------------------- */
jQuery(function($){
  // cookie for the daily email subscription currently on the article/blog detail pages
  if ($('#daily-email-sub').length > 0 ) {    
    if($.cookie('hide-email-subs') != 'true') {
      $.cookie("hide-email-subs", "false", { path: '/', expires: 90 })
      $('#daily-email-sub').removeClass('hidden').addClass('visible');
    }

    $('#daily-email-sub #close-subs').click(function(){
      $(this).parent().animate({opacity: 'hide', height: 0}, 400);
      $.cookie("hide-email-subs", "true", {  path: '/', expires: 90 })
      return false;
    });
    
    $("#daily-email-sub").validate({
      rules: {
    		"Email Address": {
    			required: true,
    			email: true
    		}
    	},
    	messages: {
  	    "Email Address": {
	        required: "Don't forget your e-mail address",
	        email:    "This doesn't look like an e-mail address"
  	    }
    	},
    	errorLabelContainer: $("#daily-email-sub div.errors")
    });
  }
});
  
/* -------------------------------------- COMMENTS -------------------------------------- */
jQuery(function($){
  // Validates login
  if ( $('#comment-login').length > 0 ) {
      $("#comment-login").validate({
      	rules: {
      		email: {
      			required: true,
      			email: true
      		},
      		password: {
      			required: true,
      			minlength: 6
      		}
      	},
      	messages: {
      	    email: {
      	        required: "You can't leave your email blank",
      	        email:    "Must use a valid email address"
      	    },
              password: {
                  required:  "You can't leave your password blank",
                  minlength: "Your password must be at least 6 characters"
              }
      	}
      });
  }
  // Posting a comment
  if ( $('#comment-form').length > 0 ) {
      $("#comment-form").validate({
      	rules: {
      		field: {
      			required: true
      		}
      	},
      	messages: {
      	    field: "You didn't add in a comment!"
      	},
      	submitHandler: function(form){
      	  $.post('/c', $('#comment-form').serialize())
      	  /*
      	  <li class="comment even clearfix">
             <div class="number"><span>2</span></div>
             <h6><b>DickHURTZ</b> said:</h6>
             <span class="date">Jul 23, 2009 at 7:17 AM</span>
             <p>WHOOP T DOO FOR MIS. WOULDN'T BRING IN MORE FANS BECAUSE OF CARFAX.</p>
          </li>
          */
          var append_comment = function() {
            var li = $('<li>').addClass('comment even clearfix');
            var comment_count = $('ol li').length + 1
            li.append( $('<div>').addClass('number').html('<span>'+ comment_count +'</span>') );
            li.append( $('<h6>').html('<b>'+sso_user.login+'</b> said:') );
            var d = new Date();
            li.append( $('<span>').addClass('date').html(d.getMonth() + ' - ' + d.getDate() + ' - ' + d.getFullYear()) );
            li.append( $('<p>').html($('#commentFormComment').val()) )
        	  $('ol').append(li)
        	  li.hide();
        	  li.fadeIn();
        	  $('#commentFormComment').val('');
        	  $('#live-preview').html('');
      	  }
      	  append_comment();
      	  return false;
      	}
      });
  }
  if ( $('textarea#commentFormComment').length > 0 ) {
      $('textarea#commentFormComment').keyup(function() {
          var charLength = $(this).val().length;
      
          // Displays count
          $('span#char-count').html('(' + charLength + '\/2000 characters left)');
      
          // Alerts when 2000 characters is reached
          if($(this).val().length > 2000)
              $('span#char-count').html('You may only have up to 2000 characters.');
      });
  }
  
  var $comment = '';
  
  if ( $('#comment-form textarea').length > 0 ) {
      $('#comment-form textarea').keyup(function() {
          $comment = $(this).val();
          $comment = $comment.replace(/\n/g, "<br />")
          .replace(/\n\n+/g, '<br /><br />');
          $('#live-preview').html( $comment );
      });
  }
});

/* -------------------------------------- MISC -------------------------------------- */
jQuery(function($){
  // adds the browser name and js to the homepage
  if($.browser.mozilla) {
      $("html").addClass("js mozilla");
  } else if($.browser.safari) {
      $("html").addClass("js safari");
  } else if($.browser.msie) {
      $("html").addClass("js msie");
  } else {
      $("html").addClass("js");
  };

  // Makes the tabs work
  if ( $(".tabs > ul").length > 0 ) {
      $(".tabs > ul").tabs();
  }

  if ( $("#video-gallery > ul").length > 0 ) {
      $("#video-gallery > ul").tabs({ fx: { opacity: 'toggle' } });
  }
  
  if ( $("#media").length > 0 ) {
    $("#media .secondary-images li:nth-child(3n)").addClass('three');
  }

  // Created the facebox popup
  //if ( $('a[rel*=facebox]').length > 0 ) {
  //    $('a[rel*=facebox]').facebox();
  //}

  // Places text from a title attribute into an input
  jQuery.fn.hint = function() {
    return this.each(function(){
        var t = $(this);
        var title = t.attr('title');

        if (title) {
            t.focus(function(){
                if (t.val() == title) {
                  t.val('');
                  t.removeClass('blur');
                }
            })

            t.blur(function(){
                if (t.val() == '') {
                  t.val(title);
                  t.addClass('blur');
                }
            })

            t.parents('form:first').submit(function(){
                if (t.val() == title) {
                    t.val('');
                    t.removeClass('blur');
                }
            });

            t.blur();
        }
    })
  }  

  // drops a hint in input fields
  $('input:text').hint();

  // Reset Font Size
  var originalFontSize = $('.resize-area').css('font-size');
  $(".reset-text").click(function(){
    $('.resize-area').css('font-size', originalFontSize);
  });

  // Increase Font Size
  $(".increase-text").click(function(){
    var currentFontSize = $('.resize-area').css('font-size');
    var currentFontSizeNum = parseFloat(currentFontSize, 10);
    var newFontSize = currentFontSizeNum*1.1;
    $('.resize-area').css('font-size', newFontSize);
    return false;
  });

  // Decrease Font Size
  $(".decrease-text").click(function(){
    var currentFontSize = $('.resize-area').css('font-size');
    var currentFontSizeNum = parseFloat(currentFontSize, 10);
    var newFontSize = currentFontSizeNum*0.9;
    $('.resize-area').css('font-size', newFontSize);
    return false;
  });

  // Open new window for external links
  $("a[rel='external']").attr('target', '_blank');
      

  
  if ( $('#top-tools .share').length > 0 ) {
      $("#top-tools .share").hover(
          function () { 
              $("#top-tools .share").addClass("selected")
          }, 
          function () { 
              $("#top-tools .share").removeClass("selected")
          } 
      );
  }
  if ( $('#bottom-tools .share').length > 0 ) {
      $("#bottom-tools .share").hover(
          function () { 
              $("#bottom-tools .share").addClass("selected")
          }, 
          function () { 
              $("#bottom-tools .share").removeClass("selected")
          } 
      );
  }
  
  // Creates the print button to make it unobtrusive
  if ( $('ul.tools li.rss').length > 0 ) {
      $('ul.tools li.rss').after('<li class="print"><a href="#print">Print this Article</a></li>');
  }
  if ( $('ul.tools li.print a').length > 0 ) {
      $('ul.tools li.print a').click(function() {
          window.print();
          return false;
      });
  }
   
  // miss sprint cup tweets
  $("#sprint-cup-girls .cup-girls").tweet({
      username: "misssprintcup",
      join_text: null,
      avatar_size: 36,
      count: 1,
      loading_text: null,
      auto_join_text_default: "We said,",
      auto_join_text_ed: "We",                
      auto_join_text_ing: "We are",            
      auto_join_text_reply: "We replied to",  
      auto_join_text_url: "We were looking at"
  });
  $("#sprint-cup-girls .scenedaily").tweet({
      username: ["bobpockrass","krisjohnson_sd","kennybruce","jeffowens_sd"],
      join_text: null,
      avatar_size: 36,
      count: 2,
      loading_text: null
  });
  
  $('#cartoons .thumbnails').masonry({ singleMode: true });
  $('#album-detail .thumbnails').masonry({ singleMode: true });
  $('#automotiveissue #classic-cars ul').masonry({ singleMode: true, saveOptions: false });
  
  // fixes the layout of the promotions page for IE
  if ( $('#promotion-index').length > 0 ) {
      $('#content ul li:nth-child(4n)').addClass('four');
  }
  
});
/* -------------------------------------- PAGEVIEW AND EVENT TRACKING -------------------------------------- */
jQuery(function($){
  var pathName = window.location.pathname;

  //page tracking
  $("a[rel*='prev']").click(function(){
  	pageTracker._trackPageview(window.location.pathname + $(this).attr('href'));
  });
  
  // adds google event tracking
  // external, news (scenedaily), twitter, facebook, subscribe, prev/next/sliderNav (tracks the spread clicks within the issues)
  // _trackEvent(category, action, optional_label, optional_value)
  // pageTracker._trackEvent('Videos', 'Downloaded', 'Gone With the Wind');
  // pageTracker._trackEvent('Downloads', 'PDF', '/salesForms/orderForm1.pdf');
  // pageTracker._trackPageview('/email/'+ $(this).attr('href'));
  $("a[rel*='external']").click(function(){
		pageTracker._trackEvent('External', 'Misc', $(this).attr('href'));
	});
	$("a[rel*='external']").click(function(){
		pageTracker._trackEvent('External', 'Misc', $(this).attr('href'));
	});
	$("a[rel*='twitter']").click(function(){
		pageTracker._trackEvent('External', 'Twitter', $(this).attr('href'));
	});
	$("a[rel*='facebook']").click(function(){
		pageTracker._trackEvent('External', 'Facebook', $(this).attr('href'));
	});
	$("a[rel*='subscribe']").click(function(){
		pageTracker._trackEvent('External', 'Subscribe', $(this).attr('href'));
	});
	$("a[rel*='email']").click(function(){
		pageTracker._trackEvent('Email', 'Share', $(this).attr('href'));
	});
	$("a[rel*='increase-text']").click(function(){
		pageTracker._trackEvent('Tool', 'Increase Text');
	});
	$("a[rel*='decrease-text']").click(function(){
		pageTracker._trackEvent('Tool', 'Decrease Text');
	});
	$("a[rel*='share']").click(function(){
		pageTracker._trackEvent('External', 'Share', $(this).attr('title'));
	});
	
	// partnership or promotion tracking
	$("a[rel*='hemmings']").click(function(){
		pageTracker._trackEvent('External', 'Hemmings', $(this).attr('href'));
	});
	$("a[rel*='fox-sports']").click(function(){
		pageTracker._trackEvent('External', 'Fox Sports', $(this).attr('href'));
	});
	$("a[rel*='rowdy']").click(function(){
		pageTracker._trackEvent('External', 'Rowdy', $(this).attr('href'));
	});
	
	// testing features
	$("#homepage #sprint-cup a").click(function(){
		pageTracker._trackEvent('More News', 'Sprint Cup', $(this).attr('href'));
	});
	$("#homepage #nationwide a").click(function(){
		pageTracker._trackEvent('More News', 'Nationwide', $(this).attr('href'));
	});
	$("#homepage #camping-world a").click(function(){
		pageTracker._trackEvent('More News', 'Camping World', $(this).attr('href'));
	});
	$("#popular-news a").click(function(){
		pageTracker._trackEvent('News Sidebar', 'Popular News', $(this).attr('href'));
	});
	$("#recent-news a").click(function(){
		pageTracker._trackEvent('News Sidebar', 'Recent News', $(this).attr('href'));
	});
	$("#more-by-author a").click(function(){
		pageTracker._trackEvent('News Sidebar', 'More By Author', $(this).attr('href'));
	});
});
