﻿/**
* @author Wayne Parkes
*/
document.writeln('<meta http-equiv="pragma" content="no-cache">');
document.writeln('<style type="text/css">.brochureDownload li { display: none; }</style>');

$(function() {
	setup.init();
});

var setup = {
	init: function() {
		formFocus();
		brochures.init();
		modelSummary.init();
		modelSelector.init();
		colourOpeningTimeRows();
		//resultsHandler.init('Show more');
		validationHandler();
		submitOnEnter();
		adjustFormHeight();
	}
};

var formFocus = function() {
	$('input[type="text"]:not(#mapDiv input):visible:first').focus();
};

var brochures = {
  parentElem: '.brochureDownload',
  hide: function() {
    $('li', this.parentElem).hide();
    $('h3', this.parentElem).hide();
    $(this.parentElem).css({ 'padding-bottom': '0px', 'padding-top': '0px' });
  },
  show: function(model) {
    var m = model.key.toLowerCase() || false;
    if (m) {
      var matchedElems = $('a[rel="' + m + '"]', this.parentElem);
      if (matchedElems.length) {
        $(this.parentElem).css({ 'padding-bottom': '14px', 'padding-top': '14px' });
        $('h3', this.parentElem).show();
        matchedElems.parent().show();
        
        // for fr-FR
        if ($('.showFormText').length) {
        	//$('.showFormText').css('padding-top', '1em');
        	if ($('.ie6, .ie7').length) $(this.parentElem).addClass('iePaddingFix');
        }
      }
    }
  },
  track: function(el, m) {
    var pdfurlparts = el.attr('href').split('/'),
		pdfname = pdfurlparts[pdfurlparts.length - 1];
    if (pageurl != null) tc_log(pageurl + m + '/' + pdfname);
  },
  delegate: function(data) {
    this.hide();
    if (typeof (data) == 'object') {
      for (i in data) {
        this.show(data[i]);
      }
    }
  },
  showForm: function() {
  	$('.hideForm').slideDown(function() {
  		$('.showFormText').slideUp(function() {
  			$(this).remove();
  			if ($('.ie6, .ie7').length) $(brochures.parentElem).removeClass('iePaddingFix');
  		});
  	});
  },
  init: function() {
    if ($(this.parentElem).length > 0) this.delegate(model); // model in this context is set by .net as a global variable
    $('.brochureDownload a.pdf').click(function() {
      brochures.track($(this), $(this).attr('rel'));
    });
    
    // for fr-FR
    if ($('.fr-FR .BrochureDownload').length) {
    	$(this.parentElem).nextAll('.formRow').wrapAll('<div class="hideForm" style="display:none" />');
    	$('.formAction').wrap('<div class="hideForm" style="display:none" />');
    	$(this.parentElem).append('<p class="showFormText" style="color:#000;font-size:1em;margin-bottom:0">Vous souhaitez en savoir plus sur nos modèles les plus récents et l’actualité de la marque Mazda ? Vous voulez être le premier à tout savoir? <a href="#showForm" onclick="brochures.showForm(); return false;">cliquez ici</a>.</p>');
    }

    // Brochure download tracking for pt-PT
    if ($('.pt-PT .brochureDownload').length) {
        $('a.pdf').click(function() {
            var trackingImg = new Image(),
				model = $(this).attr('rel');
			
            trackingImg.src = 'https://eu.link.decdna.net/n/71191/71204/MAZDOWNBRO/x/e?value=0&trans=&domain=eu.link.decdna.net&model=' + model;
        });
    }
  }
};

