$('#contactInfo').css("display", "block");

var modelId = getURLParam("modelId");
// may not need this anymore
$('form[name=getBrochureForm] :checkbox').removeAttr('checked');
// do not need it since adding modelid when contact me is checked.
/*if( modelId != "" ) { 
	$('form[name=getBrochureForm] :checkbox[value='+modelId+']').attr('checked', true); 
}
*/
if ($('input[name=contactMe]:checked').val() != 'Y' ) {
	$('#selectModel').hide();
}
if ($('input[name=contactMe]:checked').val() == 'N' ) {
	if( modelId != "" ) { 
		$('form[name=getBrochureForm] :checkbox[value='+modelId+']').attr('checked', true); 
		$('#modelIdOfInterest').val(modelId);
	}
	else {
		$('form[name=getBrochureForm] :checkbox[value='+$('#modelIdOfInterest option:selected').val()+']').attr('checked', true);
		$('#modelIdOfInterest').val($('#modelIdOfInterest option:selected').val());
	}
}

var groupedFields = {};
var localBinding = {
		'contactInfoForm' : {
	        'contactMe' : {'validate' : {validateRadio : {}}, 'onSuccess' : {radioValidateLocal: {}}, 'onFailure' : {radioValidateLocal: {'message' : 'Sorry, please indicate if you would like to be contacted by a dealer.'}}},
	        'full-line' : {'validate' : {validateRadio : {}}, 'onSuccess' : {radioValidateLocal: {}}, 'onFailure' : {radioValidateLocal: {'message' : 'Sorry, you must select a brochure to download.'}}},
	        'futureInfo' : {'validate' : {validateRadio : {}}, 'onSuccess' : {radioValidateLocal: {}}, 'onFailure' : {radioValidateLocal: {'message' : 'Sorry, please indicate if you would like to receive Mitsubishi news and offers.'}}},
			'city' : {'validate' : {validateMinLength : {'minLength' : 1}}, 'onSuccess' : {genericValidate: {}}, 'onFailure' : {genericValidate: {'message' : 'Sorry, the city name you entered is not a valid city name. Please check the spelling and try again.'}}},
			'state' : {'validate' : {validateDropdown : {}}, 'onSuccess' : {genericValidate: {}}, 'onFailure' : {genericValidate: {'message' : 'Sorry, you must select a state.'}}},
	        'preValidate' : contactInfoPreValidate,
			'onValidate' : {contactInfoSubmit : {}},
			'onValidationFail' : {defaultFailure : {}}			
		},
		'emailSignupForm' : {
			'onValidate' : {emailSignupSubmit : {}},
			'onValidationFail' : {defaultFailure : {}}
		}
	};

$(document).ready (function () {
	if ($('input[name=contactMethod]').val() == 'Y') {
		$('#contactMe-Yes').attr('checked', true);
		displaySelectModel ();
	}

    $('input[name=contactMethod]').click ( function () {
    	$('#contactMe-Yes').attr('checked', true);
    	displaySelectModel ();
    });

    /* download button */
    $('.downloadPDF').click ( function () {
    	// make sure we have a valid selection, otherwise alert
    	if ($('#PDFSelect').val() != '-1') {
    		//surveyRequest ('kpi', 'ob');
    		//Capture omniture details
    		omnitureForDownload();
    		// do the window opening
    		$('#downloadFailure').css('visibility', 'hidden');
    		// dart
    		var axel = Math.random() + "";
    		var a = axel * 10000000000000;
    		$('#contactInfo').prepend('<iframe src="http://fls.doubleclick.net/activityi;src=1033846;type=broch659;cat=broch596;ord=' + a + '?" width="1" height="1" frameborder="0"></iframe>');
    		window.open($('#PDFSelect').val());
    	} else {
    		// do an on-page message
    		$('#downloadFailure').css('visibility', 'visible');
    	}
    	
    });
    
    /* on change to hide message */
    $('#PDFSelect').change( function () {
    	$('#downloadFailure').css('visibility', 'hidden');
    });
});

