/*
--------------------------------------------------

Copart Racing
Global JS [global.js]

Copyright (c) 2010 Acquity Group LLC

--------------------------------------------------
*/

// Universal Copart Namespace
var cr = new Object();

// Navigation Control Variables
var subNavObjectSelected;
var subNavObjectIndicator;
var subNavTimeout; 

/** Init Namespace
 *  Used to create init methods specific
 *  to each page. 
 */
cr.init = {
  
  /** function home
   *  initialize home page 
   */		
  home : function(){
	cr.nav.init();
	cr.flashInit.home();
	cr.flashInit.upcomingRaces();
	cr.flashInit.saleVehicles();
	cr.social.initTwitter();
	cr.search.init();
  },
  
  /** function drivers
   *  initialize drivers page 
   */		
  drivers : function(){
    cr.nav.init();
    cr.flashInit.saleVehicles();
    cr.search.init();
    
    $("#switchOne").click(function(){    	
    	$("#displayOne").css("display","none");
    	$("#displayTwo").css("display","block");
    	$("#driversBkgHandle").removeClass("driversBkgOne");
    	$("#driversBkgHandle").addClass("driversBkgTwo"); 	
    });
    
    $("#switchTwo").click(function(){    	
    	$("#displayTwo").css("display","none");
    	$("#displayOne").css("display","block");
    	$("#driversBkgHandle").removeClass("driversBkgTwo");
    	$("#driversBkgHandle").addClass("driversBkgOne");    	  		
    });  
	
  },
  
  /** function news
   *  initialize news page 
   */		
  news : function(){
    cr.nav.init();
    cr.flashInit.saleVehicles();
	cr.social.initTwitter();  
	cr.search.init();
  },
  
  /** function about
   *  initialize about page 
   */		
  about : function(){
    cr.nav.init(); 
    cr.search.init();
  },
  
  /** function schedule
   *  initialize schedule page 
   */		
  schedule : function(){
    cr.nav.init();    
    cr.schedule.init();
    cr.flashInit.upcomingRaces();
    cr.flashInit.saleVehicles();
    cr.search.init();
  },
  
  /** function community
   *  initialize community page 
   */		
  community : function(){
    cr.nav.init(); 
    cr.flashInit.saleVehicles();
    cr.search.init();
  }  
		
}; // end init namespace

/** Nav Namespace
 *  Used to init the top navigation
 */
cr.nav = {
  
  /** function init
   *  initialize navigation
   */	
  init : function (){
	
	// get all the nav objects
	var navObjects = $("#mainNav a:not(.subNavItem)");	
	
	// add mouseover/mouseout events
	navObjects.mouseover(function(){
		$(this).addClass("navOn");	
	});
	navObjects.mouseout(function(){
		$(this).removeClass("navOn");		
	});
	
	// look for all the subnav objects
	var subNavObjects = $("#mainNav .subNav a:not(.subNavItem)");
	
	// set the mouseover action for the subnav
	subNavObjects.mouseover(function(){
		clearTimeout(subNavTimeout); // set reset timer everytime we rollover
		
		// get the subNavigation
		$(this).next("ol").css("display", "block");			
		
		// if we are not the activeNav we will display the nav indicator
		if(!$(this).parent().hasClass("navActive"))
		  $(this).parent().addClass("subNavIndicator");
		
		// set the global vars used in the close function
		subNavObjectSelected = $(this);
		subNavObjectIndicator = $(this).parent();
	});	
	
	// get the container holding the nav and subnav,
	// we will need this to know if the mouse has moved
	// outside the nav and subnav both
	var subNavLis = $("#mainNav .subNav");	
	
	// set the mouseover event for the subnav, this
	// will just reset the timer.
	subNavLis.mouseover(function(){
		clearTimeout(subNavTimeout);		
	});
	
	// set the mouseout event this will call the closeSubNav function
	subNavLis.mouseout(function(){cr.nav.closeSubNav();});
	
  },
  
  /** function closeSubNav
   *  
   *  this function will close the subnav and reset the 
   *  indicator if the mouse has moved outside the subnav
   *  container.
   */
  closeSubNav : function() {    
    subNavTimeout = setTimeout(function(){      	
      $(subNavObjectSelected).next("ol").css("display", "none");
      $(subNavObjectIndicator).removeClass("subNavIndicator");
      subNavObjectSelected = null;	      
    }, 100);  
  } // end closeSubNav  
		
}; // end nav namespace

/** flashInit Namespace
 *  Contains the init flash functions
 */
