﻿
var urlParts = location.href.replace("http://", "").replace("https://", "").split("/");
var WebServicePath = urlParts[0] + "/services";
urlParts = null;

function AddRequestParam(url, paramName, paramValue)
{
	if(url.indexOf("?") > 0)
	{
		return url + "&" + paramName + "=" + paramValue;
	}
	else
	{
		return url + "?" + paramName + "=" + paramValue;
	}
}

function CreateServiceRequest(serviceName, methodName)
{
	var protocol = "http://";
	var url = protocol + WebServicePath + "/Service.aspx?svc=" + serviceName + "&rpc=" + methodName;

	return new ServiceRequest(url);
}

function CreateSecureServiceRequest(serviceName, methodName)
{
	var protocol = "http://";
	//var protocol = "https://";
	var url = protocol + WebServicePath + "/Service.aspx?svc=" + serviceName + "&rpc=" + methodName;
	
	return new ServiceRequest(url);
}

function SendRequest(serviceRequest, callback, state) {
	var ajax = CreateAjaxRequest();

	if (ajax == null)
	{
		return;
	}

    ajax.onreadystatechange = function()
    {
    	if (ajax.readyState == 4)
    	{
    		if (ajax.status == 200)
    		{
    			var jsonString = unescape(ajax.responseText);
    			var response = eval("(" + jsonString + ")");

    			callback(response, state);
    		}
    		else
    		{
    			serviceRequest.Retries++;

    			if (serviceRequest.Retries < 4)
    			{
    				//retrying
    				SendRequest(serviceRequest, callback, state);
    			}
    			else
    			{
    				//clipboardData.setData("Text", serviceRequest.Url);
    				Error("Failed to communicate with server, reloading this page will usually fix this issue.");
    			}
    		}
    	}
    }

    serviceRequest.SendPost(ajax);
}

function CreateAjaxRequest()
{
	//this is a borrowed code snippet, verify this covers all browser implementations
	if (typeof XMLHttpRequest == "undefined") XMLHttpRequest = function()
	{
		try { return new ActiveXObject("Msxml2.XMLHTTP.6.0") } catch (e) { }
		try { return new ActiveXObject("Msxml2.XMLHTTP.3.0") } catch (e) { }
		try { return new ActiveXObject("Msxml2.XMLHTTP") } catch (e) { }
		try { return new ActiveXObject("Microsoft.XMLHTTP") } catch (e) { }
		Error("This browser does not support XMLHttpRequest.")

		return null;
	};

	return new XMLHttpRequest();
}

function ServiceRequest(url)
{
	this.Url = url;
	this.Parameters = {};
	this.Retries = 0;
}

ServiceRequest.prototype.AddFormParameter = function(name, value)
{
    this.Parameters[name] = value;
}

ServiceRequest.prototype.AddObjectParameter = function(name, value)
{
    this.Parameters[name] = value;
}

ServiceRequest.prototype.SendPost = function(ajax)
{
	ajax.open("POST", this.Url, true);

	var postData = this.Parameters.toJSONString();

	//clipboardData.setData("Text", postData);
	ajax.send(postData);
}