/*
function getBrochureSubmit (obj) {

	var formData = $('form[name=getBrochureForm]').serialize();

	// if anything is checked, process the form
	if( $('form[name=getBrochureForm] :checked').length > 0 ) {
		
			$('#getBrochure').hide();
			
			var checked2010s = false;
			var checked2011s = false;
			$('form[name=getBrochureForm] input:checkbox').each( function(i){
				if( $(this).attr('checked') == true ) { 
					if ( $(this).attr('name') == "2010s" ) { checked2010s=true; };
					if ( $(this).attr('name') == "2011s" ) { checked2011s=true; };
					}
			});
			
			// if any downloadable brochure is requested, do the download
			if( checked2010s || checked2011s ) {
				
				alert("doing download"); // do the pdf download 
				$.post("/MMNA/brochure.do", formData ,function(respData) {				
					if( respData.indexOf("Success") > -1 ) 
					{
						//window.location= '/MMNA/jsp/dealerprospectus/index.do'; this is dealer prospectus code for example only
						alert("server call success")
					} else {
						alert("server call failed");
					}
				});
				
				// if full line is also requested go to the contact form page
				if( $("#2009-full-line").attr('checked')==true || $("#2010-full-line").attr('checked')==true ) {
					$('#contactInfo').show();
					
				// otherwise go to the completion page
				} else {
					showDownloadCompletionPage()
				}
				
			// otherwise by elimination we know a full line was requested, go to the contact page
			} else {
				$('#contactInfo').show();
			}
	
	// otherwise show validation error	
	} else {
		// add invalid field message here
		alert("you have to pick something")
	}
 
	return false;
}
*/
function emailSignupSubmit (obj) {
	// not being used, but left in for possible future use
	// if used, verify the post target URL
	var formData = $('form[name=emailSignupForm]').serialize();
	//alert("formData: "+formData);
	
	$('#anotherBrochure').hide(); 
	$('#emailSignup').hide();	
	$('#emailThankYou').show();	
	
	$.post("/MMNA/newsletterSubscription.do", formData ,function(respData) {	
		if( respData.indexOf("Success") > -1 ) 
		{
			//window.location= '/MMNA/jsp/dealerprospectus/index.do'; this is dealer prospectus code for example only
			
			$('#anotherBrochure').hide(); 
			$('#emailSignup').hide();	
			$('#emailThankYou').show();	
		} else {
		}
	});
	
	return false;
	
}

function contactInfoPreValidate () {
	// this would be a good reason to define a way to 'rebind' values on the fly
	// also applies to groups... this basically pre-empts the binding variables and manipulates data() directly.
	// better solution would be to create an object that has methods to conditional bind stuff.
	$('#downloadFailure').hide();
	genericClear({source: $('#contactInfoForm input[name=contactMethod]')});
	
	if (($('input[name=contactMe]:checked').val() == 'Y')) {
		$('#contactInfoForm input[name=contactMethod]').data('validate', {validateRadio: {}});
		$('#contactInfoForm input[name=contactMethod]').data('onSuccess', {radioValidateLocal: {}});
		$('#contactInfoForm input[name=contactMethod]').data('onFailure', {radioValidateLocal: {'message' : 'Sorry, you must select a contact method.'}});
    } else {
    	$('#contactInfoForm input[name=contactMethod]').removeData('validate');
    	$('#contactInfoForm input[name=contactMethod]').removeData('onSuccess');
    	$('#contactInfoForm input[name=contactMethod]').removeData('onFailure');
    }

	if (($('input[name=contactMe]:checked').val() != 'Y') && (modelId =="" || modelId=="0")) {
		$('#modelIdOfInterest option:selected').val('0');
		$('#modelIdOfInterest').data('validate', {validateAlwaysTrue: {}});
	}
	if (($('input[name=contactMe]:checked').val() == 'Y') && (modelId =="" || modelId=="0")) {
		$('form[name=getBrochureForm] :checkbox[value='+$('#modelIdOfInterest option:selected').val()+']').attr('checked', true); 		
	}
	
	var phoneTrue = new Array('phoneAreaCode', 'phonePrefix', 'phoneSuffix');
	if (($('input[name=contactMe]:checked').val() == 'Y') && ($('#contactMethod-phone').attr('checked'))) {
		// require phone
		$.each(phoneTrue, function () {				
			$('#contactInfoForm input[name=' + this + ']').data('validate', globalBinding[this].validate);
			$('#contactInfoForm').data('groups')['phone'].onSuccess = globalBinding[this].onSuccess;				
		});
	} else {
		// resetting phone requirement
		$.each(phoneTrue, function () {				
			$('#contactInfoForm input[name=' + this + ']').data('validate', {validateAlwaysTrue: {}});
			$('#contactInfoForm').data('groups')['phone'].onSuccess = {obfuscateValidate: {}};
		});	
	}
	
	var smsTrue = new Array('secondaryPhoneAreaCode', 'secondaryPhonePrefix', 'secondaryPhoneSuffix');
	if ($("input[name='secondaryPhoneAreaCode']").val().length > 0) {
		$('#secondarySms').val('1');
		// require phone
		$.each(smsTrue, function () {				
			$('#contactInfoForm input[name=' + this + ']').data('validate', globalBinding[this].validate);
			$('#contactInfoForm').data('groups')['phoneSMS'].onSuccess = globalBinding[this].onSuccess;				
		});
	} else {
		$('#secondarySms').val('0');
		// resetting phone requirement
		$.each(smsTrue, function () {				
			$("#contactInfoForm input[name='" + this + "']").data('validate', {validateAlwaysTrue: {}});
			$("#contactInfoForm").data('groups')['phoneSMS'].onSuccess = {obfuscateValidate: {}};
		});	
	}
}

