/*
	functions.forms.js
	JQuery Form Functions
	Creator: Matt Kircher
*/

function addNotificationBar(mssg){
	
	var message = $('<div class="notification_bar"><p>'+mssg+'&nbsp;&nbsp;&nbsp;<a class="close_notifier" href="#">ok</a></p></div>');
	$(message).find('a').bind('click', function(){ 
		$('.notification_bar').css({ opacity:0.9 }).slideUp(400, function(){ 
			$('.notification_bar').remove(); 
		});
		return false;
	}).end().hide().prependTo($('body')).slideDown(400);
	return true;
}

function validateEmail(e){
	var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	return filter.test($.trim(e));
}

function setupForm(){
	$('form').each(function(){
		
		//help IE 6 & 7
		if(!$.browser.boxModel){
			$('form dd').each(function(){
				$(this).prev('dt').height($(this).height());
			});
		}
		
		//form fieldset side links
		$('#sub-content').append('<hr /><h4 class="subhead">'+$('#main-content :header:first').text()+'</h4><ul class="small_project_list"></ul>');
		$('form fieldset').each(function(index){
			$(this).attr('id', 'section'+index);
			
			var text = $(this).find('legend span').text();
			$('#sub-content .small_project_list').append('<li><a href="#section'+index+'">'+text+'</a></li>');
			
			$(this).find('legend span').prepend('<a href="#content">Back to the top</a>');
		});		
	});
}

function validateForm(f){
	
	var specificForm = ($.trim(f) == "")?'form':f;
	
	//setup valid object
	var valid = { status:true, response:'', element:null };
	
	//remove classes, go through and check for non-values
	$(specificForm+' .select_required_attention').remove();
	$(specificForm+' .required')
	.removeClass('required_attention')
	.each(function(){
		if(($(this).val() == "" || $(this).val() == null)){
			$(this).addClass('required_attention');
			valid.status = false;
			valid.response = 'One or more required fields have not been completed. Please complete them and resubmit the form.';
			if(valid.element == null){ valid.element = $(this); }
			
			if($(this).get(0).nodeName == "SELECT"){
				$(this).after('<span class="select_required_attention">&lsaquo;&mdash;</span>');
			}
		}
	});
	
	//if email is not of the form 'name@email.com', don't validate
	if(valid.status){
		$(specificForm+' input.required[name="email"]').each(function(){				
			if(!validateEmail($(this).val())){
				$(this).addClass('required_attention');
				valid.status = false;
				valid.response = 'Please supply a valid email address.';
				valid.element = $(this);
			}
		});
	}
	
	//display alert, focus on first non-valued field
	if(!valid.status){ alert(valid.response); $(valid.element).focus(); }
	return valid.status;
}

function addLoading(form, loadingMssg){
	
	var loadingHTML = $('<div class="loading_bar">'+loadingMssg+'</div>');
	
	$(form).hide();
	$('#sub-content > *').hide();
	resizeContentDivs();
	$('#main-content').append(loadingHTML);
}

function removeLoading(){
	$('.loading_bar').remove();
}

function setupContactForm(){
	
	setupForm();
		
	// prepare Options Object 
	var options = {
		type:		'POST',
		url:        	'includes/forms.process.php?action=submitContactForm',
		dataType:	'json',
		resetForm:	true,
		beforeSubmit: function(){
				
				if(validateForm('#contactForm')){
					addLoading('#contactForm', 'Sending your message...');
					return true;					
				} else {
					return false;	
				}
		},
		success:    	function(data){
			
			removeLoading();
			addNotificationBar(data.status_message);				
			if(data.status == "OK"){
				$('#contactForm').remove();
				$('#main-content').append(data.returnHTML);
			} else {
				$('#contactForm').show();
				resizeContentDivs();
			}
		}
	}; 
	
	// pass options to ajaxForm 
	$('#contactForm').ajaxForm(options);
}

function setupResumeSubmissionForm(){
	
	setupForm();
		
	// prepare Options Object 
	var options = {
		type:		'POST',
		url:        	'includes/forms.process.php?action=submitResumeForm',
		dataType:	'json',
		resetForm:	true,
		beforeSubmit: function(){
				
				if(validateForm('#resumeSubmissionForm')){
					addLoading('#resumeSubmissionForm', 'Submitting your resume...');
					return true;					
				} else {
					return false;	
				}
		},
		success:    	function(data){
			
			removeLoading();
			addNotificationBar(data.status_message);				
			if(data.status == "OK"){
				$('#resumeSubmissionForm').remove();
				$('#main-content').append(data.returnHTML);
			} else {
				$('#resumeSubmissionForm').show();
				$('#sub-content > *').show();
				resizeContentDivs();
			}
		}
	}; 
	
	// pass options to ajaxForm 
	$('#resumeSubmissionForm').ajaxForm(options);
}

