var MA = {
	dateMinWarning: 'Please revise it in the format YYYY-MM-DD and make sure it is not before the year 1900.'
	,addendumsRequired: {specialty: false, subspecialty: false}
	,downloadPath: '/sites/all/themes/cap/membership_application/downloads/'
	,setAddendum: function(selectedVal, addendumContainerSelector){
		var exists = false;
		var $addendumContainer = $(addendumContainerSelector);
		for(property in this.specialtyAddendum){
			if(property === selectedVal){
				exists = true;
				var addendum = this.specialtyAddendum[property];
				if(addendum){
					if(addendumContainerSelector.indexOf('sub') != -1){
						this.addendumsRequired.subspecialty = true;
					}
					else{
						this.addendumsRequired.specialty = true;
					}
					$addendumContainer.fadeIn('fast');
					var fullPath = this.downloadPath + addendum.toLowerCase() + '.pdf';
					$('a.specialty_addendum_link', $addendumContainer).attr('href', fullPath).text(addendum + '.pdf');
				}
				else{
					if(addendumContainerSelector.indexOf('sub') != -1){
						this.addendumsRequired.subspecialty = false;
					}
					else{
						this.addendumsRequired.specialty = false;
					}
					$addendumContainer.fadeOut('fast');
				}
				 
				break;
			}
		}
		
		if( ! exists){
			$($addendumContainer).hide();
		}	
	}
	,populate_file_status: function (files_object){
		for(var file_subject in files_object){
			var file_status_id = '#file_status_' + file_subject.toLowerCase();
			var $file_status = $(file_status_id);		
			if($('li', $file_status).hasClass('file_absent')){
				$file_status.empty();
			}
			var file_collection = files_object[file_subject];	
			for(var i = 0; i < file_collection.length; i++){
				var file_object = file_collection[i];
				$file_status.append(this.file_status_factory(file_object.file_id, file_object.file_name, file_object.file_size, file_object.uploadNoticeId));
			}			
		}
	}
	,file_status_factory: function (file_id, file_name, file_size){
		if(file_name.length > 70){	
			var temp = file_name.substring(0,70);
			var last_whitespace = temp.lastIndexOf(' ');
			if(last_whitespace > 55){
				file_name = temp.substring(0, last_whitespace);
			}
			file_name += ' ...';
		}
		var kb = (file_size / 1000).toFixed(1);
		_file_size = kb + ' KB';
		return '<li class="file_present"><span title="Delete File!" class="file_delete" fileId="' + file_id + '">Delete File</span><span title="File Size" class="file_size">' + _file_size + '</span><a title="Download File" href="/sites/all/themes/cap/membership_application/download_file.php?id=' + file_id +'">' + file_name + '</a></li>';
	}
	,isValidDate: function(strDate){
		//YYYY-MM-DD and must not be earlier than 1900-01-01 and must not be later than 2099-12-31
		var datePat = /^((19|20)\d{2})(?:\-)(\d{1,2})(?:\-)(\d{1,2})$/;		
		
		if ( ! datePat.test(strDate)){
			return false;
		}
		
		var dateObject = this.parseDate(strDate);
		var dteDate = new Date(dateObject.year, dateObject.month, dateObject.day);
		
		/*
			Javascript Dates are a little too forgiving and will change the date to a reasonable 
			guess if it's invalid. We'll use this to our advantage by creating the date object 
			and then comparing it to the details we put it. If the Date object is different, 
			then it must have been an invalid date to start with.
		*/
		return ((dateObject.day==dteDate.getDate()) && (dateObject.month==dteDate.getMonth()) && (dateObject.year==dteDate.getFullYear()));
	}
	,parseDate: function(strDate){
		//YYYY MM DD
		var datePat = /^(\d{4})(?:\-)(\d{1,2})(?:\-)(\d{1,2})$/;
		var matchArray = strDate.match(datePat);
		
		if ( ! matchArray){
			return false;
		}
			
		day = matchArray[3];
		month = matchArray[2];
		year = matchArray[1];
		month--;
		
		return {year: year, month: month, day: day};
	}
	,setSpecialtySelectList: function(selectListElementSelector, selectedSpecialty, isSubSpecialty){
		var selectList = document.getElementById(selectListElementSelector);
		if(! selectList){
			return false;
		}
		for(prop in MA.specialtyAddendum){
			if(selectList.length === 0){
				if(isSubSpecialty){
					selectList.options[0] = new Option('None', 'None', true);
				}
				else{
					selectList.options[0] = new Option('Select Specialty', 'Select Specialty', true);
				}
			}
			selectList.options.add(new Option(prop, prop, false, (prop === selectedSpecialty)));
		}		
	}
	,specialtyAddendum: {
		'Acupuncture':''
		,'Allergy & Immunology':'Allergy Questions'
		,'Anesthesiology':'Anesthesiology Questions'
		,'Bariatrics':''
		,'Burn Management':''
		,'Cardiology-Non Invasive':'Internal Medicine Questions'
		,'Cardiology-Pediatric-Non Invasive':'Internal Medicine Questions'
		,'Cardiology W/Diag Coronary Angiography':'Internal Medicine Questions'
		,'Cardiology W/Transluminal Procedures':'Internal Medicine Questions'
		,'Cardiovascular/Thoracic Surgery':'General Thoracic Vascular Surgery Questions'
		,'Colon Rectal Surgery':'General Thoracic Vascular Surgery Questions'
		,'CRS - Reduced To Assist':''
		,'Critical Care Medicine':'Internal Medicine Questions'
		,'Dermatology':'Dermatology Questions'
		,'Dermatology, W/Liposuction':'Dermatology Questions'
		,'Emergency Medicine':''
		,'Endocrinology':'Internal Medicine Questions'
		,'Family Medicine,  With Major Surgery':'Family General Practice Questions'
		,'Family Medicine, With Minor Surgery':'Family General Practice Questions'
		,'Family/General Medicine, With Surgical Assist':'Family General Practice Questions'
		,'Family Medicine, With Obstetrics ':'Family General Practice With Obstetrics Questions'
		,'Gastroenterology':'Internal Medicine Questions'
		,'General Practice, With Major Surgery':'Family General Practice Questions'
		,'General Practice, With Minor Surgery':'Family General Practice Questions'
		,'General Practice, With Obstetrics':'Family General Practice With Obstetrics Questions'
		,'General Surgery':'General Thoracic Vascular Surgery Questions'
		,'General Surgery, Oncology':'General Thoracic Vascular Surgery Questions'
		,'General Surgery, Reduced to Assist':'General Thoracic Vascular Surgery Questions'
		,'General/Vascular Surgery':'General Thoracic Vascular Surgery Questions'
		,'Geriatrics':''
		,'Gynecological Surgery':'Obstetrics and Gynecology Questions'
		,'Gynecological Surgery, Infertility':'Obstetrics and Gynecology Questions'
		,'Gyn - Reduced To Assist':'Obstetrics and Gynecology Questions'
		,'Hand Surgery':''
		,'Hematology/Oncology':'Internal Medicine Questions'
		,'Hospitalist':'Hospitalist Questions'
		,'Hyperbaric Medicine':''
		,'Independent Medical Exams':''
		,'Infectious Diseases':''
		,'Internal Medicine':'Internal Medicine Questions'
		,'Internal Medicine/Hospitalist':'Internal Medicine Questions'
		,'Internal Medicine/Pulmonology':'Internal Medicine Questions'
		,'Maternal Fetal Medicine - No Obstetrics':''
		,'Medical Oncology':'Internal Medicine Questions'
		,'Neonatology':'Pediatrics Questions'
		,'Nephrology, General':'Internal Medicine Questions'
		,'Neurological Surgery':'Neurosurgery Questions'
		,'Neurosurgery, Reduced To Assist':'Neurosurgery Questions'
		,'Neurology':'Neurology Questions'
		,'Obstetrics & Gynecology':'Obstetrics and Gynecology Questions'
		,'Obstetrics, Perinatology':'Obstetrics and Gynecology Questions'
		,'Occupational Medicine':''
		,'Ophthalmology, No  Refractive Procedures':'Ophthalmology Questions'
		,'Ophthalmology, W/ Refractive Procedures':'Ophthalmology Questions Refractive Corneal Procedures'
		,'Oral And Maxilofacial Surgery':''
		,'Orthopedic Surgery, No Spinal Surgery':'Orthopedic Surgery Questions'
		,'Orthopedic Surgery, Reduced To Assist':'Orthopedic Surgery Questions'
		,'Orthopedic Surgery, Sports Medicine':'Orthopedic Surgery Questions'
		,'Orthopedic Surgery, With Spinal':'Orthopedic Surgery Questions'
		,'Osteopathic Manipulative Medicine':'Do Practice Questions'
		,'Osteopathic Manipulative Medicine':'Do Practice Questions'
		,'Otolaryngology, Elective Cosmetic Surgery':'Otolarynology Questions'
		,'Otolaryngology, Reduced to Assist':'Otolarynology Questions'
		,'Otolaryngology, With Surgery':'Otolarynology Questions'
		,'Pain Medicine, Interventional':'Pain Management Questions'
		,'Palliative Care':'Internal Medicine Questions'
		,'Pathology, Clinical and Anatomical':'Pathology Questions'
		,'Pathology, Dermatopathology':'Pathology Questions'
		,'Pediatric Behavioral Medicine':'Pediatrics Questions'
		,'Pediatric Critical Care':'Pediatrics Questions'
		,'Pediatric  Gastroenterology':'Pediatrics Questions'
		,'Pediatrics General, Minor Surgery':'Pediatrics Questions'
		,'Pediatrics, Hospitalist':'Pediatrics Questions'
		,'Physical Medicine And Rehabilitation':'Physical Medicine and Rehabilitation Physiatry Questions'
		,'Plastic Surgery':'Plastic Surgery Questions'
		,'Plastic Surgery, Reduced To Assist':'Plastic Surgery Questions'
		,'Preventive Medicine':'Preventive Medicine Questions'
		,'Psychiatry':'Psychiatry Questions'
		,'Psychiatry-Child and Adolescent':'Psychiatry Questions'
		,'Psychoanalysis':'Psychiatry Questions'
		,'Pulmonary Medicine':'Internal Medicine Questions'
		,'Radiation Oncology':'Radiology Questions'
		,'Radiology, Diagnostic':'Radiology Questions'
		,'Radiology, Nuclear Medicine':'Radiology Questions'
		,'Rheumatology':'Internal Medicine Questions'
		,'Sleep Medicine':'Internal Medicine Questions'
		,'Sports Medicine, Primary Care':'Family General Practice Questions'
		,'Surgical Critical Care':'General Thoracic Vascular Surgery Questions'
		,'Thoracic Surgery':'General Thoracic Vascular Surgery Questions'
		,'Thoracic Surgery, Reduced To Assist':'General Thoracic Vascular Surgery Questions'
		,'Trauma Surgery':'General Thoracic Vascular Surgery Questions'
		,'Urgent Care Medicine':''
		,'Urogynecology':'Obstetrics and Gynecology Questions'
		,'Urological Surgery':'Urology Questions'
		,'Urology, Reduced To Assist':'Urology Questions'
		,'Vascular Surgery':'General Thoracic Vascular Surgery Questions'
		,'Vascular Surgery - Fellowship':'General Thoracic Vascular Surgery Questions'
		,'Vas/Thoracic Surgery, Reduced To Assist':'General Thoracic Vascular Surgery Questions'
	}
	,viewOptions: [
	    {
	        title: 'Create Your User ID and Password',
	        validation:
	            function(ctx){
	                var pw = '';
	                var pw_conf = '';
	                var msg = '';
	                $('#APPLICANT_ID_FORM :input').each(function(){
	                	var $this = $(this);
	                    var val = $this.val();
	                    switch($this.attr('name')){
	                        case 'ID_Email_Address':
		                        if( ! val){
		                            msg += 'Email Address is a required field! \n\n';
		                        }
		                        else if( ! val.match(/\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/)){
		           					msg += 'Please check the formatting of the your email address! \n\n';
		        				}
	                        	break;
	                        case 'ID_Password' :
	                        	pw = val;
	                        	if ( ! pw){
									msg += 'Password is a required field!\n\n';
								}
								break;
	                        case 'ID_Password_Confirm':
	                        	pw_conf = val;
	                        	//if( ! pw_conf){
	//								msg += 'Please enter a confirmation password!';
	//							}
	                        	break;
	                    }
	                });
	                
	                if(pw != pw_conf){
						msg += 'The passwords you entered do not match! Please try again';
					}
					
	                if(msg){
	                    alert(msg);
	                    return false;
	               }
	               return true;      
	            }
	    }
		,
		{
	        title: 'Introduction and Instructions',
			validation:
				function(ctx){
					return true;
				}       
	    }
	    ,
		{
			title: 'Physician Organizations',
			validation:
				function(ctx){
					return true;
				}
		}
	    ,
	    {
	        title: 'Personal Information',
	        validation:
	            function(ctx){
	               var msg = '';
					var fName = $('#PERSONALINFORMATION_Fname', ctx).val();
					var lName = $('#PERSONALINFORMATION_Lname', ctx).val();
					var dateOfBirth = $('#PERSONALINFORMATION_DBirth', ctx).val();
					var educationType = $('#PERSONALINFORMATION_MD:checked, #PERSONALINFORMATION_DO:checked', ctx).length;
					var ssn = $('#PERSONALINFORMATION_SSN', ctx).val();
					
					function isValidSSN(value) { 
					    var re = /^([0-6]\d{2}|7[0-6]\d|77[0-2])([ \-]?)(\d{2})\2(\d{4})$/; 
					    if (!re.test(value)) { return false; } 
					    var temp = value; 
					    if (value.indexOf("-") != -1) { temp = (value.split("-")).join(""); } 
					    if (value.indexOf(" ") != -1) { temp = (value.split(" ")).join(""); } 
					    if (temp.substring(0, 3) == "000") { return false; } 
					    if (temp.substring(3, 5) == "00") { return false; } 
					    if (temp.substring(5, 9) == "0000") { return false; } 
					    return true; 
					}
					
					if( ! fName){
						msg = 'First Name is a required field!\r\n';
					}
					
					if( ! lName){
						msg += 'Last Name is a required field!\r\n';
					}
					
					if( ! dateOfBirth){
						msg += 'Date of Birth is a required field!\r\n';
					}
					else if( ! MA.isValidDate(dateOfBirth)){
						msg += 'Date of Birth is invalid! ' + MA.dateMinWarning + '\r\n';
					}
					
					if(educationType < 1){
						msg += 'Education Type is a required field!\r\n';
					}
					
					if( ! ssn){
						msg += 'Social Security Number is a required field!';
					}
					else if(! isValidSSN(ssn)){
						msg += 'Please check the formatting of your Social Security Number!';
					}
					
					if(msg){
						alert(msg);
						return false;
					}
					
					return true;
	            }
	    }
	    ,
	    {
	        title: 'Specialty Information',
	        validation:
	            function(ctx){
	     			var msg = '';
	               	if($('#SPECIALTYINFORMATION_Specialty', ctx).val() === 'Select Specialty'){
	               		msg = "Specialty is a required field. Please select a Specialty.";
	               	}
	        		
	        		$('.date_picker', ctx).each(function(index){
	        			var val = $(this).val();
	        			var section = index < 2 ? "specialty " : "subspecialty ";
	        			if(val){
	        				if( ! MA.isValidDate(val)){
	        					msg += '\r\nThe date value you entered for ' + section + $(this).prev('label').text().toLowerCase() + ' exam is not valid! ' + MA.dateMinWarning;;
	        				}
	        			}
	        		})
	        		
	        		if(msg){
	        			alert(msg);
	        			return false;
	        		}
	        		
	        		return true;
	            }
	    }
	    ,
	    {
	        title: 'Referral and Coverage Information',
	        validation:
	            function(ctx){
	            	var msg = '';
					var coverageDateInput = $('input#REFERRALANDCOVERAGEINFORMATION_CoverageDate', ctx).val(); 
					if(coverageDateInput){
						if( ! MA.isValidDate(coverageDateInput)){
							msg = 'The Requested Coverage date you entered is not valid! ' + MA.dateMinWarning;; 
						}
						else{
							var today = new Date();
							var parsedDate = MA.parseDate(coverageDateInput);
							var coverageDate = new Date(parsedDate.year, parsedDate.month, parsedDate.day);
							if(coverageDate < today){
								msg += 'Please revise your Requested Coverage Date to a time in the future.'
							}
						}
					}
					if(msg){
	        			alert(msg);
	        			return false;
	        		}
	        		
	        		return true;
	            }
	    }
	    ,
	    {
	        title: 'Addresses',
	        validation:
	            function(ctx){
           			var msg = '';
					var pCity = $('#ADDRESSES_PrimaryOfficeCity', ctx).val();
					var pState = $('#ADDRESSES_PrimaryOfficeState', ctx).val();
					if( ! pCity){
						msg += 'Primary Office City is a required field!\r\n';
					}			
					if( ! pState){
						msg += 'Primary Office State is a required field!\r\n';
					}
					$('.date_picker', ctx).each(function(index){
	        			var val = $(this).val();
	        			if(val){
	        				if( ! MA.isValidDate(val)){
	        					msg += 'The date value you entered for temporary address is not valid! ' + MA.dateMinWarning + '\r\n';
	        				}
	        			}
	        		}) 
					if(msg){
	        			alert(msg);
	        			return false;
	        		}
	        		
	        		return true; 
	            }
	    }
	    ,
	    {
	        title: 'Practice History',
	        validation:
	            function(ctx){
					msg = '';
	                $('.date_picker', ctx).each(function(index){
	        			var val = $(this).val();
	        			var section = 'first ';
	        			switch(index){
	        				case 0 :
	        				case 1 :
		        				section = 'first';
		        				break;
		        			case 2 :
		        			case 3 :
		        				section = 'second';
		        				break;
		        			case 4 :
		        			case 5 :
		        				section = 'third';
		        				break;
		        			case 6 :
		        			case 7 :
		        				section = 'fourth';
	        			}
	        			if(val){
	        				if( ! MA.isValidDate(val)){
	        					msg += '\r\nThe date value you entered for the ' + $(this).parent('label').text().replace(/<.*?>|\(.*?\)|[^a-z]/ig, '') + ' field on the ' + section + ' location section is not valid! ' + MA.dateMinWarning;
	        				}
	        			}
	        		})
	        		
	        		if(msg){
	        			alert(msg);
	        			return false;
	        		}
	        		
	        		return true; 
	            }
	    }
	    ,
	    {
	        title: 'Training Information',
	        validation:
	            function(ctx){
	                //nothing to validate
	                return true;
	            }
	    }
	    ,
	    {
	        title: 'Practice Information',
	        validation:
	            function(ctx){
	                //nothing to validate
	                return true;
	            }
	    }
	    ,
	    {
	        title: 'Hospital Privileges',
	        validation:
	            function(ctx){
	                //nothing to validate
	                return true;
	            }
	    }
	    ,
	    {
	        title: 'Employees and Contracted Personnel',
	        validation:
	            function(ctx){
	                //nothing to validate
	                return true;
	            }
	    }
	    ,
	    {
	        title: 'Entity Information',
	        validation:
	            function(ctx){
	                //nothing to validate
	                return true;
	            }
	    }
	    ,
	    {
	        title: 'Professional Disclosure',
	        validation:
	            function(ctx){
	                //nothing to validate
	                return true;
	            }
	    }
	    ,
	    {
	        title: 'Insurance History',
	        validation:
	            function(ctx){
	            	msg = '';
	                $('.date_picker', ctx).each(function(index){
	        			var val = $(this).val();
	        			var section = 'first ';
	        			switch(index){
	        				case 0 :
	        				case 1 :
		        				section = 'first';
		        				break;
		        			case 2 :
		        			case 3 :
		        				section = 'second';
		        				break;
		        			case 4 :
		        			case 5 :
		        				section = 'third';
		        				break;

	        			}
	        			if(val){
	        				if( ! MA.isValidDate(val)){
	        					if(index < 6){
	        						msg += '\r\nThe date value you entered for the ' + $(this).parent('label').text().replace(/<.*?>|[^a-z]/ig, '') + ' field in the ' + section + ' carrier section is not valid! ' + MA.dateMinWarning;;
	        					}
	        					else{
	        						msg += '\r\nThe date value you entered for the ' + $(this).parent('label').text().replace(/<.*?>|[^a-z]/ig, '') + ' field in the period without coverage section is not valid! ' + MA.dateMinWarning;
	        					}
	        				}
	        			}
	        		})
	        		
	        		if(msg){
	        			alert(msg);
	        			return false;
	        		}
	        		
	        		return true;
	            }
	    }
	    ,
	    {
	        title: 'Claims History and Retroactive Coverage',
	        validation:
	            function(ctx){
	               msg = '';
	                $('.date_picker', ctx).each(function(index){
	        			var val = $(this).val();
	        			if(val){
	        				if( ! MA.isValidDate(val)){
	        					msg += 'The date value you entered for the Date field in the Executed on section is invalid! ' + MA.dateMinWarning;
	        				}
	        			}
	        		})
	        		
	        		if(msg){
	        			alert(msg);
	        			return false;
	        		}
	        		
	        		return true;
	            }
	    }
	    ,
	    {
	        title: 'References',
	        validation:
	            function(ctx){
	                //nothing to validate
	                return true;
	            }
	    }
	    ,
	    {
	        title: 'Representations and Warranties',
	        validation:
	            function(ctx){
	                //nothing to validate
	                return true;
	            }
	    }
	    ,
	    {
	        title: 'Upload Documents',
	        validation:
	            function(ctx){
	                //nothing to validate
	                return true;
	            }
	    }
	    ,
	    {
	        title: 'Thank You!',
	        validation:
	            function(ctx){
	                //nothing to validate
	                return true;
	            }
	    }
	]

}
