$(function() {
//alphabetical order
//call the functions here - define the functions below
	
	maintenance_tabs();
	my_accessory_brochure();
	my_gtp_value();
	my_model_brochure();
	my_owners_manual();
	my_partner_tabs();
	my_poll();
	my_subscriptions();
	my_vehicle_recall_detail();
	my_stories_modal();
	service_alert_close_button();
	submit_trade_in_button();
	
	added_security_bolding(); // this has to be called AFTER rolldown_items()
	

}); //end of document.ready

//-----------------------------------------------------------------------------------
//functions in alphabetical order. Called above from document.ready
//-----------------------------------------------------------------------------------


//added security bolding
	
function added_security_bolding(){
var added_security = $("#added_security").size();
	if (added_security != 0) {

		if(warType != ""){
			var SubaruPlans = $(".rolldown_container");
			$(SubaruPlans).find(".rolldown_top a").each(function(){
				if ($(this).html() == "Subaru Plans"){
					$(this).parent().next().slideToggle('slow');
					$(this).parent().toggleClass("opened", 'slow');
				}//end if
			});//end each
		}

		if(warType == "SAS Gold Coverage"){
		$("li.gold").addClass("bold");
		}

		if(warType == "SAS Powertrain Coverage"){
		$("div.maintenance").addClass("bold");
		$("p.maintenance").addClass("bold");
		$("li.maintenance").addClass("bold");
		}

		if(warType == "SAS Classic Coverage"){
		$("li.classic").addClass("bold");
		}


	}//end if
}//end added_security_bolding




 //capitalize 

function capitalize(incomingString, fromWhere){
	
    //extract the first letter of str
  var letter = incomingString.substr(0,1);
   //return letter capitalised concatonated with
   //str minus it's first letter
   var str = incomingString.toLowerCase()
  return letter.toUpperCase() + str.substr(1);
} 


//change dealer, requires component google/form-hidden-change-dealer
function changeDealerForm (dealertype,dealerzip,vehicle) {
	yOffset = get_page_scroll() + 120;
	//always send back to my-dealer
	var currentPage = "/my-subaru/my-account/my-dealer.html";
	var targetForm = '#change_dealer_' + dealertype;
	var targetModal = '#modalFormContainer_' + dealertype;
	$(targetForm).attr('action',linkPrefix + 'my-subaru/data/dealer/find?'+dealertype+'dealerzip='+dealerzip+'&vehiclenum='+vehicle+'&targeturl='+currentPage);
	$(targetModal).modal({
		containerId: 'mcFindDealer'
	});
	$('#modalOverlay').css({height:($(document).height().toString() + "px"), overflow:"hidden"});
	$('#mcFindDealer').css({'top': yOffset + 'px'});
	live_query_dealer_validate(targetForm);
}

//setNewDealer, requires component google/form-hidden-set-dealer
function setNewDealer (dealertype,dealerid,targeturl,vehicle) {
	var targetForm = '#set_dealer_' + dealertype;
	$(targetForm + ' input[name=targetUrl]').val(targeturl);
	$(targetForm + ' input[name='+dealertype+'DealerId]').val(dealerid);
	if (!vehicle) {}
	else {$(targetForm + ' input[name=vehicleId]').val(vehicle);}
	
	//$(targetForm).submit();
	newTarget = targeturl.substr(1);
	var formData = $(targetForm).serialize();
	var formAction = $(targetForm).attr("action");
	var redirectURL = linkPrefix+newTarget;
	$.ajax({
		type: "post",
		url: formAction,
		data: formData,
		cache: false,
		error: function (XMLHttpRequest, textStatus, errorThrown) {
			var error = errorThrown
			alert(error);
		},
		success: function(data, textStatus) {
			window.location.assign(redirectURL);
		}
	});
}

// setNewDealer_ajax
function setNewDealer_ajax (dealertype,dealerid,targeturl,vehicle) {
	var targetForm = '#set_dealer_' + dealertype;
	var formAction = "";
	if (dealertype == "preferred") {
		formAction = linkPrefix+'tools/maps/user/setpreferreddealer';
	}
	else if (dealertype == "service") {
		formAction = linkPrefix+'tools/maps/vehicle/setservicedealer';
	}
	//var currentAction = $(targetForm).attr("action");
	//var formAction = secureUrl+currentAction;
	$(targetForm + ' input[name=targetUrl]').val(targeturl);
	$(targetForm + ' input[name='+dealertype+'DealerId]').val(dealerid);
	$(targetForm).attr('action', formAction);
	if (!vehicle) {}
	else {$(targetForm + ' input[name=vehicleId]').val(vehicle);}
	
	//$(targetForm).serialize();
	//$(targetForm).submit();
	var formData = $(targetForm).serialize();
	var formUrl = $(targetForm).attr("action");
	//  /tools/gtp/vehicle/sendgtpinformation
	newTarget = targeturl.substr(1);
	//var redirectURL = linkPrefix+'my-subaru/my-account/index.html';
	var redirectURL = targeturl;
	$.ajax({
		type: "post",
		url: formAction,
		data: formData,
		error: function (XMLHttpRequest, textStatus, errorThrown) {
			window.location.assign(redirectURL);
		},
		success: function(data, textStatus) {
			window.location.assign(redirectURL);
		}
	});
}