function setupPrequalificationForm(){
	
	setupForm();
		
	// prepare Options Object 
	var options = {
		type:		'POST',
		url:        	'includes/forms.process.php?action=submitPrequalificationForm',
		dataType:	'json',
		resetForm:	true,
		beforeSubmit: function(){
				
				if(validateForm('#prequalificationForm')){
					addLoading('#prequalificationForm', 'Submitting your prequalification information...');
					return true;					
				} else {
					return false;	
				}
		},
		success:    	function(data){
			
			removeLoading();
			addNotificationBar(data.status_message);				
			if(data.status == "OK"){
				$('#prequalificationForm').remove();
				$('#main-content').append(data.returnHTML);
			} else {
				$('#prequalificationForm').show();
				resizeContentDivs();
			}
		}
	}; 
	
	// pass options to ajaxForm 
	$('#prequalificationForm').ajaxForm(options);
}

function setupBidRoomCheckinForm(){
	
	// prepare Options Object 
	var options = {
		type:		'POST',
		url:        	'includes/forms.process.php?action=submitBidRoomCheckInInfo',
		dataType:	'json',
		resetForm:	true,
		beforeSubmit: function(){
				
				if(validateForm('#bidRoomCheckinForm')){
					return true;					
				} else {
					return false;	
				}
		},
		success:    	function(data){
				
			if(data.status == "OK"){
				document.location = 'subcontractors-bid-room.php';
			} else {
				alert(data.status_message);
			}
		}
	}; 
	
	// pass options to ajaxForm 
	$('#bidRoomCheckinForm').ajaxForm(options);
}


// ==========================================================================================================
// CMS: CMS ACCESS
// ==========================================================================================================

function setupCMSAccessForm(){
	
	$('#newUsername, #newPassword').alphanumeric();
	
	// prepare Options Object 
	var options = {
		type:		'POST',
		url:        	'includes/cms.process.php?action=updateCMSAccess',
		dataType:	'json',
		resetForm:	true,
		beforeSubmit: function(){
			
				if(validateForm('#cmsCMSAccessForm')){
					return true;					
				} else {
					return false;	
				}
		},
		success:    	function(data){
			
			if(data.status == "OK"){
				addNotificationBar(data.status_message);
				$('#currentUsername').attr('value', data.vars['newUsername']);
			} else {
				if(data.status == "FAILED_CMS_HACK_ATTEMPT"){
					document.location = 'logout.php';
				} else {
					alert(data.status_message);
				}
			}
		}
	}; 
	
	// pass options to ajaxForm 
	$('#cmsCMSAccessForm').ajaxForm(options);
}

// ==========================================================================================================
// CMS: BID ROOM
// ==========================================================================================================

function setupBidRoomForm(){
	
	$('#cmsBidsForm tbody > tr').each(function(){
		var id = $(this).find('input[name="nId[]"]').val();
		
		//deactivate the activation check box if marked for deletion
		$(this).find('.delete_checkbox').click(function(){
			if($(this).is(':checked')){
				$(this).parent().parent().find('.activate_checkbox').attr('checked', false);
			}
		});
		
		//deactivate the delete checkbox if marked for activation
		$(this).find('.activate_checkbox').click(function(){
			if($(this).is(':checked')){
				$(this).parent().parent().find('.delete_checkbox').attr('checked', false);
			}
		});
		
		//set edit link buttons
		$(this).find('.edit_button').click(function(){
			document.location = "cms_pride_bid_room_listing.php?action=edit&id="+id;
		});
	});
	
	// prepare Options Object 
	var options = {
		type:		'POST',
		url:        	'includes/cms.process.php?action=updateBidRoomListings',
		dataType:	'json',
		resetForm:	false,
		beforeSubmit: function(){
			
			var m = (!$('#cmsBidsForm .delete_checkbox:checked').length)?"Are you sure you want to UPDATE your projects?":"Are you sure you want to UPDATE and DELETE selected projects?\n\nNOTE: Deleting a project will remove all files associated with that project as well.";
			return(confirm(m));
		},
		success:    	function(data){
			
			if(data.status == "OK"){
				
				//remove deleted
				$('#cmsBidsForm .delete_checkbox').each(function(){
					if($(this).is(':checked')){
						$(this).parent().parent().remove();
					}
				});
				
				$('#main-content, #sub-content').removeAttr('style');
				$('#content > div').equalHeights();
				
				addNotificationBar(data.status_message);				
			} else {
				alert(data.status_message);
			}
		}
	}; 
	
	// pass options to ajaxForm 
	$('#cmsBidsForm').ajaxForm(options);
}

function setupBidRoomListingAddForm(){
	
	// prepare Options Object 
	var options = {
		type:		'POST',
		url:        	'includes/cms.process.php?action=addBidRoomListing',
		dataType:	'json',
		resetForm:	false,
		beforeSubmit: function(){
			
				if(validateForm('#cmsBidListingForm')){
					return true;					
				} else {
					return false;	
				}
		},
		success:    	function(data){
			
			if(data.status == "OK"){
				
				var m = confirm("Your project has been added successfully!\n\n- Click OK to edit and add files to this project\n- Click CANCEL to return to the project listings page");
				
				if(m){
					document.location = "cms_pride_bid_room_listing.php?action=edit&id="+data.project_id;
				} else {
					document.location = "cms_pride_bid_room.php";
				}
			} else {
				alert(data.status_message);
			}
		}
	}; 
	
	// pass options to ajaxForm 
	$('#cmsBidListingForm').ajaxForm(options);
}