var modelSummary = {
	parentElem: '.modelSummary',
	modelCount: 0,
	modelArray: [],
	empty: function() {
		$('.choices', this.parentElem).empty();
	},
	show: function(modelArray) {
		
		var html = '',
			defaultPath = window.location.protocol+'//'+window.location.host+'/images/summary/models/',
			imagePath;
			
		for (i in modelArray) {
			if (typeof(modelArray[i].url) != 'undefined') {
				imagePath = modelArray[i].url.replace('model_selector', 'summary');
			} else {
				imagePath = defaultPath + modelArray[i].key + '.jpg';
			}
			html += '<div><p>' + modelArray[i].value + '</p><img src="' + imagePath + '" /></div>';
		}
		
		$('.choices', this.parentElem).append(html);
		
		if ($(this.parentElem).is(':hidden')) $(this.parentElem).fadeIn(300);
	},
	getImage: function(model, modelLength) {
		var m = model.key.toLowerCase() || false;
		if (m) {
			
			var mrkt = $('form').attr('class').substring(3),
				subClasses = $('.formwizard').attr('class').split(' '),
				subType = subClasses[subClasses.length - 1],
				mrktImage = new Image(),
				defaultImage = new Image(),
				submissionTypeImage = new Image(),
				imagePath = window.location.protocol+'//'+window.location.host+'/images/summary/models/',
				summaryImageSrc;
			
			submissionTypeImage.src = imagePath + mrkt + '/' + subType + '/' + m + '.jpg';
			
			if (mrkt != 'AT') mrktImage.src = imagePath + mrkt + '/' + m + '.jpg';
			
			defaultImage.src = imagePath + m + '.jpg';
			
			window.setTimeout(function() {
				if (submissionTypeImage.width == 80) {
					// check to see if a submission type specific image exists before falling back to using a market specific or default image
					summaryImageSrc = submissionTypeImage.src;
				} else {
					// check to see if a market specific image exists before using a default image
					summaryImageSrc = (mrktImage.width == 80) ? mrktImage.src : defaultImage.src;
				}
				
				modelSummary.modelCount += 1;
				modelSummary.modelArray.push({ name:model.value, src:summaryImageSrc });
				
				if (modelSummary.modelCount === modelLength) modelSummary.show(modelSummary.modelArray);
				
			}, 100);
		}
	},
	delegate: function(data) {
		this.empty();
		if (typeof(data) == 'object' && data.length) {
			// by-pass getImage function
			this.show(data);
			
			//modelSummary.modelCount = 0;
			//modelSummary.modelArray = [];
			//for (i in data) {
				//this.getImage(data[i], data.length);
			//}
		}
	},
	init: function() {
		if ($(this.parentElem).length > 0) {
			this.delegate(model); // model in this context is set by .net as a global variable
			
			if ($(modelSelector.parentElem).length == 0) $('.change', this.parentElem).show(); // shows the change model link on subsequent pages
		}
	}
};

var modelSelector = {
	required: true,
	maxmodels: 3,
	parentElem: '.visualModelSelector',
	timer: null,
	countChecked: function(currentElem) {
		var that = this,
			elem = currentElem || false,
			checkedElems = $(':checkbox:checked, :radio:checked', that.parentElem),
			n = checkedElems.length,
			errorMsg = $('.validation_msg', that.parentElem);
		
		if (n == 0) $(modelSummary.parentElem).hide(); // hide the summary panel if no models are selected
		
		if (that.required && (n == 0 || n > that.maxmodels)) {
			if (that.timer !== null) clearTimeout(that.timer);
			if (elem) {
				elem.attr('checked', ''); // uncheck last selected elem
				errorMsg.slideDown(300, function() {
					that.timer = setTimeout(function() {
						errorMsg.slideUp(300);
					}, 3000);
				});
			} else checkedElems.attr('checked', ''); // uncheck all selected elems
			if (n == 0) {
				if ($(brochures.parentElem).length > 0) brochures.delegate([]);
				if ($(modelSummary.parentElem).length > 0) modelSummary.delegate([]);
			}
		} else {
			errorMsg.slideUp(300);
			var models = [];
			checkedElems.each(function() {
				var modelSpan = $('span', $(this).parent()),
					modelImageUrl = $('img', $(this).parent()).attr('src');
				models.push({ key: modelSpan.attr('rel'), value: modelSpan.text(), url: modelImageUrl });
			});
			// update brochure control with selected model
			if ($(brochures.parentElem).length > 0) brochures.delegate(models);
			// update summary control with selected model
			if ($(modelSummary.parentElem).length > 0) modelSummary.delegate(models);
		}
	},
	adjustRowHeights: function() {
		var rowCount = 0,
			colCount = 0,
			maxHeight = 0,
			relArray = [];
		
		$('label span', this.parentElem).each(function() {
			colCount += 1;
			$(this).parents('li').attr('rel', 'row_'+rowCount);
			if (colCount == 4) {
				colCount = 0;
				rowCount += 1;
			}
			if ($(this).height() > 15) {
				var listElem = $(this).parents('li');
				if ($.inArray(listElem.attr('rel'), relArray) == -1) relArray.push(listElem.attr('rel'));
				if (listElem.height() > maxHeight) maxHeight = listElem.height();
			}
		});
		
		// Add more LI elems to make up for the shortfall
		if (colCount > 0) {
			var lastRel = $('li:last', this.parentElem).attr('rel');
			while (colCount < 4) {
				$('ul', this.parentElem).append('<li rel="'+lastRel+'"></li>');
				colCount += 1;
			}
		}
		
		// Apply height adjustment
		if (relArray.length) {
			for (i in relArray) {
				$('li[rel="'+relArray[i]+'"]', this.parentElem).height(maxHeight);
			}
		}
	},
	init: function() {
		var that = this;
		if ($(that.parentElem).length > 0) {
			that.countChecked();
			$(':checkbox, :radio', that.parentElem).click(function() {
				$(this).blur();
				that.countChecked($(this));
			});
			that.adjustRowHeights();
		}
	}
};