//build my vehicle nav
function build_my_vehicle_nav(vehicles_object, tertiaryId, sel_veh, landing_page){

	var vehicles = vehicles_object;
	var tertiary_id = tertiaryId;
	var selected_array_index = sel_veh;
	if (!landing_page){
	var linkback = "my-subaru/my-account/my-dealer.html";
	} else {
	var linkback = "my-subaru/my-account/my-profile.html";
	}



	
		function bold_the_link(arrayIndex, count){
			var array_index = arrayIndex;
			var count = count;

			if (array_index == count){
				var a = "selected";
			} else {
				var a = " ";
			}	
			return a;
		 }


	var tert = "";
	
	   var count = 0;
	$(vehicles).find("VEHICLE").each(function(){
		var vehicleYear = $(this).attr("YEAR");
		var vehicleModel = capitalize($(this).attr("MODEL"), 6);
		var vehicleTrim = $(this).attr("TRIM");
		var vehicle_vin = $(this).attr("VIN");
		var vehicle_id = $(this).attr("VEHICLE_ID");
		var arrayIndex = $(this).attr("ARRAY_INDEX");
		tert += '<li><a class=" '+ bold_the_link(selected_array_index, count) +' " id="'+ arrayIndex +'" href="'+ linkPrefix + linkback +'?vid='+arrayIndex+'&vehid='+ vehicle_id +'" >' + vehicleYear + ' ' + vehicleModel + ' ' + vehicleTrim + '</a></li>';
		count++;
		});//end of for loop
return tert;

}//end build my vehicle nav

//get buildURL
function get_buildURL(vehicleYear, myModel, modelCode, vehicle_id){
	// remove whitespace
	var buildURL = linkPrefix + "vehicles/";
	var myModel = myModel.toUpperCase();
	var vehicleYear = jQuery.trim(vehicleYear);
	var yearAbbrev = vehicleYear.substr(2);
	myModel = jQuery.trim(myModel).toUpperCase();
	var buildURLS = $.ajax({
		url: pathPrefix+'vehicles/my'+yearAbbrev+'/models.xml',
		async: false,
		cache: false
	});

	$(buildURLS.responseXML).find("model[modelName="+myModel+"]").each(function() {
		$(this).find("trim").each(function() {
			var mc = $(this).attr("modelCode");
			if (modelCode.toLowerCase() == mc.toLowerCase()) {
				buildURL += $(this).attr("buildURL");
			}//end if modelCode = mc
		
		
		})//end each trim
	
	})//end each modelname

	buildURL += "build.html?vehicleId="+ vehicle_id;
	return buildURL;

}


//get Accessory Brochure
function get_accBrochure(vehicleYear, myModel, myTrim){
	// remove whitespace
	var accBrochure = pathPrefix + "downloads/pdf/accbrochures/";
	var vehicleYear = jQuery.trim(vehicleYear);
	var yearAbbrev = vehicleYear.substr(2);
	myModel = jQuery.trim(myModel).toLowerCase();
	myModel = capitalize(myModel, 7);
	myTrim = jQuery.trim(myTrim).toLowerCase();
	myTrim = capitalize(myTrim, 8);
	
	var accbrochures = $.ajax({
		url: pathPrefix+'vehicles/my'+yearAbbrev+'/models.xml',
		async: false,
		cache: false
	});
	var regex = /.*WRX.*/;
	$(accbrochures.responseXML).find("model[modelName="+myModel+"]").each(function() {
		var acc = $(this).attr("accBrochure");
		var accWRX = $(this).attr("accBrochureWRX");
		if (accWRX === undefined) {
			accWRX = acc;
		}
		
			
				if (myTrim.match(regex)) {
					accBrochure += accWRX;
				}
				 else {
					accBrochure += acc;
				}	
			
		
	}); //end each modelname
	return accBrochure;
}


//get Model Brochure
function get_modelBrochure(vehicleYear, myModel, myTrim){
	// remove whitespace
	var modelBrochure = pathPrefix + "downloads/pdf/brochures/";
	var vehicleYear = jQuery.trim(vehicleYear);
	var yearAbbrev = vehicleYear.substr(2);
	myModel = jQuery.trim(myModel).toLowerCase();
	myModel = capitalize(myModel, 9);
	myTrim = jQuery.trim(myTrim).toLowerCase();
	myTrim = capitalize(myTrim, 10);
	var brochures = $.ajax({
		url: pathPrefix+'vehicles/my'+yearAbbrev+'/models.xml',
		async: false,
		cache: false
	});
	var regex = /.*WRX.*/;
	$(brochures.responseXML).find("model[modelName="+myModel+"]").each(function() {
		var mb = $(this).attr("modelBrochure");
		var wrxb = $(this).attr("modelBrochureWRX");
		if (wrxb === undefined) {
			wrxb = mb;
		}
			
				if (myTrim.match(regex)) {
					modelBrochure += wrxb;
				}
				 else {
					modelBrochure += mb;
				}	
				
	}); //end each modelname
	
	return modelBrochure;
}

