﻿var Api = {};

function getUrlVars()
{
	var vars = [], hash;
	var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
	for (var i = 0; i < hashes.length; i++)
	{
		hash = hashes[i].split('=');
		vars.push(hash[0]);
		vars[hash[0]] = hash[1];
	}
	return vars;
}

Api.buildRequestUrl = function(apiPath)
{
	if (apiPath.indexOf('?') > -1)
	{
		apiPath = apiPath + '&';
	}
	else
	{
		apiPath = apiPath + '?';
	}
	var op = jQuery.url.param("op");
	if (typeof (op) == 'undefined')
	{
		var op = 0;
	}
	apiPath += 'op=' + op;


	apiPath += '&pageIdentifier=' + pageIdentifier;
	return 'handlers/ClientServerApi.svc/api' + apiPath;
}

Api.invoke = function(apiPath)
{
	$.ajax({
		url: Api.buildRequestUrl(apiPath),
		cache: false,
		dataType: "xml",
		success: function(xml)
		{
		}
	});
}

Api.getListAndUpdate = function(apiPath, apiResultElementName, itemHtmlTemplate, domElementToUpdate, onUpdateCompleteCallback, onModifyItemProperties)
{
	$.ajax({
		url: Api.buildRequestUrl(apiPath),
		cache: false,
		dataType: "xml",
		success: function(xml)
		{
			var html = "";
			var itemsPropertiesArray = Array();

			$(xml).find(apiResultElementName).each(function(itemIndex)
			{
				var itemProperties = Xml.getChildrenAsArray($(this));
				if (apiResultElementName == 'ClientProduct')
				{
					Products.cacheProperties(itemProperties['ItemId'], itemProperties);
				}


				if (typeof (onModifyItemProperties) == 'function')
				{
					onModifyItemProperties(itemProperties);
				}
				
				html += String.fillWithArray(itemHtmlTemplate, itemProperties);
				itemsPropertiesArray.push(itemProperties);
			});
			domElementToUpdate.html(html);
			if (typeof (onUpdateCompleteCallback) == 'function')
			{
				var itemsCount = $(xml).find("ItemsCount").text();
				onUpdateCompleteCallback(itemsPropertiesArray, itemsCount);
			}
		}
	});
}

Api.getListAndCallback = function(apiPath, apiResultElementName, onResult)
{
	$.ajax({
		url: Api.buildRequestUrl(apiPath),
		cache: false,
		dataType: "xml",
		success: function(xml)
		{
			var html = "";
			var itemsPropertiesArray = Array();

			var results = Array();
			$(xml).find(apiResultElementName).each(function(itemIndex)
			{
				var itemProperties = Xml.getChildrenAsArray($(this));
				results[itemIndex] = itemProperties;
			});

			if (typeof (onResult) == 'function')
			{
				onResult(results);
			}
		}
	});
}


Api.updateByItem = function(itemProperties, templateSelector, targetElementSelector)
{
	var template = jQuery.trim($(templateSelector).html());
	var filledTemplate = String.fillWithArray(template, itemProperties);
	$(targetElementSelector).html(filledTemplate);
}