﻿// <!--

/*
TABLE OF CONTENTS

=Salem.RegisterNamespace
=Salem.Ajax.Service
=Salem.String

*/

/* =Salem.RegisterNamespace */
if (typeof f == "undefined" || !Salem) {
	var Salem = {};
}

Salem.RegisterNamespace = function() {
	
	var a = arguments, o = null, i, j, d;
	for (i = 0; i < a.length; i++) {
		d = a[i].split(".");
		o = Salem;

		// Salem is implied, so it is ignored if it is included
		for (j = (d[0] == "Salem") ? 1 : 0; j < d.length; j++) {
			o[d[j]] = o[d[j]] || {};
			o = o[d[j]];
		}
	}
	return o;
};

/* =Salem.Ajax.Service */
Salem.RegisterNamespace("Ajax.Service");
Salem.Ajax.Service = function AjaxService(serviceUrl) {
	var Instance = this;
	this.serviceUrl = serviceUrl;
	//Get Wrapper
	this.JsonGet = function(method, data, callback, error) {
		this.invoke("GET", method, data, callback, error, false);
	};
	//Post Wrapper
	this.JsonPost = function(method, data, callback, error) {
		this.invoke("POST", method, data, callback, error, false);
	};
	//Call a wrapped object
	this.invoke = function(action, method, data, callback, error, bare) {
		//The service endpoint URL
		var url = Instance.serviceUrl + method;
		$.ajax({
			url: url,
			data: data,
			type: action,
			processData: true,
			contentType: "application/json",
			timeout: 5000,
			dataType: "json",
			success: function(response) {
				for (var property in response) {
					//WCF returns all json as a wrapped object. This drops the outer layer that isn't needed if it exists
					response = response[property];
					break;
				}
				//Interpret JSON objects set the response as that object
				//We do this verses Eal because tha could result in an unsafe execution of code
				response = JSON.parse(response);
				//Return the object
				callback(response);
			},
			error: error
		});
	}
}

/* =Salem.String */
Salem.RegisterNamespace("Salem.String");
Salem.String = {

	IsNullOrEmpty: function() {
		var ret = false;
		for (var i = 0; i < arguments.length; i++) {
			if (ret == false && (arguments[i] == null || Salem.String.Trim(arguments[i].toString()).length == 0)) { ret = true; }
		}
		return ret;
	},

	Format: function(str) {
		for (var i = 1; i < arguments.length; i++) {
			var re = new RegExp('\\{' + (i - 1) + '\\}', 'gm');
			var val = (Salem.String.IsNullOrEmpty(arguments[i])) ? '' : arguments[i];
			str = str.replace(re, val);
		}
		return str;
	},

	Trim: function(str) {
		return str.replace(/^\s+|\s+$/g, "");
	}

};


// -->