function contactInfoSubmit (obj) {
	//Omniture tracking.
	omnitureForSubmit();
	// if no for contactMe, then get ModelId from URL; otherwise get it from select model.
	if ($('input[name=contactMe]:checked').val() == 'N') { 
		$.each(location.search.split('&'), function (idx, value) {
		// attach model id if it exists
			if (value.search ('modelId') != -1) {
				$('#modelIdOfInterest').val(value.split('=')[1]);
				return false;			    
			}
		});
	}
	var formData = '';
	var brochureList = Array ();
	
	$('input[name=full-line]:checked').each ( function () {
	    brochureList.push ($(this).val());		   
	});
	
	var phoneVal = '(' + $('#phoneAreaCode').val() + ')' +$('#phonePrefix').val() + '-' + $('#phoneSuffix').val();
    
	$('#requestedBrochure').val ( brochureList.join(',') );
    
	formData = $('form[name=contactInfoForm]').serialize() + "&phone="+phoneVal; // + "&phoneAreaCode=" + $('#phoneAreaCode').val();
	$.post("/MMNA/brochure.do", formData , function(respData) {	
		
		eval (respData)
		
		if (success) {
			// dart tags
			var axel = Math.random()+"";
			var a = axel * 10000000000000;	
			/* one of these tags looks wrong. look at "ord" values. seems like "num" should be the phone number, and "ord" the random, but it's not being used that way
			if (($('#phoneAreaCode').val().length) && ($('#phonePrefix').val().length) && ($('#phoneSuffix').val().length)) {
				$('#anotherBrochure').prepend('<IFRAME SRC="http://fls.doubleclick.net/activityi;src=1033846;type=broch659;cat=broch687;ord=1;num='+ a + '?" WIDTH=1 HEIGHT=1 FRAMEBORDER=0></IFRAME>');
			} else {
				$('#anotherBrochure').prepend('<IFRAME SRC="http://fls.doubleclick.net/activityi;src=1033846;type=broch659;cat=broch684;ord='+ a + '?" WIDTH=1 HEIGHT=1 FRAMEBORDER=0></IFRAME>');
			}
			*/
            // doubleclick tagging 4.4.2011
			$('#anotherBrochure').prepend('<iframe src="http://fls.doubleclick.net/activityi;src=1033846;type=fy11d301;cat=fy11d452;ord=1?" width="1" height="1" frameborder="0" style="display:none"></iframe>');
			
			
			if ($('input[name=futureInfo]:checked').val() == 'Y') {
				var zipFix = "&zip=" + $('#zipCode').val();
				// avoids dupe e-leads
				$('form[name=contactInfoForm]').find('input[name=contactMe]').val('N');
				formData = $('form[name=contactInfoForm]').serialize() + "&phone="+phoneVal; // + "&phoneAreaCode=" + $('#phoneArea').val();
			    //$.post("/MMNA/newsletterSubscription.do?action=newsletter", formData + zipFix);
				$.post("/MMNA/news.do?action=newsletter", formData + zipFix);
			}
	
			showFullLineCompletionPage();
			//surveyRequest ('kpi', 'ob');
		} else {
			// failed
			$('.errorMessageStack span').eq(0).html(message);
			$('.errorMessageStack').eq(0).show();
		}
	});
	
	return false;
	
}