var dealers = {
	initZoomLevel: null,
	locatorField: '.selected_dealer',
	parentElem: '.dealerLocator .results',
	listElems: '.dealerLocator .results .dealer_result',
	check: function(id, radio, li) {
		//console.log('id: %o\nradio: %o\nli: %o', id, radio, li);
		$(this.locatorField).val(id);
		$('.selected').removeClass('selected');
		$(radio).attr('checked', 'checked');
		$(li).addClass('selected');
		//if (!$(this.parentElem).length > 0) $('.primary input').click();
	},
	select: function(id) {
		var radio = $(this.listElems).find('input[value="' + id + '"]');
		var li = $(radio).parents('li');
		dealers.check(id, radio, li);
	},
	showOnMap: function(id) {
		var marker = $('img.dealerIcon[rel="' + id + '"]', '#mapDiv');
		
		if (marker.length) {
			marker.parents('div:eq(0)').mouseover();
		} else {
			if (this.initZoomLevel === null) this.initZoomLevel = mazdaDealersMap.map.GetZoomLevel();
			mazdaDealersMap.map.SetZoomLevel(this.initZoomLevel);
			
			var unclusterMarkers = function() {
				var clusteredArray = mazdaDealersMap.dataLayer.GetClusteredShapes(VEClusteringType.Grid) || [];
				
				var unclusterShape = function() {
					nextZoomLevel = currZoomLevel++;
					
					window.setTimeout(function() {
						mazdaDealersMap.map.SetCenterAndZoom(new VELatLong(cLat, cLon), nextZoomLevel);
						
						//console.log('marker length: %o', $('img.dealerIcon[rel="' + id + '"]', '#mapDiv').length);
						var pinQuery = 'img.dealerIcon[rel="' + id + '"]';
						if (nextZoomLevel < 21 && $(pinQuery, '#mapDiv').length == 0) {
							unclusterShape();
						} else {
							if ($(pinQuery, '#mapDiv').length) {
								//console.log('clustered shape has been unclustered at zoom level: %o', mazdaDealersMap.map.GetZoomLevel());
								window.setTimeout(function() {
									$(pinQuery, '#mapDiv').parents('div:eq(0)').mouseover(); // trigger map pop-up
								}, 100);
							} else {
								//console.log('Duplicate location!');
								//console.log(clusteredShape);
							}
						}
					}, 100);
				};
				
				if (clusteredArray.length) {
					var clusteredShape,
						currZoomLevel = mazdaDealersMap.map.GetZoomLevel(),
						nextZoomLevel;
					
					// Loop thru each cluster object in the array...
					for (var clusterObj in clusteredArray) {
						// ...and loop thru each array of shapes within each object
						for (var shape in clusteredArray[clusterObj].Shapes) {
							// jQuerify each icon until we get a match
							if ($(clusteredArray[clusterObj].Shapes[shape]._customIcon).attr('rel') == id) {
								clusteredShape = clusteredArray[clusterObj].Shapes[shape];
							}
						}
					}
					
					if (clusteredShape === undefined) {
						window.setTimeout(function() {
							$('img.dealerIcon[rel="' + id + '"]', '#mapDiv').parents('div:eq(0)').mouseover(); // trigger map pop-up
						}, 100);
					} else {
						var cLat = clusteredShape.Latitude,
							cLon = clusteredShape.Longitude;
						
						unclusterShape();
					}
				}
			};
			
			unclusterMarkers();
		}
	},
	init: function() {
		$(this.listElems).click(function(e) {
			
			// Sophus tracking for dealer result pin clicks...
			var target = $(e.target);
			if (target.hasClass('markerImage')) {
				var id = target.attr('rel'),
					form_type = (mazdaDealersMap.isDealerLocator) ? 'dealerlocator' : 'testdrive';
				tc_log(pageurl + form_type +'_pin_dealerdetails.htm?firststep=1&dealerId='+ id);
			}
			
			var radio = $(this).find('input[type="radio"]');
			var id = (radio.length > 0) ? $(radio).val() : $(this).find('a img').attr('rel');
			dealers.select(id);
			//dealers.check(id, radio, this);
			
			backToTop(id);
		});
		
		// Invoke flashtalking tracking for DL form only when there are dealer results
		if ($(this.listElems).length && $('.DealerLocator').length) ftspot();
	},
	clear: function() {
		$(this.listElems).remove();
	}
};

