//Set the class that is used for errors on input fields. No periods!
var error_class = 'error_field';

//Popup code
function js_popup(url,width,height) {
	if(!width){width=300}
	if(!height){height=150}
	new_window=window.open(url,'name','height='+height+',width='+width);
	if(window.focus) {new_window.focus()}
	return false;
}



$(function(){ //Start up jQuery


	var new_appeal_html = $('#add-appeal').html();
	
	/* Someone manually put them into the live form, so commenting this out to rid of dupe *s. */
	//$('.required').siblings('label,legend').prepend('<span class="required_marker">*</span>');
	
	//Selects the required text field after selecting a radio or checkbox
	$('input[type=radio]').change(function(){
		$(this).siblings('input[type=text]:first').focus();
	});
	$('input[type=checkbox]').change(function(){
		if ($(this).attr('checked')) {
			$(this).siblings('input[type=text]:first').focus();
		}
	});

	//Selects the radio after selecting a required text field
	$('input[type=text]').focus(function(){
		$(this).siblings('input[type=radio]').attr('checked','checked');
		var checked = $(this).siblings('input[type=checkbox]').attr('checked');
		$(this).siblings('input[type=checkbox]').attr('checked','checked');
	});
	
	/* Between here and the "/add_appeal" comments is the adding and validation of the #add-appeals section */
		$('a[href=#add_appeal]').click(function(){
			$(this).before('<div class="new-appeal"><h2>Additional appeal item</h2>'+new_appeal_html+'<br><a href="#delete-appeal">Delete</a><br></div>');
			reindex();
			return false;
		});
	
		$('a[href=#delete-appeal]').live('click',function(){
			$(this).parent().remove();
			return false;
		});
		/* /add_appeal */
	
		/* Between here and the "/residential" comments is validation for building permits and residential options */
		//Caching commonly used objects
		//var $f_residential = $('#f-residential');
		//var $f_building = $('#f-Building');

	
		//Hide the residentual option at the start, if its not selected (e.g. a soft refresh possibly)
		//$('input[name=APP_TYPE]:checked').val() !== $f_building.val() ?  $f_residential.parent().css('display','none') : null;
	
		//$('input[name=APP_TYPE]').change(function(){
			//If the value is NOT the building type then hide the residential option again and iucheck it
			//If it IS the building type then show the residential option.
			//$(this).val() !== $f_building.val() ? $f_residential.removeAttr('checked').parent().fadeOut() : $f_residential.parent().fadeIn();
		//});
	
		//$('input[name=APPEAL_TYPES]').change(function(){
			//If the residential option is chosen, and then the building option is changed then
			//uncheck, and hide the residential option again
			//$(this).val() == $f_residential.val() && $('input[name=APP_TYPE]:checked').val() !== $f_building.val() ? $(this).removeAttr('checked').parent().fadeOut() : null;
		//});
	/* /residential */
	
	//All the error checking takes placed inside of the submit event
	$('#bds-form').submit(function(){
		//On submit erase the old error list
		$('#error_wrap').remove();
		
		//The array that holds all the errors.
		error_code = new Array();
		
		//An error checking function. Checks to make sure text and radios are filled out.
		//For radios that have text fields as siblings, it makes sure those are filled out as well.
		//NOTE: checkboxes are not checked for!
		function error_check(selector,error){
			if($(selector).attr('type') == 'radio' || $(selector).attr('type') == 'checkbox' ){
				$(selector+':checked').val() == undefined || $(selector+':checked').siblings('[type=text]').val() == '' ? error_code.push([selector+':visible',error]) : $(selector+':checked').val() == undefined ? error_code.push([selector+':visible',error]) : null;
			}
			else { //This checks items such as text and textarea fields
				$(selector).val() == '' ? error_code.push([selector,error]) : null;
			}
		}
		//checking for blanks on the required fields and setting the error messages to display (the 2nd value)
		//It then saves it to the error array.
		error_check('[name=APP_TYPE]','Select a type of appeal.');
		error_check('[name=APPEAL_TYPES]','Choose a project type.');
		error_check('[name=APPEAL]','Select what this appeal involves.');
		error_check('#f-structure','Enter proposed use of structure.');
		error_check('[name=APP_CHOICES]','Enter your application/permit number.');
		error_check('#f-streetaddress','Enter your projects\'s street address.');
		error_check('#f-ownername','Enter your projects\'s owner\'s name.');
		error_check('#f-owneraddr','Enter your projects\'s owner\'s address.');
		error_check('#f-stories','Enter the number of stories.');
		error_check('#f-occgroup','Enter occupancy group.');
		error_check('#f-constype','Enter construction type.');
		error_check('#f-examiner','Enter plans examiner/inspector.');
		error_check('[name=FIRE]','Choose a fire sprinkler option.');
		error_check('f-examiner','Enter the plans examiner/inspector.');
		error_check('[name=payoption]','Choose a payment option.')
		error_check('[name=planoption]','Choose a plan submittal option.')
		error_check('#f-appname','Enter an appellant name.');
		error_check('#f-appaddress','Enter an appellant address.');
		error_check('#f-city2','Enter an appellant city.');
		error_check('#f-phone1','Enter in your appellant email');
		error_check('#f-state2','Enter an appellant state.');
		error_check('#f-zip','Enter an appellant zip');
		error_check('#f-phone','Enter an appellant phone number.');
		error_check('.f-codesection','Enter a code section.');
		error_check('[name*=_REQUIRES]','Fill in the requires field');
		error_check('[name*=_PROPOSED_DESIGN]','Describe the alternate methods and/or materials of construction to be used or that exist.');
		error_check('[name*=_ALTERNATE]','Describe why the alternate is required and how it will provide equivalent health, accessibility, structural capacity, energy conservation, life safety or fire protection to what the code requires.');
		
		// Check for proper extension and valid upload file
		if ($('input[name=planoption]:checked').val() == 'pdf') {
			var numFiles = 0;
			$('[id*=f-planoption_file]').each(function() {
				if ($(this).val()) {
					numFiles++;
					if ($(this).get(0).files) {
						filename = $(this).get(0).files[0].fileName;
						filename.search(/\.pdf/) > 0 ? numFiles : error_code.push(['#' + $(this).attr('id'), 'You can only upload .pdf files.']);
					}
				}
			});
			
			if (numFiles == 0) {
				error_code.push(['#f-pdf', 'You must upload at least one .pdf file.']);
			}
		}
		
		//If there is at least 1 error, run the following code...
		if(error_code.length > 0){
			//Bring you to the top to see the errors
			$('body,html').animate({scrollTop:0},1000,function(){$(window).scrollTop(0)});
			//Create the DOM structure to contain the errors for the user to see.
			$('.new_error_container').after('<div id="error_wrap"><p id="error_title">Errors:</p><ul id="error_msgs"></ul></div>');
			//Loops through each error
			for(x in error_code){
				//This adds each error to the list, and also creates an anchor to the corresponding error location
				$('#error_msgs').append('<li><a href="#'+$(error_code[x][0]).attr('id')+'">'+error_code[x][1]+'</a></li>');
				//If the error is an item that took place inside of an <li>, such as a radio...
				if($(error_code[x][0]).parent('li').length > 0){
					//Then add the error to the <li>
					$(error_code[x][0]).parent().addClass(error_class);
				}
				else{
					//Otherwise just add it to it's self
					$(error_code[x][0]).addClass(error_class);
				}
			}
			//And if there are any errors, do not submit the form!
			return false;
		}
	});
	
	//Removes the error colors/classes when the user focuses on errored out elements for user feedback
	$('.'+error_class + ','+'.'+error_class + ' input').live('focus',function(){
		console.log('remove error');
		//If the error is on a parent item of actual error item, such as a radio in an <li>...
		//Remove the error, and all the sibling errors as well, e.g. all <li>s
		//Otherwise just remove the error from itself.
		$(this).removeClass(error_class);
		$(this).parents('.'+error_class).removeClass(error_class);
		$(this).filter('[type=radio],input[type=checkbox]').length > 0 ? $(this).removeClass(error_class).parents().siblings().removeClass(error_class) : $(this).removeClass(error_class);
		$(this).siblings('[type=radio],input[type=checkbox]').length > 0 ? $(this).removeClass(error_class).parents().siblings().removeClass(error_class) : $(this).removeClass(error_class);
	});

	
	// Plan Submittal Options
	$('input[name=planoption]').click(function() {
		$('.planoption').slideUp('fast');
		$(this).siblings('.planoption').slideDown('fast');
	});
	
	$('.planoption').hide();
	$('input[name=planoption]:checked').click();
	
	// Add additional PDF upload field
	$('#add-pdf').click(function() {
		node = $('.pdf-file:last').clone();
		
		// Update counter in id and name attributes
		nodeInput = $(node).find('input[type=file]');
		id = $(nodeInput).attr('id');
		matches = id.match(/(f-planoption_file)(\d+)/);
		str = matches[1];
		num = matches[2];
		num++;
		
		$(nodeInput).attr('id', str + num);
		$(nodeInput).attr('name', str + num);	// This doesn't work in IE -- see workaround below
		$(nodeInput).parent().html($(nodeInput).parent().html()); // Use innerHTML reset trick to clear input field
		$(node).insertAfter('.pdf-file:last');

		// Workaround for setting name attribute in IE (http://webbugtrack.blogspot.com/2008/03/bug-240-setattribute-name-is-half.html)
		if ($.browser.msie) {
			nodeInput = $(node).find('input[type=file]');
			$(nodeInput).get(0).setAttribute('name', str + num);
		}
		
		return false;
	});
	
	$('.removeFile').live("click", function() {
		if ($('.pdf-file').length > 1) {
			$(this).parent().remove();
		} else {
			alert("You must upload at least one file.");
		}
		
		return false;
	});
});
