jQuery(document).ready(function($){
	
	//set up the values for the Product dropdown depending on the selected item in the product type dropdown
	//why these weren't stored as named keys in the HTML, I don't know...
	var productCategories = {
		1:[
			'Intel Product:',
			'Enrollment',
			'Account Status',
			'Membership Renewal',
			'Financial Benefit',
			'Login/Password Help',
			'Training',
			'Update Account Info', 
			'Intel&reg; Flex+', 
			'Intel&reg; Inside Track 2 Program'
		],
		2:[
			'Intel Product:',
			'Multi-core Processors',
			'Other Processors',
			'Boards',
			'Network Adapter',
			'Wireless Networking',
			'Hyperthreading Technology',
			'Other'
		],
		3:[
			'Intel Product:',
			'Multi-core Processors',
			'Other Processors',
			'Network Adapter',
			'Wireless Networking',
			'Centrino Mobile Technology',
			'Other'
		],
		4:[
			'Intel Product:',
			'Board',
			'Chassis',
			'Network Adapter',
			'Multi-core Processors',
			'Other Processors',
			'RAID Controller',
			'Spare Parts',
			'Wireless Networking',
			'Other'
		],
		5:[
			'Intel Product:',
			'Conferencing',
			'Driver/Software',
			'HMP',
			'IVR',
			'SS7',
			'VoIP', 
			'Xircom',
			'Routers',
			'Switches',
			'Hubs',
			'Intel &reg; Easy PC Webcam',
			'Other'
		],
		6:[
			'Intel Product:',
			'Developer Software',
			'Developer Hardware',
			'Other'
		],
		7:[
			'Intel Product:',
			'Embedded Products'
		],
		8:[
			'Intel Product:',
			'Viiv'
		],
		9:[
			'Intel Product:',
			'Solid State Drive',
			'Modular Server',
			'Other'
		],
		10:[
			'Intel Product:',
			'Other'
		]
	};
	
	//handle when the select box changes
	$('#IntelProductType').change(function(){
		var select = $('#IntelProduct');
		select.empty();
		if($(this).val()!=''){		
			$.each(productCategories[$(this).val()],function(i,text){
				select.append('<option value='+(!!i?i:'')+'>'+text+'</option>' );
			});	
		}
		else{
			select.append('<option>Intel Product:</option>');
		}
	}).change(); //and call the change event when the page loads
	
	//handle clicks of the submit button, doing validation and other necessary pre-submission things
	$('input[type="submit"]').click(function(){
		//remove all the little validation warnings and start clean
		$('.warning').remove();
		
		//track validity throughout the process so we know what to return
		var formIsValid = true;
		
		//function for showing little validation warnings. will be called by the validate() plugin
		//this function will also mark this process as invalid
		var showError = function(message){
			formIsValid = false;
			$(this).invalid(message);
		};
		
		//don't shove phone errors between inputs
		var showPhoneError = function(message){
			formIsValid = false;
			$('#Phone3').invalid(message);
		}
		
		//validate the required text fields
		$('#FirstName, #LastName, #Question, #NearestCountry, #CustomerType, #IntelProductType, #IntelProduct, #IssueType').validate({
			required:true,
			failure:showError
		});
		
		$('#Phone1').validate({
			required:true,
			success:function(){
				$('#Phone2').validate({
					required:true,
					success:function(){
						$('#Phone3').validate({
							required:true,
							failure:showPhoneError
						})
					},
					failure:showPhoneError
				})
			},
			failure:showPhoneError
		});
		
		//validate the required email field
		$('#email').validate({
			required:true,
			email:true,
			failure:showError
		});
		
		//the text of the selected customer type
		var selectedCustomerType = $('#CustomerType option:selected').val();
		
		//Home users must select a company name
/* 		if($('#CustomerType option:selected').val() == 'Home'){
			$('#CompanyName').validate({
				required:true,
				failure:function(){
					formIsValid = false;
					$(this).invalid('For Home Customers, you must supply a Company Name');
				}
			});
		} */
		
		
		//ICPPN users must either select partner number or company name and address
/* 		if(selectedCustomerType == 'ICPPN'){
			var message = 'For Intel(r) Channel Partner Program Members, Intel Channel Partner Number or Business name (and address) is required.';
			$('#ChannelNumber').validate({
				required:true,
				failure:function(){
					if channel partner number fails, check copany name + address
					$('#CompanyName, #Address').validate({
						required:true,
						failure:function(){
							formIsValid = false;
							$(this).invalid(message);	
						}
					});
					
				}
			});
		} */
		
		if(selectedCustomerType == 'ICPPN'){
			var message = 'For Intel &reg; Channel Partner Program Members, Intel Channel Partner Number is required.';
			$('#ChannelNumber').validate({
				required:true,
				failure:function(){
					formIsValid = false;
					$(this).invalid(message);					
				}
			});
		}
		
		
		//if the form is valid, let it submit after doing a few last things
		if(formIsValid){ 
			//setup the subject hidden field
			var c = $('#NearestCountry option:selected').text();
			var ppt = $('#IntelProductType option:selected').text();
			var prod = $('#IntelProduct option:selected').text();
			var type = $('#IssueType option:selected').text();
			var subj = c+ppt+prod+type;
			$('#subject').val(  c + ' - ' + ppt + ' - ' + prod + ' - ' + type );
			
			//for some reason we're converting the dropdown of product types to it's text string. I don't know why that's not what's just stored in the first place for value
			//but i don't want to edit the html form
			$('#IntelProductType option:selected').val(ppt);
			
			return true;
		}
		//otherwise it's not valid, don't allow submission
		return false;
	});
});