function ftspot() {
	var ftRandom = Math.random() * 1000000,
		ftspotobj = document.createElement('div');
	
	ftspotobj.id = 'ftspotdiv_1213';
	ftspotobj.style.width = '1px';
	ftspotobj.style.height = '1px';
	ftspotobj.style.display = 'none';
	ftspotobj.innerHTML = '<iframe src="http://video.flashtalking.com/container/1213/1213_iFrame.html?DealerResultsPage&cachebuster='+ftRandom+'" height="1" width="1"></iframe>';
	
	document.body.appendChild(ftspotobj);
}

var backToTop = function(dealerId) {
	var time = time || 40,
		x1 = x2 = x3 = 0,
		y1 = y2 = y3 = 0;
	
	if (document.documentElement) {
		x1 = document.documentElement.scrollLeft || 0;
		y1 = document.documentElement.scrollTop || 0;
	}
	
	if (document.body) {
		x2 = document.body.scrollLeft || 0;
		y2 = document.body.scrollTop || 0;
	}
	
	x3 = window.scrollX || 0;
	y3 = window.scrollY || 0;
	
	var x = Math.max(x1, Math.max(x2, x3)),
		y = Math.max(y1, Math.max(y2, y3));
	
	window.scrollTo(Math.floor(x / 2), Math.floor(y / 2));
	
	if (x > 0 || y > 0) {
		window.setTimeout('backToTop('+dealerId+')', time);
	} else {
		dealers.showOnMap(dealerId);
	}
};

var populateSummary = function() {

	if (!$('#summaryArea').length > 0) return false;

	// dealer search summary form
	if (
		($('.dealerSearchFieldset').length > 0 && $('.results').length > 0) ||
		($('.dealerSearchFieldset').length > 0 && $('.dealerDetails.formRow').length > 0) ||
		($('.dealerServiceLegend').length > 0 && $('.dealerDetails.formRow').length > 0)
	   ) {
		var searchBtnCopy = $('.dealerSearch .dealerSearchBtn').clone();
		$('.dealerSearch .dealerSearchBtn').remove();

		var dealerSearchFieldsetCopy = $('.dealerSearchFieldset').clone(),
			searchBtnParent = $('<div class="dealerSearch formRow"></div>');

		$('.dealerSearchFieldset').remove();

		searchBtnParent.append(searchBtnCopy);
		dealerSearchFieldsetCopy.prepend('<span class="top"></span>').append(searchBtnParent);

		$('#summaryArea').append(dealerSearchFieldsetCopy);
	}

	// dealer service type legend
	if ($('.dealerServiceLegend').length > 0) {
		var dealerServiceLegendCopy = $('.dealerServiceLegend').clone();
		$('.dealerServiceLegend').remove();
		dealerServiceLegendCopy.prepend('<span class="top"></span>');
		$('#summaryArea').append(dealerServiceLegendCopy);
		dealerServiceLegendCopy.show();
	}

	// direction search summary form
	if ($('.summaryDirections[rel="summary"]').length > 0) {
		var summaryDirectionsCopy = $('.summaryDirections').clone();
		$('.summaryDirections').remove();
		summaryDirectionsCopy.prepend('<span class="top"></span>');
		$('#summaryArea').append(summaryDirectionsCopy);
	}
};

