$(document).ready(function() {
	// do stuff when DOM is ready
	
	// hide the SEO links
	$("#permaLinks").css('display', 'none');
	
	//preload initial imgs
	var bgImg = $('<img />').attr('src', 'images/special_bg.jpg');
	var loadingImg = $('<img />').attr('src', 'images/ajax-loader.gif');
	$("#loading").show();
	
	// load external xml file, then parse upon success
	$.ajax({
		type: 'GET',
		url: 'new_specials.xml',
		dataType: "xml",
		success: parseXML,
		error: errorXML
	}); //close $.ajax
		
 }); // close document.ready


function errorXML() {
	$('div#loading').replaceWith("<p>Sorry, but there was an error loading the data.</p>");
}

function parseXML(xml) {
	
	// define the variable that will hold all the new HTML as it's built.
	var html=''; 
	
	// set up environment to test text widths
	$("<div id='tests'></div>")
		.html(html)
		.css({
			'position'	: 'fixed',
			'top'		: 0,
			'left'		: 0,
			'visibility'	: 'hidden',
			'z-index'		: 0
			})
		.appendTo('body');
	var html2 = '';
	
	
	// Define variables
	var year = '';
	var model = '';
	var rebate = '';
	var modelImg = '';
	
	// define and Parse the two variables that should appear only *once* in the XML file
	var disclaimer = $(xml).find('disclaimer').text();
	var expiration = $(xml).find('expiration').text();
	
	
	html  += "<div id='units'>";
	
	// Parse the per-unit data from XML and add it to the html container
	$(xml).find('vehicle').each(function(i) {
		
		// find each unit's data and assign to variables
		year = $(this).find('year').text();
		model = $(this).find('model').text();
		rebate = $(this).find('rebate').text();
		
		/* Build the string for the image location, based on the model name & year */
		//tweak the model name to (hopefully) ensure that spaces and letter-case don't interfere
		modelImg = model.toLowerCase();
		modelImg = modelImg.split(' ').join('');
		modelImg = modelImg.split('-').join('');
		modelImgPath = "images/new_specials/" + modelImg + "_" + year + ".jpg";
		//preload model img
		var preloaderImg = $('<img />').attr('src', modelImgPath );
		
		/* Determine if a unit is a hybrid, and make the appropriate link based on that info */
		//re-use modelImg to identify a non-Hybrid
		if (modelImg.indexOf('hybrid') == -1) {		
			/* Build the string for the link location */
			unitLink1 = "http://www.greshamtoyota.com/en_us/typebrowse.asp?StoreID=4&amp;Make=Toyota&amp;Model=" + model + "&amp;Vintage=395&amp;MinYear=" + year + "&amp;MaxYear=" + year +"&amp;internetspecial=1";
			unitLink2 = "http://www.greshamtoyota.com/en_us/rebates.asp?series="+model;
		} else {
			//remove 'hybrid' from the name and re-capitalize
			newModelName = (modelImg.split('hybrid').join('').charAt(0).toUpperCase()) + (modelImg.split('hybrid').join('').slice(1));
			/* Build the string for the link location */
			unitLink1 = "http://www.greshamtoyota.com/en_us/typebrowse.asp?StoreID=4&amp;Make=Toyota&amp;Model=" + newModelName + "&amp;Vintage=395&amp;fueltype=hybrid&amp;MinYear=" + year + "&amp;MaxYear=" + year +"&amp;internetspecial=1";
			unitLink2 = "http://www.greshamtoyota.com/en_us/rebates.asp?series="+newModelName;
		}
		
		// build each unit's chunk of html
		html += "<div class='unit'>";
		html += "<a href='" + unitLink1 + "' title='View our " + year + " " + model +" Inventory'><span class='model'>" + year + " " + model + "</span></a>";
		html += "<a href='" + unitLink1 + "'><span class='rebate";
		
			/* Determine if the Rebate text will be too wide for the interface... */
			$("<span class='rebate' id='testRebate"+i+"'></span>")
				.html(rebate)
				.appendTo("#tests");
				
			thisTest = $("#tests #testRebate"+i+"").width();
			//$.log(""+year+" "+model+" - "+rebate+" - width: "+thisTest+"px");
			
			if (thisTest > 228) {
				html += " shrinkMe";
			}
				
		html += "'>" + rebate + "</span></a>";		
		html += "<a href='" + unitLink1 + "' title='View our " + year + " " + model +" Inventory'><span class='unitImg'><img src='"+ modelImgPath +"' /></span></a>";
		html += "<a class='moreInfoLink' href='" + unitLink2 + "'>View Current Incentives</a>";
		html += "</div>"
		
	}); // end xml: each vehicle
	
	html += "</div>"
	// Don't forget to add the fine print
	html += "<div id='smallPrint'>"
	//Disclaimer & expiration
	html += "<div id='disclaimer'>* Disclaimer: Offer ends "+ expiration + ". " + disclaimer + "</div>"
	html += "</div>"
	
	$("#loading").hide('fast');
	
	$("#tests").remove();
	
	$("<div id='specials'></div>")
		.html(html)
		.appendTo('#specialsWrap');
			
}; // end parseXML

/* Console Logging for debugging help
 * A log function has been attached to the jQuery object.
 * You can then call this in your code using 
 * 	jQuery.log('my message') or $.log('my message') 
 */
;jQuery.log = function(message) {
  try {
     console.debug(message);
  } catch(e) {
	  try {
		console.log(message);
	  } catch(e) {
		//alert(message);
	  }
  }
};