cr.flashInit = {		
  
  home : function(){
	   
	var params = {
	  wmode: 'transparent'			
    };
	
    var attributes = {
	  id: 'home_flash',
	  name: 'home_flash'			
    };				
    
	var path = 'media/flash/home.swf';	
	var flashContainer = "homeFlash";
			
	// check if client has the correct version of flash
	var hasFlash = swfobject.hasFlashPlayerVersion('8');			
		
	// if the client has the correct flash display, else display nonflash content
	if(hasFlash){
		//swfobject.embedSWF(swfUrl, id, width, height, version, expressInstallSwfurl, flashvars, params, attributes, callbackFn)
		swfobject.embedSWF(path, flashContainer, '550', '430', '8', '', '', params, attributes, '');				
	}			
	
  }, // home 		
		
  upcomingRaces : function(){
   
	var params = {
	  wmode: 'transparent'			
    };
	
    var attributes = {
	  id: 'upcoming_flash',
	  name: 'upcoming_flash'			
    };				
    
	var path = 'media/flash/upcoming.swf';	
	var flashContainer = "upcomingRacesFla";
			
	// check if client has the correct version of flash
	var hasFlash = swfobject.hasFlashPlayerVersion('8');			
		
	// if the client has the correct flash display, else display nonflash content
	if(hasFlash){
		//swfobject.embedSWF(swfUrl, id, width, height, version, expressInstallSwfurl, flashvars, params, attributes, callbackFn)
		swfobject.embedSWF(path, flashContainer, '940', '45', '8', '', '', params, attributes, '');				
	}			
	
  }, // upcomingRaces
  
  saleVehicles : function(){
	   
	var params = {
	  wmode: 'transparent'			
    };
	
    var attributes = {
	  id: 'saleVehicles_flash',
	  name: 'saleVehicles_flash'			
    };				
    
	var path = 'media/flash/vehicles.swf';	
	var flashContainer = "saleVehiclesFla";
			
	// check if client has the correct version of flash
	var hasFlash = swfobject.hasFlashPlayerVersion('8');			
		
	// if the client has the correct flash display, else display nonflash content
	if(hasFlash){
		//swfobject.embedSWF(swfUrl, id, width, height, version, expressInstallSwfurl, flashvars, params, attributes, callbackFn)
		swfobject.embedSWF(path, flashContainer, '87', '39', '8', '', '', params, attributes, '');				
	}			
	
  } // salesVehicles
		
}; // end flashInit namespace

/** social Namespace
 *  social networking functions
 */
cr.social = {
  
  initTwitter : function () {
	// init twitter feeds
	$(".twitterdiv .feed").tweet({
        username: "copartracing",
        join_text: "auto",
        avatar_size: null,
        count: 10,
        auto_join_text_default: "",
        auto_join_text_ed: "",
        auto_join_text_ing: "",
        auto_join_text_reply: "",
        auto_join_text_url: "",
        loading_text: "loading tweets...",
		callback: cr.social.initTweets
    });    
	
	$('a#nextTweet').click(function(){
		cr.social.tweetNav(true, $(this))
	});
	$('a#prevTweet').click(function(){
		cr.social.tweetNav(false, $(this))
	});	
  },  
		
  initTweets : function(){
    $('ul.tweet_list li.tweet_first').addClass('current').fadeIn(300)
  },
  
  tweetNav : function(next, link) {
    $tweetList = $('ul.tweet_list');
	
	if (next) {
		if ($tweetList.find('.current').nextAll().length == 0) {
			return false;
		}
		$tweetList.find('.current').fadeOut(300, function(){
			$(this).removeClass('current').next().fadeIn(300).addClass('current')
			$tweetList.find('.current').nextAll().length == 0 ? $('a#nextTweet').addClass('off') : $('a#nextTweet').removeClass('off')
			$tweetList.find('.current').prevAll().length == 0 ? $('a#prevTweet').addClass('off') : $('a#prevTweet').removeClass('off')
		})
	} else {
		if ($tweetList.find('.current').prevAll().length == 0) {
			return false;
		}
		$tweetList.find('.current').fadeOut(300, function(){
			$(this).removeClass('current').prev().fadeIn(300).addClass('current')
			$tweetList.find('.current').nextAll().length == 0 ? $('a#nextTweet').addClass('off') : $('a#nextTweet').removeClass('off')
			$tweetList.find('.current').prevAll().length == 0 ? $('a#prevTweet').addClass('off') : $('a#prevTweet').removeClass('off')
		})
	}
  }		
		
}; // end social namespace