//get OwnersManual
function get_ownersManual(vehicleYear, myModel){
	// remove whitespace
	var ownersManual = pathPrefix + "downloads/pdf/manuals/";
	var vehicleYear = jQuery.trim(vehicleYear);
	var yearAbbrev = vehicleYear.substr(2);
	myModel = jQuery.trim(myModel);
	var manuals = $.ajax({
		url: pathPrefix+'vehicles/my'+yearAbbrev+'/models.xml',
		async: false,
		cache: false
	});

	$(manuals.responseXML).find("model[modelName="+myModel+"]").each(function() {
			
		ownersManual += $(this).attr("ownersManual");	
	})//end each modelname

	
	return ownersManual;

}

//get page scroll
function get_page_scroll() {
	var ScrollTop = document.body.scrollTop;
	if (ScrollTop == 0) {
		if (window.pageYOffset) ScrollTop = window.pageYOffset;
		else ScrollTop = (document.body.parentElement) ? document.body.parentElement.scrollTop : 0;
	}
	return ScrollTop;
}

//maintenance-tabs
function maintenance_tabs(){
	var maintenance_tabs = $("#maintenance_tabs").size();
	if (maintenance_tabs != 0) {
		var vehicles = vehicles_owned;
		var vehicleYear = "";
		var vehicleModel = "";
		var vehicleTrim = "";
		$(vehicles).find("VEHICLE").each(function() {
			vehicleYear = $(this).attr("YEAR");
			vehicleModel = capitalize($(this).attr("MODEL"), 11);
			vehicleTrim =  $(this).attr("TRIM");
		});
		
		// get the dealer's maintenance schedule
		var dealer_maintenance = get_maintenanceScheduleDealer(vehicle_id);
		var manufacturer_maintenance = get_maintenanceScheduleManufacturer(vehicle_id);
		var dmt = "";
		var mmt = "";
		
		// count the overdue service records
		var overDueDealerServiceRecords = $(dealer_maintenance.responseXML).find("maintenanceRecord[overdue=true]").size();
		var overDueManufacturerServiceRecords = $(manufacturer_maintenance.responseXML).find("maintenanceRecord[overdue=true]").size();
		
		// start the "div" table
		var mt = '\n<div class="table_row table_head">';
			mt += '\n\t<div class="col1"><p>Interval</p></div>';
			mt += '\n\t<div class="col2"><p>Status</p></div>';
			mt += '\n\t<div class="col3"><p>Action</p></div>';
			mt += '\n\t<div class="clear"> </div>';
			mt += '\n</div>';
			
		// build the dealer schedule
		$(dealer_maintenance.responseXML).find("maintenanceRecord").each(function(index, thisElement) {
			var row_class = (index%2) ? "" : "odd";
			var completed = $(this).attr("completed");
			var overdue = $(this).attr("overdue");
			var maintenanceID = $(this).find("maintenanceID").text();
			var manufacturerRecomends = $(this).find("manufacturerRecomends").text();
			var title = $(this).find("title").text();
			var mileage = $(this).find("mileage").text();
			var description = $(this).find("description").text();
			var descArray = description.split("|");
			var lastOverdue = '<p>Maintenance performed? <a href="'+linkPrefix+'my-subaru/my-account/service-history.html?vid='+sel_veh+'&vehid='+vehicle_id+'" title="Record Service">Record this service</a> in your <a href="'+linkPrefix+'my-subaru/my-account/service-history.html?vid='+sel_veh+'&vehid='+vehicle_id+'" target="_blank">Service History</a>.</p>';
				lastOverdue += '<p>You can call '+ms_dealerName+' at '+ms_dealerPhone+' or <a href="'+ms_dealerUrl+'" title="Schedule Service Appointment" target="_blank">schedule this service online</a> to set an appointment today.</p>';
			var status = "";
			var statusClass = "";
			if (completed == "true") {
				status = "Completed";
				statusClass = "";
				lastOverdue = "";
			}
			else if (completed == "false" && overdue == "false") {
				status = "Open";
				statusClass = "";
			}
			else if (completed == "false" && overdue == "true") {
				status = "Overdue"
				statusClass = "overdue";
				
				/*
				if (index == (overDueDealerServiceRecords-1)) {
					lastOverdue = '<p>Maintenance performed? <a href="'+linkPrefix+'my-subaru/my-account/service-history.html?vid='+sel_veh+'&vehid='+vehicle_id+'" title="Record Service">Record this service</a> in your <a href="'+linkPrefix+'my-subaru/my-account/service-history.html?vid='+sel_veh+'&vehid='+vehicle_id+'" target="_blank">Service History</a>.</p>';
					lastOverdue += '<p>You can call '+ms_dealerName+' at '+ms_dealerPhone+' or <a href="'+ms_dealerUrl+'" title="Schedule Service Appointment" target="_blank">schedule this service online</a> to set an appointment today.</p>';
				}
				else {
					lastOverdue = '&nbsp;';
				}
				*/
			}
			
			dmt += '\n<div class="table_row table_cell '+row_class+'">';
			dmt += '\n\t<div class="col1"><p><a href="#" rel="dealer_detail_'+index+'">'+title+'</a></div>';
			dmt += '\n\t<div class="col2 '+statusClass+'"><p>'+status+'</div>';
			dmt += '\n\t<div class="col3">'+lastOverdue+'</div>';
			dmt += '\n\t<div id="dealer_detail_'+index+'" class="row_detail">';
			dmt += '\n\t\t<h3>Maintenance Details</h3>';
			dmt += '\n\t\t<p class="close"><a href="#" rel="dealer_detail_'+index+'">Close</a></p>';
			dmt += '\n\t\t<p><strong>Vehicle:</strong> '+vehicleYear+' '+vehicleModel+' '+vehicleTrim+'</p>';
			dmt += '\n\t\t<p><strong>Interval:</strong> '+title+'</p>';
			if (description.length > 0) {
				dmt += '\n\t\t<table>';
				dmt += '\n\t\t\t<tr>';
				dmt += '\n\t\t\t\t<th>Action</th>';
				dmt += '\n\t\t\t\t<th>Description</th>';
				dmt += '\n\t\t\t</tr>';
				jQuery.each(descArray, function(i, val) {
					var thisRowClass = (i%2) ? "" : "odd";
					var detail = val.split(" - ");
					dmt += '\n\t\t\t<tr class="'+thisRowClass+'">';
					dmt += '\n\t\t\t\t<td>'+detail[0]+'</td>';
					dmt += '\n\t\t\t\t<td>'+detail[1]+'</td>';
					dmt += '\n\t\t\t</tr>';
				});	
				dmt += '\n\t\t</table>';
			}
			dmt += '\n\t</div>';
			dmt += '\n\t<div class="clear"> </div>';
			dmt += '\n</div>';
			
		});
		
		var dealerDetail = mt+dmt;
		$('#dealer_schedule').empty().append(dealerDetail);
		
		// build the manufacturer schedule	
		$(manufacturer_maintenance.responseXML).find("maintenanceRecord").each(function(index, thisElement) {
			var row_class = (index%2) ? "" : "odd";
			var completed = $(this).attr("completed");
			var overdue = $(this).attr("overdue");
			var maintenanceID = $(this).find("maintenanceID").text();
			var manufacturerRecomends = $(this).find("manufacturerRecomends").text();
			var title = $(this).find("title").text();
			var mileage = $(this).find("mileage").text();
			var description = $(this).find("description").text();
			var descArray = description.split(", ");
			var lastOverdue = '<p>Maintenance performed? <a href="'+linkPrefix+'my-subaru/my-account/service-history.html?vid='+sel_veh+'&vehid='+vehicle_id+'" title="Record Service">Record this service</a> in your <a href="'+linkPrefix+'my-subaru/my-account/service-history.html?vid='+sel_veh+'&vehid='+vehicle_id+'" target="_blank">Service History</a>.</p>';
				lastOverdue += '<p>You can call '+ms_dealerName+' at '+ms_dealerPhone+' or <a href="'+ms_dealerUrl+'" title="Schedule Service Appointment" target="_blank">schedule this service online</a> to set an appointment today.</p>';
			var status = "";
			var statusClass = "";
			if (completed == "true") {
				status = "Completed";
				statusClass = "";
				lastOverdue = "";
			}
			else if (completed == "false" && overdue == "false") {
				status = "Open";
				statusClass = "";
			}
			else if (completed == "false" && overdue == "true") {
				status = "Overdue"
				statusClass = "overdue";
				
				/*
				if (index == (overDueDealerServiceRecords-1)) {
					lastOverdue = '<p>Maintenance performed? <a href="'+linkPrefix+'my-subaru/my-account/service-history.html?vid='+sel_veh+'&vehid='+vehicle_id+'" title="Record Service">Record this service</a> in your <a href="'+linkPrefix+'my-subaru/my-account/service-history.html?vid='+sel_veh+'&vehid='+vehicle_id+'" target="_blank">Service History</a>.</p>';
					lastOverdue += '<p>You can call '+ms_dealerName+' at '+ms_dealerPhone+' or <a href="'+ms_dealerUrl+'" title="Schedule Service Appointment" target="_blank">schedule this service online</a> to set an appointment today.</p>';
				}
				else {
					lastOverdue = '&nbsp;';
				}
				*/
			}
			
			mmt += '\n<div class="table_row table_cell '+row_class+'">';
			mmt += '\n\t<div class="col1"><p><a href="#" rel="manufacturer_detail_'+index+'">'+title+'</a></div>';
			mmt += '\n\t<div class="col2 '+statusClass+'"><p>'+status+'</div>';
			mmt += '\n\t<div class="col3">'+lastOverdue+'</div>';
			mmt += '\n\t<div id="manufacturer_detail_'+index+'" class="row_detail">';
			mmt += '\n\t\t<h3>Maintenance Details</h3>';
			mmt += '\n\t\t<p class="close"><a href="#" rel="manufacturer_detail_'+index+'">Close</a></p>';
			mmt += '\n\t\t<p><strong>Vehicle:</strong> '+vehicleYear+' '+vehicleModel+' '+vehicleTrim+'</p>';
			mmt += '\n\t\t<p><strong>Interval:</strong> '+title+'</p>';
			if (description.length > 0) {
				mmt += '\n\t\t<table>';
				mmt += '\n\t\t\t<tr>';
				mmt += '\n\t\t\t\t<th>Action</th>';
				mmt += '\n\t\t\t\t<th>Description</th>';
				mmt += '\n\t\t\t</tr>';
				jQuery.each(descArray, function(i, val) {
					var thisRowClass = (i%2) ? "" : "odd";
					var detail = val.split(" - ");
					mmt += '\n\t\t\t<tr class="'+thisRowClass+'">';
					mmt += '\n\t\t\t\t<td>'+detail[0]+'</td>';
					mmt += '\n\t\t\t\t<td>'+detail[1]+'</td>';
					mmt += '\n\t\t\t</tr>';
				});	
				mmt += '\n\t\t</table>';
			}
			mmt += '\n\t</div>';
			mmt += '\n\t<div class="clear"> </div>';
			mmt += '\n</div>';
			
		});
		
		var manufacturerDetail = mt+mmt;
		$('#manufacturer_schedule').empty().append(manufacturerDetail);
		
		$("#maintenance_tabs").tabs();
		
		$(".table_row .col1 a").livequery('click', function(e) {
			e.preventDefault();
			var detailId = $(this).attr("rel");
			var detailClass = $(this).attr("class");
			
			if (detailClass == "open") {
				$("#"+detailId).slideUp("slow");
				$(this).removeClass("open");
				$("#"+detailId+" p.close a").removeClass("open");
			} else {
				$("#"+detailId).slideDown("slow");
				$(this).addClass("open");
				$("#"+detailId+" p.close a").addClass("open");
			}
			return false;
		});
		
		// close link
		$(".row_detail a.open").livequery('click', function(e) {
			e.preventDefault();
			var detailId = $(this).attr("rel");
			$("#"+detailId).slideUp("slow");
			$(".table_row .col1 a").removeClass("open");
			$(this).removeClass("open");
			return false;
		});
	}
}