/*
function showDownloadCompletionPage() {
	$('#anotherBrochure').show();
	$('#emailSignup').show();	
	$('form[name=anotherBrochureForm] :checkbox').removeAttr('checked');
	$('form[name=getBrochureForm] :checked').each(function(){
		var id  = $(this).attr('id');
		$('form[name=anotherBrochureForm] :checkbox[id='+id+']').attr('disabled', 'disabled');
		$('label[for='+id+']').after(" <span style='font-size:9px; color:#ED1C24;'>(downloaded)</span>");
	});	
}
*/
function showFullLineCompletionPage() {
	$('#contactInfo').hide();	
	$('#full-lineThankYou').show();
	$('#anotherBrochure').show();
	$('form[name=anotherBrochureForm] :checkbox').removeAttr('checked');
	$('form[name=getBrochureForm] :checked').each(function(){
		var id  = $(this).attr('id');
		$('form[name=anotherBrochureForm] :checkbox[id='+id+']').attr('disabled', 'disabled');
		$('label[for='+id+']').after(" <span style='font-size:9px; color:#ED1C24;'>(downloaded)</span>");
	});
	
	//Omniture tracking
	var brochureYear = "";
	var brochureType ="";


	if (($('#2010-full-line').attr('checked')) && ($('#2011-full-line').attr('checked')) && ($('#2011-lancer-family').attr('checked')) && ($('#2011-outlander-family').attr('checked'))) {
		brochureYear = "2010-2011";
		brochureType="2010-2011-Full-2011LancerFamily-2011OutlanderFamily"
	}
	else if (($('#2010-full-line').attr('checked')) && ($('#2011-full-line').attr('checked')) && ($('#2011-lancer-family').attr('checked'))) {
		brochureYear = "2010-2011";
		brochureType="2010-2011-Full-2011LanderFamily"
	}
	else if (($('#2010-full-line').attr('checked')) && ($('#2011-full-line').attr('checked')) && ($('#2011-outlander-family').attr('checked'))) {
		brochureYear = "2010-2011";
		brochureType="2010-2011-Full-2011OutlanderFamily"
	}
	else if (($('#2010-full-line').attr('checked')) && ($('#2011-lancer-family').attr('checked')) && ($('#2011-outlander-family').attr('checked'))) {
		brochureYear = "2010-2011";
		brochureType="2010-Full-2011LanderFamily-2011OutlanderFamily"
	}
	else if (($('#2010-full-line').attr('checked')) && ($('#2011-outlander-family').attr('checked'))) {
		brochureYear = "2010-2011";
		brochureType="2010-Full-2011OutlanderFamily"
	}
	else if (($('#2010-full-line').attr('checked')) && ($('#2011-lancer-family').attr('checked'))) {
		brochureYear = "2010-2011";
		brochureType="2010-Full-2011LanderFamily"
	}
	else if (($('#2010-full-line').attr('checked')) && ($('#2011-full-line').attr('checked'))) {
		brochureYear = "2010-2011";
		brochureType="2010-2011-Full"
	}
	else if (($('#2011-full-line').attr('checked')) && ($('#2011-lancer-family').attr('checked')) && ($('#2011-outlander-family').attr('checked'))) {
		brochureYear = "2011";
		brochureType="2011-Full-2011LanderFamily-2011OutlanderFamily"
	}
	else if (($('#2011-full-line').attr('checked')) && ($('#2011-lancer-family').attr('checked'))) {
		brochureYear = "2011";
		brochureType="2011-Full-2011LanderFamily"
	}
	else if (($('#2011-full-line').attr('checked')) && ($('#2011-outlander-family').attr('checked'))) {
		brochureYear = "2011";
		brochureType="2011-Full-2011OutlanderFamily"
	}
	else if (($('#2011-lancer-family').attr('checked')) && ($('#2011-outlander-family').attr('checked'))) {
		brochureYear = "2011";
		brochureType="2011LanderFamily-2011OutlanderFamily"
	}
	else if ($('#2011-lancer-family').attr('checked')) {
		brochureYear = "2011";
		brochureType="2011LanderFamily"
	}
	else if ($('#2011-outlander-family').attr('checked')) {
		brochureYear = "2011";
		brochureType="2011OutlanderFamily"
	}
	else if ($('#2011-full-line').attr('checked')) {
		brochureYear = "2011";
		brochureType="2011-Full"
	}
	else if ($('#2010-full-line').attr('checked')) {
		brochureYear = "2010";
		brochureType="2010-Full"
	}

	var page_Name = "mc:vehicle:shop:get-brochure:" + brochureType + "-form:complete";
	var product_String = "get-brochure;" + brochureType + "-form;1;";
	bubbleSequentialEvent(" var variables = [{name: 'server', value: 'Mitsubishi Cars'}, {name: 'channel', value: 'vehicle'}, {name: 'pageName', value: '" + page_Name + "'}, {name: 'eVar1', value: '" + brochureYear + "'}, {name: 'eVar12', value: '" + page_Name + "'}, {name: 'eVar32', value: ''}, {name: 'prop1', value: '" + brochureYear + "'}, {name: 'prop14', value: ''}, {name: 'prop19', value: '" + page_Name + "'}, {name: 'prop20', value: 'shop'}, {name: 'prop21', value: 'get-brochure'}, {name: 'events', value: 'event3,event16,purchase'}, {name: 'purchaseID', value: '" + transactionId + "'}, {name: 'products', value: '" + product_String + "'}]");
}


