﻿
(function($) {
	if (typeof ($.Eleview) === 'undefined') $.Eleview = {};

	// CONVERTION FUNCTIONS
	var convertKgToLb = $.Eleview.convertKgToLb = function(kg) {
		return kg / 0.45359237;
	}

	var convertLbToKg = $.Eleview.convertLbToKg = function(lb) {
		return lb * 0.45359237;
	}

	var convertCmToIn = $.Eleview.convertCmToIn = function(cm) {
		return cm / 2.54;
	}

	var convertInToCm = $.Eleview.convertInToCm = function(inch) {
		return inch * 2.54;
	}

	var roundDigits = $.Eleview.roundDigits = function(amount, digits) {
		p = Math.pow(10, digits);
		return Math.round(amount * p) / p;
	}

	var getMoneyString = $.Eleview.getMoneyString = function(amount) {
		var sn = "00" + Math.round(amount * 100);
		if (sn.length > 4) sn = sn.substring(2, sn.length);
		return Number(sn.substring(0, sn.length - 2)) + "." + sn.substring(sn.length - 2, sn.length);
	}
	// -------------------

	// Ajax response handler
	var jsonRx = $.Eleview.jsonRx = /^({.*})$/;
	var parseAjaxResponse = $.Eleview.parseAjaxResponse = function(data) {
		if (!$.Eleview.jsonRx.test(data)) { // if clear HTML
			var fakeResult = $.evalJSON("{\"StatusCode\":1,\"Data\":\"\"}");
			fakeResult.Data = data;
			return fakeResult;
		}
		var result = $.evalJSON(data);
		if (result == null) {
			alert("Incorrect response format:\n'" + data + "'");
			return null;
		}
		switch (result.StatusCode) {
			case 1: // Success
				return result;

			case 2: // Error
				alert("Server error: " + result.Data);
				return null;

			case 3: // NotAutorized
				alert("You are not authorized for this action");
				return null;

			case 4: // NotAuthenticated
				window.location.reload();
				return null;

			case 5: // Friendly error
				alert(result.Data);
				return null;

			default:
				alert("Unknown status code from the server: " + result.StatusCode);
				return null;
		}
	}

	// Tree members
	var lock = $.Eleview.lock = false;
	var changeTreeState = $.Eleview.changeTreeState = function(td, clientID, handle) {
		if (lock) return;
		lock = true;

		var childs = $("#menu_" + clientID + "_" + handle);
		var img = $(td).find("img");
		if (visible = childs.css("display") == "none") {
			childs.show();
			img.attr("src", img.attr("src").replace("Close", "Open"));
		} else {
			childs.hide();
			img.attr("src", img.attr("src").replace("Open", "Close"));
		}

		var cookieName = $("#" + clientID + "_cookieName").val();
		var cookie = $.evalJSON($.cookie(cookieName));
		if (cookie == null) cookie = {};
		cookie["" + handle] = visible;
		$.cookie(cookieName, $.toJSON(cookie), { expires: 1 });

		lock = false;
	}
	//----------------------------------

	var selectEntity = $.Eleview.selectEntity = function(enablefolder) {
		return window.showModalDialog(
			"popup.aspx?main=entitytree&po=" + (enablefolder ? "1" : "0"),
			"",
			"dialogHeight: 500px; dialogWidth: 400px;"
		);
	}

})(jQuery);


