  $(document).ready(function() {
	
	$('a[rel*=facebox]').facebox();
	
	var load_options = {
        success:       formLoad,  		// post-submit callback 
        // other available options: 
        url:       "dataPost.php",       // override for form's 'action' attribute 
        type:      "POST"		        // 'get' or 'post', override for form's 'method' attribute 
    }; 
	
	$('#main_data').ajaxSubmit(load_options); 
	
	var options_source = {
        beforeSubmit:  showRequestSource,  		// pre-submit callback 
        success:       showResponseSource,  		// post-submit callback 
        // other available options: 
        url:       "formPost.php",       // override for form's 'action' attribute 
        type:      "POST"		        // 'get' or 'post', override for form's 'method' attribute 
    }; 
	
	var options_dest = {
        beforeSubmit:  showRequestDest,  		// pre-submit callback 
        success:       showResponseDest,  		// post-submit callback 
        // other available options: 
        url:       "formPost.php",       // override for form's 'action' attribute 
        type:      "POST"		        // 'get' or 'post', override for form's 'method' attribute 
    }; 
 
	var options_data = { 
        beforeSubmit:  formValidate,  		// pre-submit callback 
        success:       formResponse,  		// post-submit callback 
        // other available options: 
        url:       "dataPost.php",       // override for form's 'action' attribute 
        type:      "POST"		        // 'get' or 'post', override for form's 'method' attribute 
    }; 
	
	var options_save = { 
	    beforeSubmit:   formValidate,  
		success:		formSaved,  		// post-submit callback 
        // other available options: 
        url:       "dataSave.php",       // override for form's 'action' attribute 
        type:      "POST"		        // 'get' or 'post', override for form's 'method' attribute 
    }; 
 
	$('a[rel*=clear]').click(function() {
		var clear_area = $(this).attr('href').replace("#","");
		
		$("input[@name='"+clear_area+"_source']").attr('checked', false);
		$("input[@name='"+clear_area+"_dest']").attr('checked', false);
		
		if (clear_area == "data_format") {
			$("input[@name='data_format_other_source']").val("");
			$("input[@name='data_format_other_dest']").val("");
		} else if (clear_area == "data_unique") {
			$("input[@name='"+clear_area+"_source']").val("");
			$("input[@name='"+clear_area+"_dest']").val("");
		}
		
		return false;
	});
 
	$("input[@name='data_format_other_source']").keydown(function() {
		$("input[@name='data_format_source']").attr('checked', false);
	});
 
	$("input[@name='data_format_source']").click(function(event) {
		$("input[@name='data_format_other_source']").val("");
	});
 
	$("input[@name='data_format_other_dest']").keydown(function() {
		$("input[@name='data_format_dest']").attr('checked', false);
	});
 
	$("input[@name='data_format_dest']").click(function(event) {
		$("input[@name='data_format_other_dest']").val("");
	});
	
	$("input[@name='data_limaccept'][@type='checkbox']").change(function() {
		if ($("input[@name='data_limaccept'][@type='checkbox']").attr("checked"))
			$("input[@name='data_limaccept'][@type='hidden']").val("true");
		else
			$("input[@name='data_limaccept'][@type='hidden']").val("false");
	});
	
	// bind to the form's submit event 
    $('#data_file_source').change(function() {
        // inside event callbacks 'this' is the DOM element so we first 
        // wrap it in a jQuery object and then invoke ajaxSubmit 
		$('#data_up_form_source').ajaxSubmit(options_source); 
 
        // !!! Important !!! 
        // always return false to prevent standard browser submit and page navigation 
        return false; 
    });

	// bind to the form's submit event 
    $('#data_file_dest').change(function() { 
        // inside event callbacks 'this' is the DOM element so we first 
        // wrap it in a jQuery object and then invoke ajaxSubmit 
		$('#data_up_form_dest').ajaxSubmit(options_dest); 
 
        // !!! Important !!! 
        // always return false to prevent standard browser submit and page navigation 
        return false; 
    });
	
	$("input[@name='data_save']").click(function() {
		// inside event callbacks 'this' is the DOM element so we first 
        // wrap it in a jQuery object and then invoke ajaxSubmit 
        $('#main_data').ajaxSubmit(options_save); 
 
        // !!! Important !!! 
        // always return false to prevent standard browser submit and page navigation 
        return false; 
	});
	
	$("input[@name='data_submit']").click(function() {
		// inside event callbacks 'this' is the DOM element so we first 
        // wrap it in a jQuery object and then invoke ajaxSubmit 
        $('#main_data').ajaxSubmit(options_data); 
 
        // !!! Important !!! 
        // always return false to prevent standard browser submit and page navigation 
        return false; 
	});
	
	$("textarea[@name='db_comments']").blur(function() {
		$("input[@name='db_comments']").val($("textarea[@name='db_comments']").val().replace(/<br \/>/g,'\n'));
	});
	
	$("div.information_cell").hover(
      function () {
        $(this).addClass('hovered');
      }, 
      function () {
        $(this).removeClass('hovered');
      }
    );
	
	$("li").hover(
	  function () {
        $(this).addClass('hovered');
	//	if (isReview) {
	//		$('a[rel*=clear]').hide();
	//	}
      }, 
      function () {
        $(this).removeClass('hovered');
      }
    );
	
  });
  
  	// pre-submit callback 
	function showRequestSource(formData, jqForm, options) {
	    // formData is an array; here we use $.param to convert it to a string to display it 
	    // but the form plugin does this for you automatically when it submits the data 
	    var queryString = $.param(formData); 
	    
	    $("input[@name='data_save']"); 
	//	$("input[@name='data_submit']").attr("disabled","disabled");
	 
	    $("#upload_start_source").html('<img src="/facebox/loading.gif" /><p>Please wait while the file uploads.</p>');
	 
	    return true; 
	} 
 
	// post-submit callback 
	function showResponseSource(responseText, statusText)  {
		$("#upload_start_source").html('');
	
	    $("input[@name='data_save']");
	//	$("input[@name='data_submit']").removeAttr("disabled");
	 
		if (statusText == "success")
		    
			$("#files_uploaded_source ul").append('<li name="files/'+$("input[@name='db_un_id']").val()+'/source/'+responseText+'"><a href="http://dx.pipetech.tv/files/'+$("input[@name='db_un_id']").val()+'/source/'+responseText+'" target="_blank">'+responseText+'</a> <a href="files/'+$("input[@name='db_un_id']").val()+'/source/'+responseText+'" onClick="delFile(event)" class="delete"><span>.</span></a></li>');
		else
			$("#files_uploaded_source").append('<li>File failed to upload.</li>');
	}
  
  // pre-submit callback 
	function showRequestDest(formData, jqForm, options) {
	    // formData is an array; here we use $.param to convert it to a string to display it 
	    // but the form plugin does this for you automatically when it submits the data 
	    var queryString = $.param(formData); 
	   
		$("input[@name='data_save']");
	//	$("input[@name='data_submit']").attr("disabled","disabled");
	 
	    $("#upload_start_dest").html('<img src="/facebox/loading.gif" /><p>Please wait while the file uploads.</p>');
	 
	    return true; 
	} 
 
	// post-submit callback 
	function showResponseDest(responseText, statusText)  {
		$("#upload_start_dest").html('');
	    
		$("input[@name='data_save']");
	//	$("input[@name='data_submit']").removeAttr("disabled");
	 
		if (statusText == "success")
			$("#files_uploaded_dest ul").append('<li name="files/'+$("input[@name='db_un_id']").val()+'/dest/'+responseText+'"><a href="http://dx.pipetech.tv/files/'+$("input[@name='db_un_id']").val()+'/dest/'+responseText+'" target="_blank">'+responseText+'</a> <a href="files/'+$("input[@name='db_un_id']").val()+'/dest/'+responseText+'" onClick="delFile(event)" class="delete"><span>.</span></a></li>');
		else
			$("#files_uploaded_dest").append('<li>File failed to upload.</li>');
	}
  
	function formResponse(responseText, statusText) {
	
	var arrResponse = responseText.split("|");
	
	if (arrResponse[0] == "SUBMIT_OK") {
	 	$("textarea[@name='db_comments']").val($("textarea[@name='db_comments']").val().replace(/<br \/>/g,'\n'));
		$("#body_content").html('<div class="information_cell"><h2>Data Exchange Information Collection Form</h2></div><div class="information_cell"><p><h4>Data submitted successfully. Please be patient while we process your request.</h4>Create another <a href="http://dx.pipetech.tv/">data exchange information form</a> or go back to<a href="http://www.pipetech.tv/services/?page=CustomDevelopment"> home page</a></p></div>');
	} else {
		$('#main_data').ajaxSubmit(options_save); 
		alert("An error occured while submitting the data, please try again.");
	}
	
	}
  
	var isReview=false;
  
	function formLoad(responseText, statusText) {
		
		var strResponse = "";
		
		if (responseText.substring(responseText.length-1,responseText.length) == '|') {
			strResponse = responseText.substring(0,responseText.length-1);
		} else {
			strResponse = responseText;
		}
			
		var arrResponse = strResponse.split("|");
		
		if (arrResponse[0] == "NEWID") {
			$("input[@name='db_un_id']").val(arrResponse[1]);
		} else if (arrResponse[0] == "OLDID" || arrResponse[0] == "REVIEW") {
			var name;
			var value;
			isReview=false;
			for (var i = 0; i < arrResponse.length;i++) {
					name = arrResponse[i];
					value = arrResponse[++i];
					switch (name) {
					
						case "contact_name":
						case "contact_company":
					    case "filename":
						case "data_format_other_source":
						case "data_format_other_dest":
						case "data_unique_source":
						case "data_unique_dest":
						if (value != "false")
							$("input[@name='"+name+"']").val(value);
						break;
						
						case "files_uploaded_source":
						case "files_uploaded_dest":
						if (value != "false")
							$("#"+name+" ul").html(value);
						break;
						
						case "OLDID":
							$("input[@name='db_un_id']").val(value);
						break;
						
						case "REVIEW":
							isReview = true;
						break;
						
						case "data_limaccept":
							if (value != "false") {
								$("input[@name='data_limaccept'][@type='hidden']").val("true");
								$("input[@name='data_limaccept'][@type='checkbox']").attr("checked","checked");
							} else {
								$("input[@name='data_limaccept'][@type='hidden']").val("false");
								$("input[@name='data_limaccept'][@type='checkbox']").removeAttr("checked");
							}
						break;
										
						case "db_comments":
							if (value != "false") {
								$("input[@name='db_comments']").val(value.replace(/<br \/>/g,'\n'));
								$("textarea[@name='db_comments']").val(value.replace(/<br \/>/g,'\n'));
							}
							break;
						
						default:
							if (value != "false") {
								$("input[@value='"+value+"'][@name='"+name+"']").attr("checked","checked");
								}
						break;
						
					}
				}
				if (isReview) {
				 
					$("input");
					$("input[@value='Lougout']");
					
					//$("input").attr("disabled", "disabled");
				//	$("input[@value='Lougout']").removeAttr("disabled");
				}
		} else {
			alert("The page did not load correctly. Please try again.");
		}
	
	}
		
	function formSaved(responseText, statusText) {
	
		var arrResponse = responseText.split("|");
	
		if (arrResponse[0] == "DATA_SAVED") {
			$("textarea[@name='db_comments']").val($("textarea[@name='db_comments']").val().replace(/<br \/>/g,'\n'));
			$("#body_content").html('<div class="information_cell"><h2>Data Exchange Information Collection Form</h2></div><div class="information_cell"><p><h4>Data submitted successfully. Please be patient while we process your request.</h4>Create another <a href="http://dx.pipetech.tv/">data exchange information form</a> or go back to<a href="http://www.pipetech.tv/services/?page=CustomDevelopment"> home page</a></p></div>');
		} else
			alert("An error while saving the data, please try again.");
	
	}
	
	var bolFormError;
	
	function formValidate() {
		$("div.information_cell b").css("color", "black");
		bolFormError = 0;

	
	    if ($("input[@name='filename']").val() == "") {
			$("div.information_cell:contains('Create the form name') b").css("color", "red");
			bolFormError++;
		}
		
		if ($("input[@name='data_format_other_source']").val() == "") {
			if (!$("input[@name='data_format_source'][@checked]").val()) {
				$("div.information_cell:contains('basic format') b").css("color", "red");
				bolFormError++;
			}
		}
			
		 if ($("input[@name='data_format_other_dest']").val() == "") {
			if (!$("input[@name='data_format_dest'][@checked]").val()) {
				$("div.information_cell:contains('basic format') b").css("color", "red");
				bolFormError++;
			}
		}
			
		if (!$("input[@name='data_assemblage_source'][@checked]").val() || !$("input[@name='data_assemblage_dest'][@checked]").val()) {
			$("div.information_cell:contains('assemblage of inspections') b").css("color", "red");
			bolFormError++;
		}
		
		if (!$("input[@name='data_manhole_source'][@checked]").val() || !$("input[@name='data_manhole_dest'][@checked]").val()) {
			$("div.information_cell:contains('naming convention') b").css("color", "red");
			bolFormError++;
		}
		
		if (!$("input[@name='data_continuous_source'][@checked]").val() || !$("input[@name='data_continuous_dest'][@checked]").val()) {
			$("div.information_cell:contains('logging method') b").css("color", "red");
			bolFormError++;
		}
		
		if (!$("input[@name='data_obstruction_source'][@checked]").val() || !$("input[@name='data_obstruction_dest'][@checked]").val()) {
			$("div.information_cell:contains('impassable obstruction') b").css("color", "red");
			bolFormError++;
		}
		
		if ($("input[@name='data_unique_source']").val() == "" || $("input[@name='data_unique_dest']").val() == "") {
			$("div.information_cell:contains('that define a unique') b").css("color", "red");
			bolFormError++;
		}
		
		if (!$("input[@name='data_schema_source'][@checked]").val() || !$("input[@name='data_schema_dest'][@checked]").val()) {
			$("div.information_cell:contains('Describe the database schema') b").css("color", "red");
			bolFormError++;
		}
		
		if (!$("input[@name='data_formatchange_source'][@checked]").val() || !$("input[@name='data_formatchange_dest'][@checked]").val()) {
			$("div.information_cell:contains('change over time') b").css("color", "red");
			bolFormError++;
		}
		
		if (!$("input[@name='data_name_source'][@checked]").val()) {
			$("div.information_cell:contains('Field Name Consistency') b").css("color", "red");
			bolFormError++;
		}
		
		if (!$("input[@name='data_linking_source'][@checked]").val()) {
			$("div.information_cell:contains('Inspection Media Linking') b").css("color", "red");
			bolFormError++;
		}
		
		if (!$("input[@name='data_videofile_source'][@checked]").val() || !$("input[@name='data_videofile_dest'][@checked]").val()) {
			$("div.information_cell:contains('Inspections have an associated video file') b").css("color", "red");
			bolFormError++;
		}
		
		if (!$("input[@name='data_limaccept'][@checked]").val()) {
			$("div.information_cell:contains('Data Exchange Limitations') b").css("color", "red");
			bolFormError++;
		}
		
		if (bolFormError > 0) {
			$("div.errorCell").html("<p>Please fill in all the fields that are red.</p>");
			return false;
		} else {
			$("div.errorCell").html("");
			window.scrollTo(0,0);
			return true;
		}
		
	}
	
	// Get the HTTP Object
	function getHTTPObject(){
		if (window.ActiveXObject) 
			return new ActiveXObject("Microsoft.XMLHTTP");
		else if (window.XMLHttpRequest) 
			return new XMLHttpRequest();
		else {
			alert("Your browser does not support AJAX.");
			return null;
		}
	}
	
	var xmlhttp = null;
	var strLink = "";
	var strSub = 'http://dx.pipetech.tv/?v=1';
	
	function delFile(e) {
		strLink = 'n';
		
		if (e.srcElement) {
			strLink = String(e.srcElement);
		} else if (e.target) {
			strLink = String(e.target);
		}
		
		strLink = strLink.substring(strSub.length);
		
		/* Set up the request */
	    xmlhttp =  getHTTPObject();
	    if (xmlhttp != null) {
			xmlhttp.open('GET', 'deleteFile.php?del_file='+strLink, true);
			xmlhttp.send(null);
			xmlhttp.onreadystatechange = remFile;
		}
		
		if (e && e.preventDefault) {
			e.preventDefault(); // DOM style
		} else {
			e.returnValue = false;
		}
		
		return false; // IE style
	
	}
	
	/* The callback function */
	function remFile() {
		if (xmlhttp.readyState == 4) {
			$("li[@name="+strLink+"]").remove();
		} else {
		}
	}
	