function defaultFailure(obj) {
	return false;
}

function gotToURLmodelId (url) {
	window.location = url;
}

function omnitureForSubmit() {
	var brochureYear = "";
	var brochureType ="";

	if (($('#2010-full-line').attr('checked')) && ($('#2011-full-line').attr('checked')) && ($('#2011-lancer-family').attr('checked')) && ($('#2011-outlander-family').attr('checked'))) {
		brochureYear = "2010-2011";
		brochureType="2010-2011-Full-2011LancerFamily-2011OutlanderFamily"
	}
	else if (($('#2010-full-line').attr('checked')) && ($('#2011-full-line').attr('checked')) && ($('#2011-lancer-family').attr('checked'))) {
		brochureYear = "2010-2011";
		brochureType="2010-2011-Full-2011LanderFamily"
	}
	else if (($('#2010-full-line').attr('checked')) && ($('#2011-full-line').attr('checked')) && ($('#2011-outlander-family').attr('checked'))) {
		brochureYear = "2010-2011";
		brochureType="2010-2011-Full-2011OutlanderFamily"
	}
	else if (($('#2010-full-line').attr('checked')) && ($('#2011-lancer-family').attr('checked')) && ($('#2011-outlander-family').attr('checked'))) {
		brochureYear = "2010-2011";
		brochureType="2010-Full-2011LanderFamily-2011OutlanderFamily"
	}
	else if (($('#2010-full-line').attr('checked')) && ($('#2011-outlander-family').attr('checked'))) {
		brochureYear = "2010-2011";
		brochureType="2010-Full-2011OutlanderFamily"
	}
	else if (($('#2010-full-line').attr('checked')) && ($('#2011-lancer-family').attr('checked'))) {
		brochureYear = "2010-2011";
		brochureType="2010-Full-2011LanderFamily"
	}
	else if (($('#2010-full-line').attr('checked')) && ($('#2011-full-line').attr('checked'))) {
		brochureYear = "2010-2011";
		brochureType="2010-2011-Full"
	}
	else if (($('#2011-full-line').attr('checked')) && ($('#2011-lancer-family').attr('checked')) && ($('#2011-outlander-family').attr('checked'))) {
		brochureYear = "2011";
		brochureType="2011-Full-2011LanderFamily-2011OutlanderFamily"
	}
	else if (($('#2011-full-line').attr('checked')) && ($('#2011-lancer-family').attr('checked'))) {
		brochureYear = "2011";
		brochureType="2011-Full-2011LanderFamily"
	}
	else if (($('#2011-full-line').attr('checked')) && ($('#2011-outlander-family').attr('checked'))) {
		brochureYear = "2011";
		brochureType="2011-Full-2011OutlanderFamily"
	}
	else if (($('#2011-lancer-family').attr('checked')) && ($('#2011-outlander-family').attr('checked'))) {
		brochureYear = "2011";
		brochureType="2011LanderFamily-2011OutlanderFamily"
	}
	else if ($('#2011-lancer-family').attr('checked')) {
		brochureYear = "2011";
		brochureType="2011LanderFamily"
	}
	else if ($('#2011-outlander-family').attr('checked')) {
		brochureYear = "2011";
		brochureType="2011OutlanderFamily"
	}
	else if ($('#2011-full-line').attr('checked')) {
		brochureYear = "2011";
		brochureType="2011-Full"
	}
	else if ($('#2010-full-line').attr('checked')) {
		brochureYear = "2010";
		brochureType="2010-Full"
	}

	var page_Name = "mc:vehicle:shop:get-brochure:" + brochureType + "-form";
	bubbleSequentialEvent(" var variables = [{name: 'server', value: 'Mitsubishi Cars'}, {name: 'channel', value: 'vehicle'}, {name: 'pageName', value: '" + page_Name + "'}, {name: 'eVar1', value: '" + brochureYear + "'}, {name: 'eVar12', value: '" + page_Name + "'}, {name: 'eVar32', value: ''}, {name: 'prop1', value: '" + brochureYear + "'}, {name: 'prop14', value: ''}, {name: 'prop19', value: '" + page_Name + "'}, {name: 'prop20', value: 'shop'}, {name: 'prop21', value: 'get-brochure'}, {name: 'events', value: ''}]");

}

