// Define WSI object
var WSI={
	formname: null,
	errordiv: null

};

WSI.setProps=function(formName) {
	this.formname = formName;
	this.errordiv = formName + "error";
}

// define success callback
WSI.submitCallbackSuccess=function(obj){
	if (typeof obj === 'object'){
		// Process JSON object response
		if (obj.success){
			// Success
			$("form[name='"+WSI.formname+"']").find('fieldset').slideUp().end().find('h2').text(obj.success).fadeTo('normal', 1);
		} else if (obj.errors) {
			var errorMessage='';
			// Errors
			$("form[name='" + WSI.formname+"'] label").removeClass("error");

			$.each(obj.errors, function(err){
				// add error class to field
				$("form[name='"+WSI.formname+"'] label[for='"+obj.errors[err].field+"']").addClass("error");
				// add error message
				errorMessage = errorMessage + obj.errors[err].error + '<br/>';
			});
			// Display errors
			$("#"+WSI.errordiv).html(errorMessage);

			// Re-enable submit button and fade in
			$("form[name='"+WSI.formname+"']").find("input").removeAttr("disabled").end().children().fadeTo('normal', 1);

		} else {
			// The object is not what we expect
			WSI.submitCallbackFailure(null, 'An error occured', null);
		}
	} else {
		// We have a bad response
		WSI.submitCallbackFailure(null, 'An error occured', null);
	}
};

// define failure callback
WSI.submitCallbackFailure=function(XMLHttpRequest, textStatus, errorThrown){
	//Record error
	$("#"+WSI.errordiv).html("Error: "+ textStatus + "<div>Please try again</div>");

	// Re-enable submit button and fade in
	$("form[name='"+WSI.formname+"']").find("input").removeAttr("disabled").end().children().fadeTo('normal', 1);
};

WSI.salesforce={};

//define success callback
WSI.salesforce.submitCallbackSuccess=function(obj){
	if (typeof obj === 'object'){
		// Process JSON object response
		if (obj.success){
			// Success
			// 1. fade in fields
			// 2. Attach print message
			$("form[name='" + WSI.formname+"'] label").removeClass("error");

			$("form[name='"+WSI.formname+"']").children().fadeTo('normal', 1).end().find("input[title='Submit']").attr({src: '/apps/designer/docroot/images/btn_print_small.gif', title:'Print', alt:'Print'}).before("<div class=\"printMessage\">Thank You for submitting your information. Please print out your application by clicking the \"Print Application\" button below. Then fax it along with your qualifications to (702)&nbsp;360-7171.</div><div id='salesforce-success'>"+obj.salesforce+"</div>");

			// $("form[name='"+WSI.formname+"']").find('fieldset').slideUp().end().find('h2.success').text(obj.success).fadeTo('normal', 1);
			$("input[title='Print']").removeAttr("disabled");
			$("input[title!='Print'], select").addClass("disable").attr("readonly", "readonly").removeAttr("disabled");
			window.scrollTo(0, 0);
			WSI.salesforce.init();
			WSI.salesforce.printOpen();
		} else if (obj.errors) {
			var errorMessage='';
			$("form[name='" + WSI.formname+"'] label").removeClass("error");

			// Errors
			$.each(obj.errors, function(err){
				// add error class to field
				$("form[name='"+WSI.formname+"'] label[for='"+obj.errors[err].field+"']").addClass("error");
				// add error message
				errorMessage = errorMessage + obj.errors[err].error + '<br/>';
			});
			// Display errors
			$(".errors").html(errorMessage);

			// Re-enable submit button and fade in
			$("form[name='"+WSI.formname+"']").find("input").removeAttr("disabled").end().children().fadeTo('normal', 1);

		} else {
			// The object is not what we expect
			WSI.salesforce.submitCallbackFailure(null, 'An error occured', null);
		}
	} else {
		// We have a bad response
		WSI.submitCallbackFailure(null, 'An error occured', null);
	}
};

//define failure callback
WSI.salesforce.submitCallbackFailure=function(XMLHttpRequest, textStatus, errorThrown){
	//Record error
	$(".errors").html("Error: "+ textStatus + "<div>Please try again</div>");

	// Re-enable submit button and fade in
	$("form[name='"+WSI.formname+"']").find("input").removeAttr("disabled").end().children().fadeTo('normal', 1);
};

// Define print dialog open
WSI.salesforce.printOpen=function(){
	// Set the window id
	var dlg=$("#printDialog .window");

	// JS for the window
	var maskHeight = $(document).height();  
	var maskWidth = $(window).width();  

	// Get the mask
	var mask = $('#printDialogMask');
	//Set height and width to mask to fill up the whole screen  
	mask.css({'width':maskWidth,'height':maskHeight, 'filter': 'alpha(opacity=50)'}).fadeIn(1000);  
          
	//Get the window height and width  
	var winH = $(window).height();  
	var winW = $(window).width();  

	//Set the popup window to center  
	dlg.css({'top': winH/2-dlg.height()/2, 'left': winW/2-dlg.width()/2}).fadeIn(2000);

}

// Define print function
WSI.salesforce.print=function(){
	$('#printDialogMask, #printDialog .window').hide();  		
	window.print();
	return false;
}

// Definre Salesforce init()
WSI.salesforce.init=function(){
	$("body").append('<div id="printDialog"><div class="window"><div id="printMessage" class="printMessage">Thank You for submitting your information. Please print out your application by clicking the "Print Application" button below. Then fax it along with your qualifications to (702)&nbsp;360-7171.</div><a href="#" id="printLink"><img src="/apps/designer/docroot/images/btn_print_small.gif" tile="Print" alt="Print"></a></div><div id="printDialogMask"></div></div>').find("#printLink").click(WSI.salesforce.print);
}


function attachSalesforceSubmit(formName) {
	$("form[name='"+formName+"']").submit(function(evt){
		// Has this been successfully submitted? If so print
		if ($('#salesforce-success').length > 0){window.print(); return false;}
		// Clear errors
		$(".errors").html('');
		// Grab form inputs and post via AJAX
		var params=$("form[name='"+formName+"']").serialize();

		WSI.setProps(formName);
		// Disable submit and partially fade form
		$("input", this).attr("disabled", "disabled").removeClass("error").end().children().fadeTo('normal', .33);
		$.ajax( {'type':'POST', 'url': this.action, 'dataType': 'json', 'data': params, 'success': WSI.salesforce.submitCallbackSuccess, 'error': WSI.salesforce.submitCallbackFailure} );
		return false;
	});
	// Create print dialog
	WSI.salesforce.init();
}

function attachFormSubmit(formName) {
	$("form[name='"+formName+"']").submit(function(evt){
        // Clear errors
        $("#"+formName+"error").html('');
        // Grab form inputs and post via AJAX
        var params=$("form[name='"+formName+"']").serialize();

        WSI.setProps(formName);

        // Disable submit and partially fade form
        $("input", this).attr("disabled", "disabled").removeClass("error").end().children().fadeTo('normal', .33);
        $.ajax( {'type':'POST', 'url': this.action, 'dataType': 'json', 'data': params, 'success': WSI.submitCallbackSuccess, 'error': WSI.submitCallbackFailure} );
        return false;
    });
}