var setThankyouName = function() {
	if (! $('.nl-NL').length) {
	    // long names don't display well on ThankYou Page
	    if (thankyouUserName.length > 50) {
	        thankyouUserName = thankyouUserName.substring(0, 47) + '...' ;
	    }
	    
	    if (thankyouUserName != '' && $('.formTitle h2').length > 0) $('.formTitle h2').text($('.formTitle h2').text() + thankyouUserName);
	}

    // Removing the form tiltle h2 for IT: For Amy
	//if ($('.it-IT').length) {
	//    $('#formHead .formTitle h2').css('display', 'none');
	//}
    
    // also apply a fix for the phantom RFN spacebox issue
	if ($('div.chosenModels').length && ! $('ul.models').children().length) {
		$('div.chosenModels').css('background-color', 'transparent');
	}

};

var colourOpeningTimeRows = function() {
	var table = $('.dealerDetails table');
	if (table.length > 0) $('tr:gt(0):odd', table).addClass('rowColour');
};

var hideSuggestions = function() {
	var hideAutoSuggestStyle = '<style type="text/css" title="hideAutoSuggest">.autoSuggestElem { display: none; }</style>';
	if ($('.dealerSearchInput').length > 0) $('head').append(hideAutoSuggestStyle);
};

var removeSuggestions = function() {
	$(function() {
		$('.autoSuggestElem').remove();
	});
};

var bindSuggestions = function(cultureInfo) {
	$(function() {
		var inputElem = $('.dealerSearchInput');
		
		var autoSuggest = inputElem.autocomplete({
			serviceUrl: '/services/dealerautocompleteservice.ashx',
			minChars: 2,
			delimiter: /(,|;)\s*/, // regex or character
			maxHeight: 100,
			width: 250,
			deferRequestBy: 0,
			params: { culture: cultureInfo }
		});
		
		if (! $('.ie6').length) {
			autoSuggest.enable();
		} else autoSuggest.disable();
		
		inputElem.one('focus', function() {
			$('style[title="hideAutoSuggest"]').remove();
		});
	});
};

var resultsHandler = {
	growth: 3,
	resultsElem: '.results',
	results: {},
	resultCount: null,
	showCount: null,
	init: function(localisedText) {
		var that = this,
			parentElem = $(that.resultsElem);
		
		if (!parentElem.length > 0) return false;
		
		that.results = parentElem.children();
		that.resultCount = that.results.length;
		
		if (that.resultCount > that.growth) {
			that.results.each(function(i) {
				if (!(i < that.growth)) $(this).hide();
			});
			
			that.addControl(localisedText);
		}
	},
	//named function - public
	addControl: function(localisedText) {
		var that = this,
			controlElem = $('<p style="text-align: right;"><a href="#showMore" id="showMore">'+localisedText+'</a></p>');
		
		$(that.resultsElem).after(controlElem);
		//binding it to the eleemnt
		$('#showMore').click(function(e) {
			e.preventDefault();
			$(this).blur();
			
			that.showMore();
		});
	},
	showMore: function() {
		var that = this;
		
		if (that.showCount === null) that.showCount = that.growth;
		
		var targetCount = ((that.showCount + that.growth) < that.resultCount) ? (that.showCount + that.growth) : that.resultCount;
		
		var runMethod = function() {
			
			if (that.showCount < that.resultCount) {
				
				var nextElemIndex = that.showCount;
				
				if (nextElemIndex < targetCount) {
					
					$(that.results[nextElemIndex]).show(100, function() {
						that.showCount++;
						runMethod();
					});
				}
			
			} else that.removeControl();
		};
		
		runMethod();
	},
	removeControl: function() {
		$('#showMore').parent().fadeOut(300);
	}
};

var secondaryButtonSubmitted = false;