function omnitureForDownload() {
	var pdf_select = "";
	pdf_select = $('#PDFSelect option:selected').text();
	
	//For some reason the selected model text is being set as eg. 2011 EclipseSelect a Model. Remove the unwanted text.
	pdf_select = pdf_select.replace("Select a Model", "");
	pdf_select = $.trim(pdf_select);
	pdf_select = pdf_select.toLowerCase();
	bubbleSequentialEvent(" var variables = [{name: 'server', value: 'Mitsubishi Cars'}, {name: 'channel', value: 'vehicle'}, {name: 'pageName', value: 'mc:vehicle:shop:get-brochure:download'}, {name: 'eVar1', value: ''}, {name: 'eVar12', value: 'mc:vehicle:shop:get-brochure:download'}, {name: 'eVar32', value: '" + pdf_select + "'}, {name: 'prop1', value: ''}, {name: 'prop14', value: '" + pdf_select + "'}, {name: 'prop19', value: 'mc:vehicle:shop:get-brochure:download'}, {name: 'prop20', value: 'shop'}, {name: 'prop21', value: 'get-brochure'}, {name: 'events', value: 'event3,event16'}]");
}

function displaySelectModel () {
	$('#selectModel').show();
}

// when select model is displayed.
function setModelId () {
	$('form[name=getBrochureForm] :checkbox[value='+$('#modelIdOfInterest option:selected').val()+']').attr('checked', true); 
}

function setModelDefault() {
	$('#selectModel').hide();

	$.each(location.search.split('&'), function (idx, value) {
		// attach model id if it exists
			if (value.search ('modelId') != -1) {
				$('#modelIdOfInterest').val(value.split('=')[1]);
			}
			else {
				modelId = "0"; 
			}
		});
	$('form[name=getBrochureForm] :checkbox[value='+modelId+']').attr('checked', true); 
	$('#modelIdOfInterest').val(modelId);
   	$('#contactMethod-email').attr('checked', false);
   	$('#contactMethod-phone').attr('checked', false);
 }

