// prepare the form when the DOM is ready 
$(document).ready(function() {
	
// for error messages dialog
$("body").append("<div id='error_messages'></div>");

    var options = {
        //target: '#output1',
        // target element(s) to be updated with server response 
        beforeSubmit: before_submit,
        success: submit_success_callbacks, // post-submit callback 
        semantic: true,
        // other available options: 
        //url:       url         // override for form's 'action' attribute 
        //type:      type        // 'get' or 'post', override for form's 'method' attribute 
        dataType: 'json',        // 'xml', 'script', or 'json' (expected server response type) 
        iframe: true
        //clearForm: true        // clear all form fields after successful submit 
        //resetForm: true        // reset the form after successful submit 
        // $.ajax options can be used here too, for example: 
        //timeout:   3000 
    };

    // bind form using 'ajaxForm' 
    $('#myForm').ajaxForm(options);
});

// pre-submit callback 
function showRequest(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); 
    // jqForm is a jQuery object encapsulating the form element.  To access the 
    // DOM element for the form do this: 
    // var formElement = jqForm[0]; 
    //alert('About to submit: \n\n' + queryString); 
    // here we could return false to prevent the form from being submitted; 
    // returning anything other than false will allow the form submit to continue 
    return true;
}

// post-submit callback 
function showResponse(responseText, statusText) {
    // for normal html responses, the first argument to the success callback 
    // is the XMLHttpRequest object's responseText property 
    // if the ajaxForm method was passed an Options Object with the dataType 
    // property set to 'xml' then the first argument to the success callback 
    // is the XMLHttpRequest object's responseXML property 
    // if the ajaxForm method was passed an Options Object with the dataType 
    // property set to 'json' then the first argument to the success callback 
    // is the json data object returned by the server 
    alert('status: ' + statusText + '\n\nresponseText: \n' + responseText + '\n\nThe output div should have already been updated with the responseText.');
}

before_submit = function() {
    $("#view_reports").attr("value", "Creating Reports").attr("disabled", "disabled");
    $("#submit_message").html('<img id="submit_loading" src="images/loading.gif">');
}

