d = document;

/**
 * ce (create element) funkcija sukuria elementa
 * pvz.: inputas = ce('input', 'input_id', 'input_name', 'radio');
 */
function ce(type, id, name, innertype) {
	elem = document.createElement(type);

	try	{
	  elem.id = id;
	}
	catch (exp) {
	}

	try	{
	  elem.name = name;
	}
	catch (exp) {
	}

	try	{
	  elem.type = innertype;
	}
	catch (exp) {
	}

	return elem;
}

function addEvent( obj, sType, fn )
{
	if (obj.addEventListener)
	{
		obj.addEventListener(sType, fn, false);
	} 
	else if (obj.attachEvent) 
	{
		var r = obj.attachEvent("on"+sType, fn);
	}
	else 
	{
        alert("Neimanoma prisieti veiksmo!");
    }
}

function change_amount(increase, elem_id) {
	try {
		elem = d.getElementById(elem_id);
		amount = elem.value;
		if(!is_numeric(amount, true)) {
			elem.value = "0";
			alert("Laukelyje turi buti sveikas skaicius!");
			return;
		}
		else
			amount = parseInt(amount);
	}
	catch(exp) {
		elem.value = "0";
		alert("Laukelyje turi buti sveikas skaicius!");
		return;
	}
	
	if(increase) {
		amount++;
		elem.value = amount;
	}
	else {
		if(amount > 0) {
			amount--;
			elem.value = amount;
		}
	}
}

function is_numeric(string, positive_only) {
	pos_valid_chars = "1234567890.";
	all_valid_chars = "1234567890.-";
	
	dots = 0;

	if(string.length == 0) 
		return false;

	for(i = 0; i < string.length && (dots <= 1); i++) {
		ch = string.charAt(i);

		if(ch == ".")
			dots++;
				
		// jeigu pirmas taskas iseinam
		if((i == 0) && (ch == '.')) 
			return false;

		// jeigu daugiau kaip 1 taskas, iseinam
		if(dots > 1)
			return false;
				
		if(positive_only) {
			if(pos_valid_chars.indexOf(ch) == -1) {
				return false;
			}
		}
		else {
			// ziurim pirma skaiciu, nes tik jis gali buti "-"
			if(i == 0) {
				if(all_valid_chars.indexOf(ch) == -1) {
					return false;
				}
			}
			else {
				if(pos_valid_chars.indexOf(ch) == -1) {
					return false;
				}
			}
		}
	}
	
	return true;
}

function money_format(num) {
	num = num.toString();
	has_dot = false;
	dot_pos = 0;
	if(is_numeric(num)) {
		for(i = 0; i < num.length; i++) {
			ch = num.charAt(i);
			if(ch == ".") {
				has_dot = true;
				dot_pos = i;
				break;
			}
		}
		
		if(has_dot) {
			if((dot_pos + 1) == num.length-1) {
				return (num.substr(0, dot_pos + 2) + "0");
			}
			else if(dot_pos == num.length-1) {
				return (num + "00");
			}
			else {
				return num.substr(0, dot_pos + 3);
			}
		}
		else {
			return num + ".00";
		}
	}
	return false;
}