// Birmingham radio promotional campaign - Ollie Buck
// isupport id 16039
// This is a time limited thing for certain pages only, let's try and keep it out of the core booking form code shall we?

$( function() {	

	// setTimeout so it doesn't matter if this file is included before or after the bookingform is
	setTimeout( function() {
		
		// Get all classes from the promo code box's parent - one of them will match a <form>
		$( $('input[name=accountnum]').parent('div').attr('class').split(' ')).each( function(i,n) {
		
			// if it does, this class name is the name of our booking form javascript object!
			if( typeof(n) == 'string' && $('form.'+n).length && $('form.'+n).find('input[name=accountnum]').length ) {
				
				// Only show promo code box if airport is bhx
				$(':input[name=Location]', 'form.'+n).change( function() {
					if($(this).val() == 'BHX') {
						$('input[name=accountnum]').parent().show();
					} else {
						$('input[name=accountnum]').parent().hide();
					}
				}).change();
				
				// Still need to call the original validation
				window[n].validateOrig = window[n].validate;
				
				// But with some other code in front of it
				window[n].validate = function() {
					if( $(':input[name=Location]').val() != 'BHX') {
						// only offer discount on BHX, restore original code otherwise
						if( this.originalAgentCode) {
							$('input[name=agent]').val( this.originalAgentCode);
						}
						return true;
					} else {
						this.originalAgentCode = $('input[name=agent]').val();
						
						// Levenshtein algorithm! I spell that good. From php.js as i didnt want to write ANOTHER script to
						// call asynchronously and commit it into svn to support this one-time marketing driven thing...
						// This lets us correct small typos if what the user typed is "close enough" to a known promo code
						var levenshtein = function(s1, s2) {
						
							if (s1 == s2) {
								return 0;
							}
							var s1_len = s1.length;
							var s2_len = s2.length;
							if (s1_len === 0) {
								return s2_len;
							}
							if (s2_len === 0) {
								return s1_len;
							}
						
						    var split = false;
						    try {
								split=!('0')[0];
						    } catch (e) {
						    	split=true; // Earlier IE may not support access by string index
						    }
						    if (split) {
						        s1 = s1.split('');
						        s2 = s2.split('');
						    }

							var v0 = new Array(s1_len+1);
							var v1 = new Array(s1_len+1); 
							var s1_idx=0, s2_idx=0, cost=0;
							for (s1_idx=0; s1_idx<s1_len+1; s1_idx++) {
								v0[s1_idx] = s1_idx;
							}
							var char_s1='';
							var char_s2='';
							for (s2_idx=1; s2_idx<=s2_len; s2_idx++) {
								v1[0] = s2_idx;
								char_s2 = s2[s2_idx - 1];
								for (s1_idx=0; s1_idx<s1_len;s1_idx++) {
									char_s1 = s1[s1_idx];
									var cost = (char_s1 == char_s2) ? 0 : 1;
									var m_min = v0[s1_idx+1] + 1;
									var b = v1[s1_idx] + 1;
									var c = v0[s1_idx] + cost;
									if (b < m_min) {
										m_min = b; 
									}
									if (c < m_min) {
										m_min = c; 
									}
									v1[s1_idx+1] = m_min;
								}
								var v_tmp = v0;
								v0 = v1;
								v1 = v_tmp;
							}
							return v0[s1_len];
						}
					
						var validPromoCode = false;
						var promoCodes = { /* enjoy your discount, person who reads our source code for whatever reason. hope you're flying from birmingham! */
							'radio':'WG923',
							'discount':'WG925',
							'birmingham':'WG924',
							'heart':'WR001',
							'wyvern':'WR002',
							'beacon':'WR003'
						}
												
						var promoCode = $('input[name=accountnum]').val().replace(/ /g, '').toLowerCase();
						
						if( promoCode == '') { 
							validPromoCode = true; // they didn't even try one, let it through...						
						} else if( promoCodes[promoCode]) {
							$('input[name=agent]').val( promoCodes[promoCode]); // exact match
							validPromoCode = true;
						} else {
							for( c in promoCodes) {
								if( (typeof( promoCodes[c]) == 'string') && (levenshtein( c, promoCode) <= 2) ) {
									$('input[name=agent]').val( promoCodes[c]); // close enough!
									validPromoCode = true;
								}
							}
						}
					}
					
					// so, do we prompt here if they tried one and its wrong, or not?
					return (validPromoCode || confirm('We don\'t recognise this promotional code. Continue anyway?')) && window[n].validateOrig();
				};
			}
		});
	}, 250);
});