submit_success_callbacks = function(data) {

if($('#report_mode').attr("value") == "sample") {
    pageTracker._trackPageview("/sample_reports_requested");	
} else {
	pageTracker._trackPageview("/reports_requested");
}



function show_reports(){
	$("#output1").html(data.html_output);
	// for view reports button
	if ($("#file").attr("value") != '') {
	$("#view_reports").attr("value", "View Reports").attr("disabled", "");
	}
	never_submitted = 1;
	if (fb_errors = '') {
		$("#submit_message").html("<span id='submit_modified_message'>Reports Created Successfully</span>").css("color", "green");
		$("#submit_message").fadeIn("slow");
	} else {
		$("#submit_message").html("");
	}
	$("#view_reports").attr("value", "Update Reports");
	
	// for gantt chart column widths
	gantt_day_cells = $(".gantt_day_cell").length;
	gantt_day_cells_width = 100 / gantt_day_cells + '%';
	$(".gantt_day_cell").css("width", gantt_day_cells_width);
	
	$(".gantt_event_name_cell:last").css("padding-bottom", "8px");
	
	//$(".gantt_labels_bars tr:hover").css("background-color","#ccc");
	// for gantt tooltips
	$('.bar').tooltip({
		track: true,
		delay: 0,
		showURL: false,
		showBody: " - ",
		fade: 250,
		extraClass: "gantt_tooltip"
	});
	
	// try this after next jquery ui release
	/* $('#report_tabs > ul').tabs({
	 fx: {
	 height: 'toggle', opacity: 'toggle', duration: 'fast'
	 }
	 }).tabs('equalize'); */
	$('#report_tabs > ul').tabs({
		selected: 0
	});
	
	// jumping tabs hack
	var gantt_height = $("#gantt_chart").height();
	// var output_1_height = (gantt_height * 3);
	var output_1_height = $("#tasks_per_boss_report").height();
	$("#output1").css("height", output_1_height);
	
	// for submit to google ajax form
	var options = {
		target: '#google_calendar_output' // target element(s) to be updated with server response 
		// beforeSubmit:  showRequest,  // pre-submit callback 
		//success:       start_tooltips_and_tabs  // post-submit callback 
		// other available options: 
		//url:       url         // override for form's 'action' attribute 
		//type:      type        // 'get' or 'post', override for form's 'method' attribute 
		//dataType:  null        // 'xml', 'script', or 'json' (expected server response type) 
		//clearForm: true        // clear all form fields after successful submit 
		//resetForm: true        // reset the form after successful submit 
		// $.ajax options can be used here too, for example: 
		//timeout:   3000 
	};
	
	//$('#send_to_google_calendar').ajaxForm(options);
	
	// for sample button - switch form back to "standard" mode
	
	$('#report_mode').attr("value", "standard");
	
	// fix gant bars for ie7
	
	$("#bar_wrapper").css("position", "relative");
	
} // show_reports

var fb_critical_errors = false;
var fb_errors = '';
// read json output
// create error messages
// update critical_errors as needed

var validation_obj = data.validation_obj;
//console.log(validation_obj);

// missing data errors

fb_missing_data_errors = '';

if (validation_obj.missing_data.missing_column_headers != "") {
	fb_missing_data_errors += "<p><strong>Reqired column header(s)</strong> are missing from your ToDo list: " + validation_obj.missing_data.missing_column_headers + "</p>";
    fb_critical_errors = true;
}

// only report missing data if all column headers are present

if (validation_obj.missing_data.missing_column_headers == "") {
	if (validation_obj.missing_data.task != "") {
		fb_missing_data_errors += "<p><strong>Task Name</strong> is missing on lines " + validation_obj.missing_data.task + "</p>";
	}
	
	if (validation_obj.missing_data.hours != "") {
		fb_missing_data_errors += "<p><strong>Hours</strong> is missing on lines " + validation_obj.missing_data.hours + "</p>";
		fb_critical_errors = true;
	}
	
	if (validation_obj.missing_data.description != "") {
		fb_missing_data_errors += "<p><strong>Description</strong> is missing on lines " + validation_obj.missing_data.description + "</p>";
	}
	
	if (validation_obj.missing_data.boss != "") {
		fb_missing_data_errors += "<p><strong>Boss Name</strong> is missing on lines " + validation_obj.missing_data.boss + "</p>";
	}
}
// file errors

fb_file_errors = '';

if (validation_obj.the_file.provided != "true") {
	fb_file_errors += "<p>There was no file specified in <strong>Step 1</strong></p>";
	fb_critical_errors = true;
}
if (validation_obj.the_file.provided == "true") {
	if (validation_obj.the_file.error_free != "true") {
		fb_file_errors += "<p>There was an <strong>error</strong> reading your file</p>";
		fb_critical_errors = true;
	}
}
// only check the rest of the file reqirements if the file was provided & no errors

if (validation_obj.the_file.provided == "true" && validation_obj.the_file.error_free == "true") {
	if (validation_obj.the_file.csv != "true") {
		fb_file_errors += "<p>The file is not in the required <strong>CSV format</strong></p>";
		fb_critical_errors = true;
	}
	
	if (validation_obj.the_file.file_size != "true") {
		fb_file_errors += "<p>The file exceeds the <strong>maximum file size</strong> of 200k</p>";
		fb_critical_errors = true;
	}
}

// reqired settings errors

var missing_reqired_settings = "";

if (validation_obj.missing_required_settings.days_worked == "7") {
	missing_reqired_settings = "Days That You Work";
	fb_critical_errors = true;
}

if (validation_obj.missing_required_settings.hours_per_day == "") {
	fb_critical_errors = true;
	if (missing_reqired_settings = "") {
		missing_required_settings = "Hours Per Day";
	} else {
		missing_required_settings += ", Hours Per Day";
	}
}

// add header message if errors exist

if (fb_file_errors != '' || fb_file_errors != '' || fb_missing_data_errors != '') {
		pageTracker._trackPageview("/errors"); 
	if (fb_critical_errors == true) {
		fb_errors += "<p class='fb_error_header'>Please correct the below error(s) and try again.</p>";
			pageTracker._trackPageview("/critical_errors"); 
	}
	else {
		fb_errors += "<p class='fb_error_header'>Your Todo List is not complete.</p>";
			pageTracker._trackPageview("/non_critical_errors"); 
	}
}

fb_errors += fb_file_errors;
if (missing_reqired_settings != '') {
	fb_errors += "These required settings were not entered: " + missing_reqired_settings;
}
if(fb_file_errors == ''){
	fb_errors += fb_missing_data_errors;
}

$('#error_messages').html(fb_errors);

if (fb_errors == '') {
	pageTracker._trackPageview("/no_errors"); 
	show_reports();
} else if(fb_critical_errors == false) {

// show dialog for error messages if no critical errors

	$("#error_messages").dialog({
        buttons: {
            'Show Reports Anyway': function() {
             show_reports();
			 $(this).dialog("close");
			 $("#view_reports").attr("value", "Update Reports").attr("disabled", "");
			 dialog_button_allow();
            },
            'Cancel': function() { 
			$(this).dialog("close");
			dialog_button_allow();
			}
		},
			close: function(event,ui) { 
				$("#submit_message").html("");
			    $("#view_reports").attr("value", "View Reports").attr("disabled", "");
		 },
		autoOpen: false,
        modal: true,
        title: "Error Messages",
        height: "230px",
        width: "415px",
        overlay: {
            opacity: 0.75,
            background: "black"
        }
    });
	
	
$("#error_messages").dialog('open');
	
} else if (fb_critical_errors == true){
	
// show dialog for error messages if critical errors exist
	
	$("#error_messages").dialog({
        buttons: {
            'Close': function() { 
			$(this).dialog("close");
			dialog_button_allow();
			}
		},
            close: function(event,ui) { 
				$("#submit_message").html("");
			    $("#view_reports").attr("value", "View Reports").attr("disabled", "");
		 },
		autoOpen: false,
        modal: true,
        title: "Error Messages",
        height: "230px",
        width: "415px",
        overlay: {
            opacity: 0.75,
            background: "black"
        }
    });

$("#error_messages").dialog('open');
}

} // function