//my accessory brochure
function my_accessory_brochure(){
	var article_accessory_brochure = $(".article_accessory_brochure").size();
	if (article_accessory_brochure != 0) {
		if(vehicleYear > 1997){
		var accBrochure = get_accBrochure(vehicleYear, vehicleModel, vehicleTrim);
		$(".article_accessory_brochure .brochure-pdf").attr("href", accBrochure);
		} else {
		$(".article_accessory_brochure  .article_container").contents().empty();
		var tooOldError = "We're sorry to say that an online version of your Owner's Manual is not available. Unfortunately, we do not have access to an electronic version of manuals prior to 1998 model year vehicles. Please refer to the Owner's Manual you received with your Subaru at the time of purchase to answer any questions you may have.";
		$(".article_accessory_brochure .summary").append(tooOldError);
		
		}
	}//end if accessory brochure
}

//my gtp_value
function my_gtp_value(){
var gtp_Success = $(".gtp_Success").size();
	if (gtp_Success != 0){
	var gtpInfoXml = get_gtpInformation(gtp_vehicle_id, "vehicle_id");
	
		$(gtpInfoXml.responseXML).find("priceInfo").each(function() {
		var status = $(this).find("status").text();
		if(status==0){
			var gtpValue = $(this).find("value").text();
			var gtpValueHTML = formatCurrency(gtpValue);
			var gtpEndDate = $(this).find("endDate").text();
			var gtpMileage = formatCommas($(this).find("mileage").text());
			var gtpEndDateHTML = '&ndash; Guaranteed Until ' + gtpEndDate + '* <a href="'+ linkPrefix +'finance-center/guaranteed-trade-in-program/rules-eligibility.html">See Applicable Restrictions</a>';
			$("div.trade_in_value span.gtpMileage").append(gtpMileage);
			$("div.trade_in_value span.trade_in_value").append(gtpValueHTML);
			$("div.trade_in_value span.guaranteedUntil").append(gtpEndDateHTML);
			
			$("#gtpSuccess").show();
		} else if(status == 1){
			$("#gtpError1").show();
		} else if(status == 2){
			$("#gtpError2").show();		
		} else if(status == 3){
			$("#gtpError3").show();		
		}
	
		});//end each
	}//end if 

}//end function