var validationHandler = function() {
	// dirty any rows which fields are invalid onload
	$('.validation_msg:visible').each(function() {
		$(this).parent('.formRow').addClass('hasError');
	});

	var errorText = '<p>There was an error submitting your details.<br />The following fields are missing or filled in incorrectly:</p>';
	
	var match_email_addresses = function(email_2) {
		if (email_2.val()) {
			var email_1 = $('.PrivateEmail');
			
			if (email_1.length && email_1.val()) {
				var email_2_pt = email_2.parent('.formRow'),
					no_match_error = $('span:last', email_2_pt);
				
				if (email_1.val() != email_2.val()) {
					if ($('.validation_msg:visible', email_2_pt).length) {
						no_match_error.css({ 'float':'right', 'margin-right':'13px' });
					} else {
						no_match_error.css({ 'float':'left', 'margin-right':'0' });
					}
					no_match_error.show();
					email_2_pt.addClass('hasError');
					
					Page_BlockSubmit = true;
				} else {
					no_match_error.hide();
					email_2_pt.removeClass('hasError');
					
					Page_BlockSubmit = false;
				}
			}
		}
	};
	
	var focusOnError = function(e) {
		e.preventDefault();
		var msg = $(this).text();
		$('.validation_msg:visible').each(function() {
			if ($(this).text() == msg) $(':input, :checkbox, :radio', $(this).parent()).focus();
		});
	};
	
	var removeErrorFromSummary = function(pt) {
		$('.validation_msg', pt).each(function() {
			var msg = $(this).text();
			
			$('.errorSummary li').each(function() {
				if ($(this).text() == msg) $(this).fadeOut(250, function() {
					$(this).remove();
					if (! $('.errorSummary li').length) $('.errorSummary').slideUp(250);
				});
			});
		});
	};
	
	var addErrorToSummary = function(pt) {
		if (! $('.errorSummary').length) {
			// create an error summary if one doesn't exist already
			var html = '<div class="errorSummary" style="color: red; display: none;">'+ errorText +'<ul></ul></div>';
			$('.formStep div:first').prepend(html);
		} else {
			if (! $('ul', '.errorSummary').length) {
				$('.errorSummary').append('<ul></ul>');
			}
		}
		
		if ($('.errorSummary').not(':visible')) $('.errorSummary').slideDown(250);
		
		var msgText = $('.validation_msg:visible', pt).text(),
			msgFound = false;
		
		$('.errorSummary li').each(function() {
			if ($(this).text() === msgText) msgFound = true;
		});
		
		if (! msgFound) {
			
			var li = $('<li style="display: none;"></li>'),
				a = $('<a href="#" class="errorfocus">'+ msgText +'</a>').click(focusOnError);
			
			li.append(a);
			
			$('.errorSummary ul').append(li);
			
			li.fadeIn(250);
		}
	};
	
	var dirtyInvalidRows = function() {
		var el = $(this),
			pt = el.parents('.formRow:not(.visualModelSelector)'); // exclude modelselector as it appends errors to the summary instead
		
		if (el.val()) el.change();
		
		window.setTimeout(function() {
			if ($('.validation_msg:visible', pt).length) {
				pt.addClass('hasError');
				
				if ($('form.en-GB').length) addErrorToSummary(pt);
			} else {
				pt.removeClass('hasError');
				
				if ($('form.en-GB').length && $('.errorSummary').length) removeErrorFromSummary(pt);
			}

		}, 50);
		
		if (el.hasClass('PrivateEmailConfirm')) {
			match_email_addresses(el);
		}
	};
	
	$('form').delegate(':input, :checkbox, :radio', 'blur', dirtyInvalidRows);
	
	var submissionHandler = function() {
		
		if (secondaryButtonSubmitted) {
			secondaryButtonSubmitted = false;
			return false;
		}
		
		// handle validation of title field radio buttons
		if (! $(':input[type="radio"]:checked', '.titleField').length) {
			$('.validation_msg', '.titleField').show();
			$('.titleField').addClass('hasError');
		}
		
		$(':input[type="radio"]', '.titleField').click(function() {
			if ($(':input[type="radio"]:checked', '.titleField').length) {
				$('.validation_msg', '.titleField').hide();
				$('.titleField').removeClass('hasError');
			}
		});
		
		// dirty field rows which return invalid
		window.setTimeout(function() {
			if ($('.validation_msg:visible').length) {
				$('.validation_msg:visible').each(function() {
					$(this).parents('.formRow').addClass('hasError');
				});
			}
		}, 50);
		
		// Messages are automatically added to the error summary onsubmit...
		// ...just have to bind the links with their fields
		if ($('form.en-GB').length && $('.errorSummary').length) {
			if (! $('.errorSummary p').length) $('.errorSummary').prepend(errorText);
			
			$('li', '.errorSummary').each(function() {
				var msgText = $(this).text(),
					a = $('<a href="#" class="errorfocus">'+ msgText +'</a>').click(focusOnError);
				$(this).html(a);
			});
		}
		
//		// T&C Opt-in validation for es-ES KMI & TD forms
//		if ($('form.es-ES .ComingSoon').length) {
//			var el = $('.optin input:first');
//			
//			if (el.is(':checked')) {
//				$('span.validation_msg', el.parent()).hide();
//				el.parents('.formRow').removeClass('hasError');
//			} else {
//				$('span.validation_msg', el.parent()).show();
//				el.parents('.formRow').addClass('hasError');
//			}
//		}
		
		if ($('.PrivateEmailConfirm').length) {
			match_email_addresses($('.PrivateEmailConfirm'));
		}
	};
	
	$('.secondary input[type="submit"]').click(function() {
		secondaryButtonSubmitted = true;
	});
	
	$('form').submit(function() {
		submissionHandler();
	});
	
	// T&C Opt-in validation for es-ES KMI & TD forms
//	if ($('form.es-ES .ComingSoon').length) {
//		var el = $('.optin input:first');
//		
//		if (el.length) {
//			var error_msg = '<span class="validation_msg" style="color: Red; display: none;">Por favor, acepte los términos y condiciones</span>',
//				button = $('.primary input[type="submit"]');
//			
//			el.parent().append('<acronym>*</acronym>').append(error_msg);
//			
//			el.click(function() {
//				var el = $(this);
//				if (el.is(':checked')) {
//					$('span.validation_msg', el.parent()).hide();
//					el.parents('.formRow').removeClass('hasError');
//				} else {
//					$('span.validation_msg', el.parent()).show();
//					el.parents('.formRow').addClass('hasError');
//				}
//			});
//			
//			button.click(function() {
//				submissionHandler();
//				if (!el.is(':checked')) {
//					// This is a global variable exposed by .net webforms
//					Page_BlockSubmit = true;
//				}
//			});
//		}
//	}
};