function setupBidRoomListingAddFileForm(){
	
	// prepare Options Object 
	var options = {
		type:		'POST',
		url:        	'includes/cms.process.php?action=addBidRoomProjectFile',
		dataType:	'json',
		resetForm:	true,
		beforeSubmit: function(){
				
				$('#cmsBidListingFileUploadForm #projectFile').attr('readonly', 'readonly');
				$('#cmsBidListingFileUploadForm .submit_bar button').hide();
				$('#cmsBidListingFileUploadForm .submit_bar').append('<img src="../images/loadingAnimation.gif" align="right" />');
				
				if(validateForm('#cmsBidListingFileUploadForm')){
					return true;
				} else {
					return false;	
				}
		},
		success:    	function(data){
			
			$('#cmsBidListingFileUploadForm #projectFile').removeAttr('readonly');
			$('#cmsBidListingFileUploadForm .submit_bar img').remove();
			$('#cmsBidListingFileUploadForm .submit_bar button').show();
			
			if(data.status == "OK"){
				addNotificationBar(data.status_message);
				
				//add row
				var newRow = '<tr>'
							+'<td valign="top" align="center">'
								+'<input type="hidden" name="fileId[]" value="'+data.vars['newFileId']+'" />'
								+'<input type="checkbox" class="activate_checkbox" name="bActive[]" value="'+data.vars['newFileId']+'" checked="checked" /></td>'
							+'<td valign="top" align="center"><input type="checkbox" class="delete_checkbox" name="deleteFile[]" value="'+data.vars['newFileId']+'" /></td>'
							+'<td valign="top"><a href="../'+data.vars['newFileURI']+'" target="_blank">'+data.vars['newFileTitle']+'</a></td>'
							+'<td valign="top">'
								+'<strong>'+data.vars['newUploadedDate']+'</strong><br />'
								+'<span class="note">'+data.vars['newUploadedTime']+'</span>'
							+'</td>'
							+'<td valign="top">'+data.vars['newFileCategory']+'</td>'
						+'</tr>';
						
				$('#cmsBidListingForm tbody').append($(newRow));
				
				//add new category, if available
				var add = 1;
				$('#existingCategories optgroup option').each(function(){
					//check if it exists already
					if($(this).val() == data.vars['newFileCategory']){
						add = 0;	
					}
				});
				if(add){
					//add if its not there
					$('#existingCategories optgroup').append('<option value="'+data.vars['newFileCategory']+'">'+data.vars['newFileCategory']+'</option>');
				}
				
				$('#main-content, #sub-content').removeAttr('style');
				$('#content > div').equalHeights();
				
				setupBidRoomListingEditForm();
				
			} else {
				alert(data.status_message);
			}
		}
	}; 
	
	// pass options to ajaxForm 
	$('#cmsBidListingFileUploadForm').ajaxForm(options);
}

function setupBidRoomListingEditForm(){
	
	$('#cmsBidListingForm tbody > tr').each(function(){
		var id = $(this).find('input[name="fileId[]"]').val();
		
		//deactivate the activation check box if marked for deletion
		$(this).find('.delete_checkbox').click(function(){
			if($(this).is(':checked')){
				$(this).parent().parent().find('.activate_checkbox').attr('checked', false);
			}
		});
		
		//deactivate the delete checkbox if marked for activation
		$(this).find('.activate_checkbox').click(function(){
			if($(this).is(':checked')){
				$(this).parent().parent().find('.delete_checkbox').attr('checked', false);
			}
		});
	});
	
	// prepare Options Object 
	var options = {
		type:		'POST',
		url:        	'includes/cms.process.php?action=editBidRoomListing',
		dataType:	'json',
		resetForm:	false,
		beforeSubmit: function(){
			
				if(validateForm('#cmsBidListingForm')){
					var m = (!$('#cmsBidListingForm .delete_checkbox:checked').length)?"Are you sure you want to UPDATE your project attributes and files?":"Are you sure you want to UPDATE and DELETE selected project attributes and files?";
					return(confirm(m));
				} else {
					return false;	
				}
		},
		success:    	function(data){
			
			if(data.status == "OK"){
				
				//remove deleted
				$('#cmsBidListingForm .delete_checkbox').each(function(){
					if($(this).is(':checked')){
						$(this).parent().parent().remove();
					}
				});
				
				$('#main-content, #sub-content').removeAttr('style');
				$('#content > div').equalHeights();
				
				addNotificationBar(data.status_message);
				
			} else {
				alert(data.status_message);
			}
		}
	}; 
	
	// pass options to ajaxForm 
	$('#cmsBidListingForm').ajaxForm(options);
}