//my model brochure
function my_model_brochure(){
	var article_model_brochure = $(".article_model_brochure").size();
	if (article_model_brochure != 0) {
	if(vehicleYear > 2004){
		var modelBrochure = get_modelBrochure(vehicleYear, vehicleModel, vehicleTrim);
		$(".article_model_brochure .brochure-pdf").attr("href", modelBrochure);
		} else {
		$(".article_model_brochure .article_container").contents().empty();
		var tooOldError = "We're sorry to say that an online version of your Owner's Manual is not available. Unfortunately, we do not have access to an electronic version of manuals prior to 1998 model year vehicles. Please refer to the Owner's Manual you received with your Subaru at the time of purchase to answer any questions you may have.";
		//$(".article_model_brochure .summary").append(tooOldError);

		
		}
	}//end if article_owner_manual
}

//my owners manual
function my_owners_manual(){
	var article_owner_manual = $(".article_owner_manual").size();
	if (article_owner_manual != 0) {
	if(vehicleYear > 1997){
		var ownersManual = get_ownersManual(vehicleYear, vehicleModel);
		$(".article_owner_manual .brochure-pdf").attr("href", ownersManual);
	} else {
	
		$(".article_owner_manual .article_container").contents().empty();
		var tooOldError = "We're sorry to say that an online version of your Owner's Manual is not available. Unfortunately, we do not have access to an electronic version of manuals prior to 1998 model year vehicles. Please refer to the Owner's Manual you received with your Subaru at the time of purchase to answer any questions you may have.";
		$(".article_owner_manual .summary").append(tooOldError);

	}
	}//end if article_owner_manual
}

