﻿var a2bMaster = {

	onDocumentReady: function() {

		$("div.tabs").tabs().bind("tabsshow", doGridResize);
		$("div.box").expandable();
		$(".forceUpper").forceUpperCase();

		// Set the default properties for all jqGrids.	        
		$.extend($.jgrid.defaults,
				{
					datatype: "json",
					mtype: "POST",
					height: 250,
					autowidth: true,
					rowNum: 100,
					rowList: [50, 100, 200],
					viewrecords: true,
					recordtext: 'Viewing {0} to {1} of {2}',
					beforeRequest: function() {
						a2bMaster.copyFilterCookieToGrid(this.id);
					},
					loadComplete: function(xhr) {
						var recordsInThisSet = xhr.records;
						var allRecords = xhr.recordsUnfiltered;
						if (!isNaN(recordsInThisSet) && !isNaN(allRecords) && recordsInThisSet != allRecords) {
							var formattedAll = $.fmatter.util.NumberFormat(allRecords, $.jgrid.formatter.integer);
							$(".ui-paging-info", $(this).pager).append('<span id="filterStatus"> (from ' + formattedAll + ')</span>');
						}
					}
				}
			);

		$.extend($.jgrid.formatter,
				{
					integer: { thousandsSeparator: ",", defaultValue: '0' }
				}
			);
		// END: Set the default properties for all jqGrids.

		// Automatically resize jQuery.Grids               
		var resizeTimer = null;
		$(window).bind('resize', function() {
			if (resizeTimer) clearTimeout(resizeTimer);
			resizeTimer = setTimeout(doGridResize, 100);
		});

		function doGridResize() {
			if (grid = $('.ui-jqgrid-btable:visible')) {
				grid.each(function(index) {
					var gridId = $(this).attr('id');
					var container = $('#gbox_' + gridId).parent();
					$('#' + gridId).setGridWidth(container.width());
				});
			}
		};
		// END: Automatically resize jQuery.Grids

		// Set the default properties for all datepickers
		$.datepicker.setDefaults(
                    {
                    	dateFormat: $.datepicker.ISO_8601, //ISO_8601 = "yy-mm-dd"
                    	constrainInput: false,
                    	showOn: 'focus'
                    }
                );
		// END: Set the default properties for all datepickers


		$("#message").hide();
		$("#errorMessage").hide();

		$(document).ajaxError(function(event, request, options, exception) {
			var error = "<strong>Error:</strong> " + options.url + " " + request.statusText;
			if (exception) {
				error += exception.toString();
			}

			a2bMaster.showErrors(error);
		});

	}, //onDocumentReady

	showErrors: function(errors) {
		if (errors) {
			$("#errorMessages").html(errors);
			$("#errorMessage").show();
		}
	},

	showMessage: function(messageHtml) {
		if (messageHtml) {
			$("#messages").html(messageHtml);
			$("#message").slideDown('slow').delay(2000).slideUp('slow');
		}
	},

	/**** Filter Utility Methods ****/
	copyFilterCookieToGrid: function(gridId) {
		var filter = readCookie(gridId + '-filterCookie');
		$('#' + gridId).setGridParam({ postData: { filter: filter} });
	},

	setFilterFromCookie: function(gridId, filterEditorId) {
		var filterString = a2bMaster.getFilterCookie(gridId);
		if (filterString) {
			$('#' + filterEditorId).filterClauseEditor('setFilter', JSON.parse(filterString));
		}
		else {
			$('#' + filterEditorId).filterClauseEditor('reset');
		}
	},

	setCookieFromFilter: function(gridId, filterEditorId) {
		var filter = $('#' + filterEditorId).filterClauseEditor('getFilter');
		a2bMaster.setFilterCookie(gridId, JSON.stringify(filter));
	},

	getFilterCookie: function(gridId) {
		var filter = readCookie(gridId + '-filterCookie');
		return filter;
	},

	setFilterCookie: function(gridId, value) {
		createCookie(gridId + '-filterCookie', value);
	},

	clearFilterCookie: function(gridId) {
		eraseCookie(gridId + '-filterCookie');
	}
	/**** End Filter Utility Methods ****/
}


//******************************************************
//	Helper functions for cookies
//******************************************************
function createCookie(name, value, days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
		var expires = "; expires=" + date.toGMTString();
	}
	else var expires = "";
	document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for (var i = 0; i < ca.length; i++) {
		var c = ca[i];
		while (c.charAt(0) == ' ') c = c.substring(1, c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name, "", -1);
}
//******************************************************
//	End Helper functions for cookies
//******************************************************