var testDriveButtonHandler = {
	showButtons: function() {
		if ($('.results').length > 0 && $('.hiddenFormAction').length > 0) {
			$('.hiddenFormAction').addClass('formAction').removeClass('hiddenFormAction');
		}
	},
	hideButtons: function() {
		$('.dealerSearchBtn .search :submit').click(function() {
			if ($('.formAction').length > 0) {
				$('.formAction').addClass('hiddenFormAction').removeClass('formAction');
			}
		});
	}
};

var submitOnEnter = function() {
	if ($('input[type="submit"]').length == 2) {
		if ($('input[type="submit"]','.formAction').length == 2) {
			$('form').keypress(function(e) {
				if (e.which == 13) {
					e.preventDefault();
					$('.formAction .primary input').click();
				} else return;
			});
		}
	}
};

// TODO: missing localisation
var jsLinks = {
	printText: 'Print this page',
	bookmarkText: 'Bookmark this page',
	create: function(formType) {
		$(function() {
			var html = $('<ul class="js-links"></ul>');

			if ((formType === 'DealerLocator' || formType === 'TestDrive')) {
				html.append('<li class="print"><a href="javascript:window.print();">' + jsLinks.printText + '</a></li>');

				if ($('.resultCount').length || (!$('form').hasClass('fr-CH') || !$('form').hasClass('it-CH') || !$('form').hasClass('de-CH'))) {
					$('.resultCount').append(html);
					return false;
				}

				if ($('.formTitle').length > 0 && $('.resultCount').length == 0 && $('.dealerDetails').length > 0) {
					if (formType === 'DealerLocator') {
						html.append(addToFavourites());
					}
					$('.formTitle').append(html);
				}

			} else return false;
		});
	}
};