//my_partner
function my_partner_tabs(){
	var my_partner_tabs = $("#my_partner_tabs").size();
	if (my_partner_tabs != 0) {
		$("#my_partner_tabs").tabs();
	}
}

// My Poll
function my_poll() {
	var poll_comp = $('.my_poll').size();
	if (poll_comp != 0) {
		// Submit_submit_my_poll
		$('#submit_my_poll').click(function() {
			var formData = $('.my_poll form').serialize();
			$('.form_my_poll').fadeOut("slow", function() {
				$(this).empty();
			});
			$.ajax({
				type: "post",
				dataType: "xml",
				url: linkPrefix+"my-subaru/data/poll/submitanswer",
				data: formData, 
				async: false,
				cache: false,
				success: function(data, textStatus) {
					var resultXML = data;
					var results = '\n<dl class="graph">';
					var totalVotes = 0;
					$(resultXML).find("answer").each(function() {
						var count = $(this).attr("count");
						totalVotes = totalVotes+parseInt(count);
					});
					$(resultXML).find("answer").each(function() {
						var answerId = $(this).attr("id");
						var answer = $(this).text();
						var thisCount = $(this).attr("count");
						var percentage = Math.round((parseInt(thisCount)/totalVotes)*100);
						results += '\n\t<dt class="bar-title">'+answer+'</dt>';
						results += '\n\t\t<dd class="bar-container">';
						results += '\n\t\t\t<div id="bar'+answerId+'" style="width:0%">&nbsp;</div>';
						results += '\n\t\t\t<strong>'+percentage+'%</strong>';
						results += '\n\t\t</dd>';
					});
					results += '\n</dl>';
					results += '\n<p>Total Votes: '+totalVotes+'</p>';
					$('#poll_results').empty().append(results).fadeIn("slow", function() {
						my_poll_animate();
					});
				}
			});
			return false;
		});
	}
}

function my_poll_animate() {
	$("#poll_results div").each(function(){
	      var percentage = $(this).next().text();
	      $(this).css({width: "0%"}).animate({
					width: percentage}, 'slow');
	  });
}

// My Subscriptions
function my_subscriptions() {
	var my_subscriptions = $("#my_subscriptions").size();
	if (my_subscriptions != 0) {
		//var subscriptions = user_subscriptions;
		$(enabled_subscriptions).each(function() {
			var subscriptionId = $(this).attr("subscriptionId");
			$("input[value="+subscriptionId+"]").attr('checked',true);
		});
	}
}