//create a jquery plugin for basic form validation
//syntax : myElement.validate({required:true,email:true}) and so on...
(function($){
	$.fn.validate = function(options){
		var settings = $.extend({
			required:false,
			email:false,
			phone:false,
			integer:false,
			success:function(){},
			failure:function(){}
		},options);
		
		var validateInteger = function(val){
			var i;
			for (i = 0; i < val.length; i++){
				var c = val.charAt(i);
				if (((c < "0") || (c > "9"))) return false;
			}
			return true;
		};
		var validateEmail = function(val){
			var trimmed = val.replace(/^\s+|\s+$/, '');
			var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ;
			var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;
		   
			if (!emailFilter.test(trimmed) || val.match(illegalChars)) {
				return false;
			}
			return true;
		};
		
		var validatePhone = function(val,minDigits){
			var digits = "0123456789";
			var phoneNumberDelimiters = "()- ";
			var validWorldPhoneChars = phoneNumberDelimiters + "+";
			var minDigitsInIPhoneNumber = minDigits || 10;
		
			var stripCharsInBag = function(s, bag){ 
				var i;
				var returnString = "";
				for (i = 0; i < s.length; i++){
					var c = s.charAt(i);
					if (bag.indexOf(c) == -1) returnString += c;		
				}
				return returnString;
			}
			var s=stripCharsInBag(val,validWorldPhoneChars);
			return (validateInteger(s) && s.length >= minDigitsInIPhoneNumber);
	
		};
		return this.each(function(){
			var val = (this.nodeName.toLowerCase() == 'input' || this.nodeName.toLowerCase() == 'textarea' || this.nodeName.toLowerCase() == 'select')?$(this).val():$(this).text();
			if (val === '') {
				if (settings.required) {
					settings.failure.call(this, 'Required Field');
					return;
				}
				settings.success.call(this);
				return;
			}
			if (settings.integer && !validateInteger(val)){
				settings.faiure.call(this,'Not a number');
				return;
			}
			if (settings.email && !validateEmail(val)){
				settings.failure.call(this,'Invalid Email')
				return;
			}
			if (settings.phone && !validatePhone(val)){
				settings.failure.call(this,'Invalid Phone Number')
				return;
			}
			settings.success.call(this);
		});				
	};
	
	$.fn.invalid = function(message){
		var message = message;
		return this.each(function(){
			$('<span style="color:ff0000;margin-left:5px;" class="warning"><br />'+message+'</span>').insertAfter($(this));	
		});
	};
	$.fn.valid = function(){
		return this.each(function(){
			var label = $('label[for='+this.id+']');
			label.find('.invalid').remove();
		});
	};
})(jQuery);