var addToFavourites = function() {
	var url = window.location.href,
		title = window.document.title,
		parentEl = $('<li class="bookmark"></li>'),
		el = $('<a href="#">'+jsLinks.bookmarkText+'</a>');
	
	var ua = navigator.userAgent.toLowerCase(),
		isKonq = ua.indexOf('konqueror') != -1,
		isSafari = ua.indexOf('webkit') != -1,
		isMac = ua.indexOf('mac') != -1,
		buttonStr = isMac ? 'Cmd' : 'Ctrl';
	
	if (window.external && (!document.createTextNode || (typeof(window.external.AddFavorite) == 'unknown'))) { // IE/Win
		el.click(function(e) {
			e.preventDefault();
			window.external.AddFavorite(url, title);
		});
	} else if (isKonq) { // Konqueror
		el.addClass('noLink').text(el.text() +' ('+buttonStr+' + B)');
	} else if (window.opera) { // Opera 7+
		el.attr('rel', 'sidebar').attr('title', title).attr('href', url).click(function() {
			void(0);
		});
	} else if (window.sidebar) { // Firefox
		el.click(function(e) {
			e.preventDefault();
			window.sidebar.addPanel(title, url, '');
		});
	} else if (isSafari) { // Safari, Chrome, iCab
		el.addClass('noLink').text(el.text() +' ('+buttonStr+' + D)');
	} else if (!window.print || isMac) { // Safari 1.0, Mac
		el.addClass('noLink').text(el.text() +' ('+buttonStr+' + D)');
	} else return false;
	
	return parentEl.append(el);
};

var removeBorder = function() {
	// removes unwanted bottom border from chosen models on brochure request and KMI forms
	$('li:not(li li):last', '.chosenModels[rel="chosenModelsOnly"]').css({'border-bottom':'none', 'padding-bottom':'0'});
};

var cookie = {
	set: function(name, value, expireDays) {
		var exDate = new Date();
		exDate.setDate(exDate.getDate()+expireDays);
		document.cookie = name+'='+escape(value)+((expireDays==null) ? '' : ';expires='+exDate.toGMTString());
	},
	get: function(name) {
		if (document.cookie.length > 0) {
			var start = document.cookie.indexOf(name+'=');
			if (start != -1) {
				start += name.length+1;
				var end = document.cookie.indexOf(';', start);
				if (end == -1) end = document.cookie.length;
				return unescape(document.cookie.substring(start, end));
			}
		}
		return null;
	},
	kill: function(name) {
		this.set(name, '', -1);
	}
};

var bindThankyouTcLog = function() {
	$('.pdf a').click(function() {
		var pdfurlparts = $(this).attr('href').split('/');
		var pdfname = pdfurlparts[pdfurlparts.length - 1];
		if (pageurl != null) tc_log(pageurl + $(this).attr('rel') + '/' + pdfname);
	});
};

var optinDependency = function() {
	if ($('.rbOptins input').length && $('.cbOptins input').length) {
		
		if ($('.nl-NL').length) {
			var parentEl = $('.cbOptins').parent();
			parentEl.append('<span class="validation_msg rbError" style="color: red; display: none;">Selecteer een keuzerondje</span><span class="validation_msg cbError" style="color: red; display: none;">Selecteer een selectievakje</span><acronym style="left: 217px; top: 13px;">*</acronym>');
			
			var addError = function(className) {
				if ($('.'+ className +':hidden', parentEl).length) {
					$('.'+ className, parentEl).show();
					parentEl.css('background-color', '#FFDACC').addClass('hasError');
				}
			};
			
			var removeError = function() {
				if ($('.validation_msg:visible', parentEl).length) {
					$('.validation_msg', parentEl).hide();
					parentEl.css('background-color', '#fff').removeClass('hasError');
				}
			};
			
			$('.rbOptins input').click(function() {
				removeError();
			});
			
			$('.primary input[type="submit"]').click(function() {
				if (!$('.rbOptins input:checked').length) {
					addError('rbError');
					Page_BlockSubmit = true;
				}
			});
			
			$('form').unbind('keypress').keypress(function(e) {
				if (e.which == 13) {
					e.preventDefault();
					
					if (!$('.rbOptins input:checked').length) {
						addError('rbError');
						Page_BlockSubmit = true;
					} else {
						$('.formAction .primary input').click();
					}
					
				} else return;
			});
		} else {
			$('.cbOptins input').attr('disabled', true);
			
			$('.rbOptins input').click(function() {
				$(this).blur();
				if ($(this).attr('value') == 'false') {
					$('.cbOptins input').attr('disabled', true);
				} else {
					$('.cbOptins input').attr('disabled', false);
				}
			});
		}
	}
};

var adjustFormHeight = function() {
	if ($('body.ie6').length) {
		if ($('.formwizard').height() < 230) $('.formwizard').height(230);
	}
};