//my_vehicle_recall_detail
function my_vehicle_recall_detail(){
	var my_vehicle_recall_detail = $(".my_vehicle_recall_detail").size();
	if (my_vehicle_recall_detail != 0) {
		// get the recall detail
		var recall_detail = get_recallDetail(vehicle_id);
		// start the "div" table
		var rd = '\n<div class="table_row table_head">';
			rd += '\n\t<div class="col1"><p>Program</p></div>';
			rd += '\n\t<div class="col2"><p>Completed / Open</p></div>';
			rd += '\n\t<div class="col3"><p>Program Title</p></div>';
			rd += '\n\t<div class="clear"> </div>';
			rd += '\n</div>';
		// build each row
		var rowCount = 0;
		$(recall_detail.responseXML).find("recall").each(function(index, thisElement) {
			var row_class = (index%2) ? "" : "odd";
			var program = $(this).find("recallId").text();
			var completedDate = $(this).find("recallCompleteDate").text();
			var completed = (completedDate.length > 0) ? "Completed - "+completedDate : "Open"; 
			var title = $(this).find("recallTile").text();
			var description = $(this).find("recallDescription").text();
			
			rd += '\n<div class="table_row table_cell '+row_class+'">';
			rd += '\n\t<div class="col1"><p><a href="#" rel="detail_'+index+'">'+program+'</a></div>';
			rd += '\n\t<div class="col2"><p>'+completed+'</div>';
			rd += '\n\t<div class="col3"><p>'+title+'</p></div>';
			rd += '\n\t<div id="detail_'+index+'" class="row_detail">';
			if (completed == "Open") {
				rd += '\n\t\t<h3>Service Program Details</h3>';
				rd += '\n\t\t<table>';
				rd += '\n\t\t\t<tr>';
				rd += '\n\t\t\t\t<th>Program Number</th>';
				rd += '\n\t\t\t\t<td>'+program+'</td>';
				rd += '\n\t\t\t</tr>';
				rd += '\n\t\t\t<tr class="odd">';
				rd += '\n\t\t\t\t<th>Year of Recall</th>';
				rd += '\n\t\t\t\t<td></td>';
				rd += '\n\t\t\t</tr>';
				rd += '\n\t\t\t<tr>';
				rd += '\n\t\t\t\t<th>Completed / Open</th>';
				rd += '\n\t\t\t\t<td>This service has not yet been completed.</td>';
				rd += '\n\t\t\t</tr>';
				rd += '\n\t\t\t<tr class="odd">';
				rd += '\n\t\t\t\t<th>Program Title</th>';
				rd += '\n\t\t\t\t<td>'+title+'</td>';
				rd += '\n\t\t\t</tr>';
				rd += '\n\t\t\t<tr>';
				rd += '\n\t\t\t\t<th>Summary</th>';
				rd += '\n\t\t\t\t<td>'+description+'</td>';
				rd += '\n\t\t\t</tr>';
				rd += '\n\t\t</table>';
			} 
			else {
				// get the service record
				$(this).find("serviceRecord").each(function() {
					var serviceRecordId = $(this).find("serviceRecordId").text();
					var serviceDate = $(this).find("serviceDate").text();
					var mileage = $(this).find("mileage").text();
					var repairOrderNumber = $(this).find("repairOrderNumber").text();
					var serviceReason = $(this).find("serviceReason").text();
					var serviceProvider = $(this).find("serviceProvider").text();
					var serviceDescription = $(this).find("serviceDescription").text();
					var dealerId = "";
					var dealerName = "";
					var dealerUrl = "";
					// get dealer info
					$(this).find("dealer").each(function(){
						dealerId = $(this).find("dealerId").text();
						dealerName = $(this).find("dealerName").text();
						dealerUrl = $(this).find("dealerUrl").text();
					});
					rd += '\n\t\t<h3>Service History Details</h3>';
					rd += '\n\t\t<table>';
					rd += '\n\t\t\t<tr>';
					rd += '\n\t\t\t\t<th>Service Provider</th>';
					rd += '\n\t\t\t\t<td><a href="'+dealerUrl+'" target="_blank">'+dealerName+'</a></td>';
					rd += '\n\t\t\t</tr>';
					rd += '\n\t\t\t<tr class="odd">';
					rd += '\n\t\t\t\t<th>Date</th>';
					rd += '\n\t\t\t\t<td>'+serviceDate+'</td>';
					rd += '\n\t\t\t</tr>';
					rd += '\n\t\t\t<tr>';
					rd += '\n\t\t\t\t<th>Mileage</th>';
					rd += '\n\t\t\t\t<td>'+mileage+'</td>';
					rd += '\n\t\t\t</tr>';
					rd += '\n\t\t\t<tr class="odd">';
					rd += '\n\t\t\t\t<th>RO#</th>';
					rd += '\n\t\t\t\t<td>'+repairOrderNumber+'</td>';
					rd += '\n\t\t\t</tr>';
					rd += '\n\t\t\t<tr>';
					rd += '\n\t\t\t\t<th>Reasons for Service</th>';
					rd += '\n\t\t\t\t<td>'+serviceReason+'</td>';
					rd += '\n\t\t\t</tr>';
					rd += '\n\t\t\t<tr class="odd">';
					rd += '\n\t\t\t\t<th>Source</th>';
					rd += '\n\t\t\t\t<td>Manufacturer</td>';
					rd += '\n\t\t\t</tr>';
					rd += '\n\t\t\t<tr>';
					rd += '\n\t\t\t\t<th>Description</th>';
					rd += '\n\t\t\t\t<td>'+serviceDescription+'</td>';
					rd += '\n\t\t\t</tr>';
					rd += '\n\t\t</table>';
				});
			}
			rd += "\n\t</div>";
			rd += '\n\t<div class="clear"> </div>';
			rd += '\n</div>';
			rowCount++;
		});
		
		if (rowCount == 0) {
			rd += '\n<div class="table_row table_cell odd no_content">';
			rd += '\n\t\t<p>Subaru of America has not issued any recalls for your vehicle.</p>';
			rd += '\n</div>';
		}
		
		// append the table
		$('.table_container').empty().append(rd);
		
		$(".table_row .col1 a").livequery('click', function(e) {
			e.preventDefault();
			var detailId = $(this).attr("rel");
			var detailClass = $(this).attr("class");
			
			if (detailClass == "open") {
				$("#"+detailId).slideUp("slow");
				$(this).removeClass("open");
			} else {
				$("#"+detailId).slideDown("slow");
				$(this).addClass("open");
			}
			return false;
		});
	}
}