/** schedule Namespace
 *  schedule functions
 */
cr.schedule = {
  
  init : function() {
    cr.schedule.tabsInit();
//    cr.schedule.writeData();	
  },
  
  tabsInit : function() {
    $("#tabNation a").click(function(){	    	
      if(!$("#tabNation").hasClass('tabActive')){
        $("#tabNhra").removeClass("tabActive");
    	$("#tabNation").closest(".scheduleNav").removeClass("nhraActive");
    	$("#tabNation").addClass("tabActive");     		
    	$("#tabNation").closest(".scheduleNav").addClass("nationActive");    	
    	$("#nhraData").css("display", "none");
    	$("#nationData").css("display", "block");    	
      }     	
      return false;
    });
    $("#tabNhra a").click(function(){    	
      if(!$("#tabNhra").hasClass('tabActive')){
        $("#tabNation").removeClass("tabActive");
    	$("#tabNation").closest(".scheduleNav").removeClass("nationActive");
    	$("#tabNhra").addClass("tabActive");   
    	$("#tabNation").closest(".scheduleNav").addClass("nhraActive");
    	$("#nationData").css("display", "none");
    	$("#nhraData").css("display", "block");
      }    	
      return false;
    }); 
  },
  
  writeData : function() {  
	  
	  var nationStartTag = "<div id='nationData'><p>";
	  var nationStartTag2= "</p><table cellspacing='0'>";
	  var nhraStartTag = "<div id='nhraData'><p>";
	  var nhraStartTag2 = "</p><table cellspacing='0'>";	  
	  var scheduleHeader = "<tr class='schHead'><th class='schDate'>Date</th><th class='schTime'>Time(ET)</th>"
  		+ "<th class='schRace'>Race Name</th><th class='schTrack'>Track</th><th class='schTV'>TV</th>"
  		+ "<th class='schResult'>Finish</th><th class='schWrap'></th></tr>";
	  var scheduleHeaderNhra = "<tr class='schHead'><th class='schDateNhra'>Dates</th>"
  		+ "<th class='schRaceNhra'>Race Name</th><th class='schTrack'>Track</th><th class='schTVNhra'>TV(ET)</th>"
  		+ "<th class='schResult'>Finish</th><th class='schWrap'></th></tr>";				
	  var nationWideData = "";
	  var nhraData = "";	  
	  var endTag = "</table></div>";
	  
	  var firstNation = true;
	  var firstNhra = true;
	  
	  var nationIntro1 = $('#nascar-intro1').html() + "<br/>";
	  var nationIntro2 = $('#nascar-intro2').html();
	  var nhraIntro1 = $('#nhra-intro1').html();
	  var nhraIntro2 = $('#nhra-intro2').html();
	  
	  $.ajax({
          type: "GET",
          url: "media/xml/schedule.xml",
          dataType: "xml",
          success: function(xml) {
              
		   $(xml).find('item').each(function(){
            var type = $(this).attr('type');
            var copart = $(this).attr('copart');
			var result = $(this).find('result').text();
			
            if("nationwide" == type && "yes" == copart && result == ""){ 
				nationWideData += cr.schedule.wrapHTMLBoldNoFinish($(this), firstNation);
            	firstNation = false;
			}
			if("nationwide" == type && "yes" == copart && result != ""){ 
				nationWideData += cr.schedule.wrapHTMLBold($(this), firstNation);
            	firstNation = false;
			}
			if("nationwide" == type && "no" == copart && result == ""){ 
				nationWideData += cr.schedule.wrapHTMLNoFinish($(this), firstNation);
            	firstNation = false;
			}
			if("nationwide" == type && "no" == copart && result != ""){ 
				nationWideData += cr.schedule.wrapHTML($(this), firstNation);
            	firstNation = false;
			}
			if("nhra" == type && result == ""){
            	nhraData += cr.schedule.wrapHTMLNhraNoFinish($(this), firstNhra);
            	firstNhra = false;
            }  
            else if("nhra" == type && result != ""){
            	nhraData += cr.schedule.wrapHTMLNhra($(this), firstNhra);
            	firstNhra = false;
            }
			
            	
           }); //close each     		  
		   
		   $("#scheduleDataEl").html(nationStartTag + nationIntro1 + nationIntro2 + nationStartTag2 + scheduleHeader + nationWideData + endTag + nhraStartTag + nhraIntro1 + nhraIntro2 + nhraStartTag2 + scheduleHeaderNhra + nhraData + endTag);
              
          } // end success
      }); // end ajax	    
	  	
  },
  wrapHTMLBoldNoFinish : function (xmlNode, isFirstEl) {
    var htmlStringBoldNoFinish = "<tr>";  
    var firstELBoldNoFinish = "";  
    if(isFirstEl)firstELBoldNoFinish = " firstSch";
	htmlStringBoldNoFinish += "<td class='schDate" + firstELBoldNoFinish + "'><b>" + $(xmlNode).find('date').text() + "</b></td>";
    htmlStringBoldNoFinish += "<td class='schTime" + firstELBoldNoFinish + "'><b>" + $(xmlNode).find('time').text() + "</b></td>";
    htmlStringBoldNoFinish += "<td class='schRace" + firstELBoldNoFinish + "'><b>" + $(xmlNode).find('race').text() + "</b></td>";
    htmlStringBoldNoFinish += "<td class='schTrack" + firstELBoldNoFinish + "'><b>" + $(xmlNode).find('track').text() + "</b></td>";
    htmlStringBoldNoFinish += "<td class='schTV" + firstELBoldNoFinish + "'><b>" + $(xmlNode).find('tv').text() + "</b></td>";    
    htmlStringBoldNoFinish += "<td class='schResult" + firstELBoldNoFinish + "'>" + $(xmlNode).find('result').text() + "</td>";
	htmlStringBoldNoFinish += "<td class='schWrap" + firstELBoldNoFinish + "'></td>";
    htmlStringBoldNoFinish += "</tr>";    
    return htmlStringBoldNoFinish;	
 },
   wrapHTMLBold : function (xmlNode, isFirstEl) {
    var htmlStringBold = "<tr>";  
    var firstElBold = "";  
    if(isFirstEl)firstElBold = " firstSch";
	htmlStringBold += "<td class='schDate" + firstElBold + "'><b>" + $(xmlNode).find('date').text() + "</b></td>";
    htmlStringBold += "<td class='schTime" + firstElBold + "'><b>" + $(xmlNode).find('time').text() + "</b></td>";
    htmlStringBold += "<td class='schRace" + firstElBold + "'><b>" + $(xmlNode).find('race').text() + "</b></td>";
    htmlStringBold += "<td class='schTrack" + firstElBold + "'><b>" + $(xmlNode).find('track').text() + "</b></td>";
    htmlStringBold += "<td class='schTV" + firstElBold + "'><b>" + $(xmlNode).find('tv').text() + "</b></td>";    
    htmlStringBold += "<td class='schResult" + firstElBold + "'>" + $(xmlNode).find('result').text() + "</td>";
	htmlStringBold += "<td class='schWrap" + firstElBold + "'><a href='" + $(xmlNode).find('link').text() + "' target=\"_blank\">WRAP-UP</a></td>";
    htmlStringBold += "</tr>";    
    return htmlStringBold;	
 },
  wrapHTML : function (xmlNode, isFirstEl) {
    var htmlString = "<tr>";  
    var firstEl = "";  
    if(isFirstEl)firstEl = " firstSch";
	htmlString += "<td class='schDate" + firstEl + "'>" + $(xmlNode).find('date').text() + "</td>";
    htmlString += "<td class='schTime" + firstEl + "'>" + $(xmlNode).find('time').text() + "</td>";
    htmlString += "<td class='schRace" + firstEl + "'>" + $(xmlNode).find('race').text() + "</td>";
    htmlString += "<td class='schTrack" + firstEl + "'>" + $(xmlNode).find('track').text() + "</td>";
    htmlString += "<td class='schTV" + firstEl + "'>" + $(xmlNode).find('tv').text() + "</td>";    
    htmlString += "<td class='schResult" + firstEl + "'>" + $(xmlNode).find('result').text() + "</td>"; 
	htmlString += "<td class='schWrap" + firstEl + "'><a href='" + $(xmlNode).find('link').text() + "' target=\"_blank\">WRAP-UP</a></td>";
    htmlString += "</tr>";    
    return htmlString;	
 },
  wrapHTMLNoFinish : function (xmlNode, isFirstEl) {
    var htmlStringNoFinish = "<tr>";  
    var firstElNoFinish = "";  
    if(isFirstEl)firstElNoFinish = " firstSch";
	htmlStringNoFinish += "<td class='schDate" + firstElNoFinish + "'>" + $(xmlNode).find('date').text() + "</td>";
    htmlStringNoFinish += "<td class='schTime" + firstElNoFinish + "'>" + $(xmlNode).find('time').text() + "</td>";
    htmlStringNoFinish += "<td class='schRace" + firstElNoFinish + "'>" + $(xmlNode).find('race').text() + "</td>";
    htmlStringNoFinish += "<td class='schTrack" + firstElNoFinish + "'>" + $(xmlNode).find('track').text() + "</td>";
    htmlStringNoFinish += "<td class='schTV" + firstElNoFinish + "'>" + $(xmlNode).find('tv').text() + "</td>";    
    htmlStringNoFinish += "<td class='schResult" + firstElNoFinish + "'>" + $(xmlNode).find('result').text() + "</td>"; 
	htmlStringNoFinish += "<td class='schWrap" + firstElNoFinish + "'></td>";
    htmlStringNoFinish += "</tr>";    
    return htmlStringNoFinish;	
 },
  
  wrapHTMLNhra : function (xmlNode, isFirstEl) {
    var htmlStringNhra = "<tr>";  
    var firstElNhra = "";  
    if(isFirstEl)firstElNhra = " firstSch";
	htmlStringNhra += "<td class='schDateNhra" + firstElNhra + "'>" + $(xmlNode).find('date').text() + "</td>";
    htmlStringNhra += "<td class='schRace" + firstElNhra + "'>" + $(xmlNode).find('race').text() + "</td>";
    htmlStringNhra += "<td class='schTrack" + firstElNhra + "'>" + $(xmlNode).find('track').text() + "</td>";
    htmlStringNhra += "<td class='schTV" + firstElNhra + "'>" + $(xmlNode).find('tv').text() + "</td>";    
    htmlStringNhra += "<td class='schResult" + firstElNhra + "'>" + $(xmlNode).find('result').text() + "</td>"; 
	htmlStringNhra += "<td class='schWrap" + firstElNhra + "'><a href='" + $(xmlNode).find('link').text() + "' target=\"_blank\">WRAP-UP</a></td>";
    htmlStringNhra += "</tr>";    
    return htmlStringNhra;	
 },
   
  wrapHTMLNhraNoFinish : function (xmlNode, isFirstEl) {
    var htmlStringNhraNoFinish = "<tr>";  
    var firstElNhraNoFinish = "";  
    if(isFirstEl)firstElNhraNoFinish = " firstSch";
	htmlStringNhraNoFinish += "<td class='schDateNhra" + firstElNhraNoFinish + "'>" + $(xmlNode).find('date').text() + "</td>";
    htmlStringNhraNoFinish += "<td class='schRace" + firstElNhraNoFinish + "'>" + $(xmlNode).find('race').text() + "</td>";
    htmlStringNhraNoFinish += "<td class='schTrack" + firstElNhraNoFinish + "'>" + $(xmlNode).find('track').text() + "</td>";
    htmlStringNhraNoFinish += "<td class='schTV" + firstElNhraNoFinish + "'>" + $(xmlNode).find('tv').text() + "</td>";    
    htmlStringNhraNoFinish += "<td class='schResult" + firstElNhraNoFinish + "'>" + $(xmlNode).find('result').text() + "</td>"; 
	htmlStringNhraNoFinish += "<td class='schWrap" + firstElNhraNoFinish + "'></td>";
    htmlStringNhraNoFinish += "</tr>";    
    return htmlStringNhraNoFinish;	
 }
 
}; // end schedule namespace

/** search Namespace
 *  search functions
 */
cr.search = {
  init : function(){
    $("#SearchForm").submit(function() {
	  var searchValue = $("#searchTxt").val();
	  searchValue = $.trim(searchValue);
	  var searchType = $("input[@name=ftOptions]:checked").val();	  
	  var prefix = "";
	  if ("+" == searchType) {
	  	prefix = "+";
	  }
	  searchValue = prepareQueryString(searchValue, prefix);
	  /*
	  if("+" == searchType){
		 searchValue = "+" + searchValue + "*";		  
	  }	
	  */  	  
	  $("#textSearch").val(searchValue.replace(/&/g, '').replace(/,/g, ''));
	  $("#filterBaseLabel").val(searchValue);
    });	
  } // end init		
};

/**
 * This method splits the search string and adds symbol '+' to indicate this is a AND search.
 * @param {Object} searchString
 * @param {Object} prefix
 */
function prepareQueryString(searchString, prefix) {
	var newString="";
	var tokens = searchString.split(" ");
	for (var i = 0; i < tokens.length; i++) {
		newString = newString + prefix + $.trim(tokens[i]) + "* ";
	}
	return $.trim(newString);
}