//my_stories_modal
function my_stories_modal() {
	$(".myStory").click(function() {
		$("#modalOwnerStory").modal({containerId: 'mcOwnerStory'});
		$('#modalOverlay').css({height:($(document).height().toString() + "px"), overflow:"hidden"});
	});
}

//service_alert_close_button
function service_alert_close_button(){
	$(".service_alert .close_button img").livequery("click", function(){
		//vehicleID parent rel
		var alertVehicleId = $(this).parent().attr("rel");
		//maintenceRecordArrayIndex (stored in rel)
		var alertMaintRecIndex = $(this).attr("rel");
			//console.log("vehId= " + alertVehicleId);
			//console.log("Index= " + alertMaintRecIndex);
		var linkToSuppressDealerRecord = linkPrefix + "my-subaru/data/maintenance/suppressdealermaintenancerecord";
		var linkToSuppressMaintRecord = linkPrefix + "my-subaru/data/maintenance/suppressmanufacturermaintenancerecord";
		var linkToSuppressRecallNotice = linkPrefix + "my-subaru/data/maintenance/suppressrecallnotice";
	
		//figure out if we're dealing with a maintenance or dealer service
		if ($(this).hasClass("dealer")){	
			$.ajax({
				type: "POST",
				data: "vehicleId="+alertVehicleId+"&serviceMaintenanceRecordIndex="+alertMaintRecIndex,
				url: linkToSuppressDealerRecord,
				async: true,
				cache: false
			});
		} 
		else if ($(this).hasClass("manufacturer")) {
			$.ajax({
				type: "POST",
				data: "vehicleId="+alertVehicleId+"&serviceMaintenanceRecordIndex="+alertMaintRecIndex,
				url: linkToSuppressMaintRecord,
				async: true,
				cache: false
			});
		}
		else if ($(this).hasClass("recall")) { 
			$.ajax({
				type: "POST",
				data: "vehicleId="+alertVehicleId+"&recallNoticeIndex="+alertMaintRecIndex,
				url: linkToSuppressRecallNotice,
				async: true,
				cache: false
			});
		}
		//make this happen on success
		$(this).parent().parent().parent().hide();
	});	
} // end service_alert_close_button

function submit_gtp_calculator() {
	var vin = jQuery.trim($('#vin').val());
	if ((vin.length == 8 || vin.length == 17) && vin != "Enter VIN - Last 8 or all 17 characters") {
		var formAction = $('#form_check_trade_in_value').attr("action");
		var redirectURL = formAction+vin;
		window.location.assign(redirectURL);
	}
	else {
		$('input#vin').val("Enter VIN - Last 8 or all 17 characters");
	}
}

// submit_trade_in_button
function submit_trade_in_button(){
	var check_trade_in_value = $('.check_trade_in_value').size();
	if (check_trade_in_value != 0) {
		// Input_instruct_VIN
		$('input#vin').focus(function() {
			// clear the input field
			$(this).val("");
		}).blur(function() {
			var inputValue = jQuery.trim($(this).val());
			if (inputValue.length == 8 || inputValue.length == 17 ) {
				// don't do anything
			} 
			else {
				$(this).val("Enter VIN - Last 8 or all 17 characters");
			}
		}).keypress(function(e) {
			if (e.which == 13) {
				e.preventDefault();
				submit_gtp_calculator();
				return false;
			}
		});
		
		// submit_trade_in
		$('#submit_trade_in').click(function(e) {
			e.preventDefault();
			submit_gtp_calculator();
			return false;
		});
	}
}

// Vin Lookup
function vin_lookup(vin) {
	var vinInfo = $.ajax({
		type: "POST",
		data: "vin="+vin,
		url: linkPrefix+'my-subaru/data/vehicle/salesinfo/',
		async: false,
		cache: false
	});
	return vinInfo;
}

