$(document).ready(function(){

	/*if (!e) var e = window.event;
	e.cancelBubble = true;
	if (e.stopPropagation) e.stopPropagation();*/

	refresha();
	loadTopProducts();

	$('div#gallery div.image a').fancybox();
	$('div.image a.thickbox').fancybox();
	$('a.fancy').fancybox({
		callbackOnShow: function(){
			if ($('#fancy_outer').width() < 400){
				$('#fancy_outer').width(400);
				centered_left =  parseInt(($(window).width() - 400) / 2 - 18);
				centered_left += 'px';
				
				$('#fancy_outer').css('left', centered_left);
			}
		}
	});
	
	$('.delivery_terms_pop').fancybox({'frameWidth': 800,'frameHeight': 600});


/* BEGIN Actions - MAIN MENU ***************************************************** */
	$("table#mainmenu td.middle").mouseover(
		function(){
			var id = $(this).attr("id");
			var id_num = id.substring(2);

			button1_mouseon(id_num);
			$("ul#sub"+id_num).removeClass('hidden');

			var button = {};
			$("td#m_"+id_num).position(button);

			var submenu_width = 250;
			if (button.left + submenu_width > $(window).width()) {
				$("ul#sub"+id_num).addClass('submenu_right');
			}
			else{
				$("ul#sub"+id_num).addClass('submenu_left');
			}
		}
	);

	$("table#mainmenu td.middle").mouseout(
		function(){
			var id = $(this).attr("id");
			var id_num = id.substring(2);

			button1_mouseout(id_num);
			$("ul#sub"+id_num).addClass('hidden');
		}
	)

	/*$("ul.submenu").mouseout(function(){
		$("ul.submenu").addClass('hidden');
	});*/

	$("ul.submenu").hover(
	  function () { /* hover ON */
			/*var id = $(this).attr("id");
		alert(id);*/
	  },
      function () { /* hover OUT */
      	/*$("ul.submenu").addClass('hidden');*/
	  }
	);

});

function delCategory(link){
	var answer = confirm("Vai tiešām vēlaties izdzēst šo kategoriju?")
	if (answer){
		$('#categoriesPlace').load(link);
	}
}

function roundNumber(num, dec) {
	var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
	return result;
}

function refresha()
{
	$("a.delete").click(function(){
		var id = $(this).attr("rel");
		removeFormField('#'+id);
	});
}

function button1_mouseon(id){
	$("#l_"+id).addClass("left_hov");
	$("#m_"+id).addClass("middle_hov");
	$("#r_"+id).addClass("right_hov");
}

function button1_mouseout(id){
	$("#l_"+id).removeClass("left_hov");
	$("#m_"+id).removeClass("middle_hov");
	$("#r_"+id).removeClass("right_hov");
}

// Load top products into start block
function loadTopProducts(){
	var cat_url = webroot+language+"/categories/";
	$('#TopProducts').load(cat_url + 'get_top/15');
	$('#categorySel').attr({value: "15"}); // set also value for SELECT tag appropirate to value
}

/*var cat_url = webroot+language+"/admin/categories/list";

$.ajax({
	url: cat_url,
	cache: false,
	success: function(data){
		$("#categoriesPlace").html(data);
	}
});*/

var msie = (((navigator.appVersion.indexOf("MSIE")!= -1)&&!window.opera) ? true : false);

/**
 * Hook elements
 */
window.onload = function ()
{
	// Blur every link when focused

	var links = document.getElementsByTagName("a");

	for (var i = 0; i < links.length; i++)
	{
		links[i].onfocus = function() { this.blur(); }
	}

	// Find all forms and hook every input element using
	// addInputSubmitEvent function

	var forms = document.getElementsByTagName('form');

	for (var i=0; i<forms.length; i++)
	{
		var inputs = forms[i].getElementsByTagName('input');

		for (var j=0; j<inputs.length; j++)
		{
			addInputSubmitEvent(forms[i], inputs[j]);
		}
	}
}


/**
 * Add submit event for every input in forms when Enter is pressed
 *
 * @param form element Form to submit
 * @param input element Input to hook
 */
function addInputSubmitEvent(form, input)
{
	/*input.onkeydown = function(e)
	{
		e = e || window.event;

		if (e.keyCode == 13)
		{
			form.submit(); return false;
		}
	};*/
}


/**
 * submit form
 */
function submitForm(formID)
{
	var form = document.getElementById(formID);

	if (form)
	{
		form.submit();
	}
}

/**
 * Appends one of the existing values to values textarea
 * Used in "Add Product" page
 */
function appendValue(destination_id, new_val)
{
	var el = document.getElementById(destination_id);

	if (el)
	{
		// trim
		var old_val = el.value.replace(/^\s+|\s+$/g,"");

		// append
		el.value = (old_val == "" ? new_val : old_val+"\n"+new_val);
	}
}


function confirmAction()
{
	return confirm("Vai tiešām vēlaties veikt šo darbību?")
}


/**
 * Manages switching information tabs when viewing product
 */
function openTAB(id)
{
	var el_link = document.getElementById("a_"+id);
	var el_cont = document.getElementById(id+"_");

	// change link style

	var menu = document.getElementById("product_info_menu");

	var els = menu.getElementsByTagName("a");

	for (var i=0; i<els.length; i++)
	{
		els[i].className = (els[i] == el_link ? "active" : "");
	}

	// change content style

	var holder = document.getElementById("information");

	els = holder.getElementsByTagName("div");

	for (var i=0; i<els.length; i++)
	{
		if (els[i].id != "")
		{
			els[i].className = (els[i] == el_cont ? "visible" : "hidden");
		}
	}

	// change url

	document.location = "#" + id;
}



/**
 * Lateko leasing calculator's engine
 *
 * @param int price Price
 * @param int advance First payment (Ls)
 * @param int period Leasing period (months)
 */

function calculateLeasingLATEKO(price, advance, period)
{
	var lblAdvance = document.getElementById("lblAdvance");

	var lblPayment = document.getElementById("lblPayment");

	var service = 0.005;

	var rate = 0.23;


	lblAdvance.innerHTML = "---";

	lblPayment.innerHTML = "---";

	// ---

	if (price > 4000)
	{
		return "Pirkuma maksa līzinga apstākļos nevar pārsniegt 4000 Ls";
	}
	else if (price < 35)
	{
		return "Pirkuma maksa līzinga apstākļos nevar būt mazāka par 35 Ls";
	}
	else
	{
		var advance_val = price - price * (advance / 100);

		if (advance_val > 2000)
		{
			return "Minimālais avans ir " + Math.ceil((price - 2000) / price * 100) + "%";
		}
		else
		{
			if (rate == 0)
			{
				var payment = advance_val / period;
			}
			else
			{
				var payment = (advance_val * rate / 12) / (1 - Math.pow((1 + (rate / 12)), -period));
			}

			monthly = Math.round((payment + (price * service)) * 100) / 100;
		}
	}

	var intAdvance = Math.round((price - advance_val) * 100) / 100;

	var intPayment = monthly;

	lblAdvance.innerHTML = intAdvance;

	lblPayment.innerHTML = intPayment + " Ls";

	return "";
}

/**
 * GE Money leasing calculator's engine
 *
 * @param int price Price
 * @param int advance First payment (Ls)
 * @param int period Leasing period (months)
 * @return string Alert (if any)
 */
function calculateLeasingGEMONEY(price, advance, period)
{
	var lblAdvance = document.getElementById("lblAdvance");

	var lblPayment = document.getElementById("lblPayment");

	var commission = 0;

	var apr = 0;

	lblAdvance.innerHTML = "---";

	lblPayment.innerHTML = "---";

	// ---

	if (price > 10000)
	{
		return "Pirkuma maksa līzinga apstākļos nevar pārsniegt 10 000 Ls";
	}
	else if (price < 49)
	{
		return "Pirkuma maksa līzinga apstākļos nevar būt mazāka par 49 Ls";
	}
	else
	{
		if((price >= 49) && (price <= 499))
		{
			if (advance == 0)
			{
				commission = 0;

				apr = 23.00;
			}
			else
			{
				commission = 0;

				if (advance < 5)
				{
					advance = 5;

					return "Minimālais avanss ir 5% vai 0%";
				}
				else
				{
					advance = advance - commission;
				}

				apr = 23.00;
			}
		}
		else
		if ((price >= 500) && (price <= 2500))
		{
			if (advance == 0)
			{
				commission = 0;

				apr = 22.00;
			}
			else
			{
				commission = 0;

				if(advance < 5)
				{
					advance = 5;

					return "Minimālais avanss ir 5% vai 0%";
				}
				else
				{
					advance = advance - commission;
				}

				apr = 22.00;
			}
		}
		else
		if ((price >= 2501) && (price <= 10000))
		{
			commission = 0;

			apr = 17.50;
		}

		var advance_val = price * (advance / 100);

		GEMoneyCalculator = new GEMoneyLeasingCalculation;

		res = GEMoneyCalculator.gpl(price, period, advance_val, commission, apr);


		var intAdvance = Math.round(advance_val * 100) / 100;

		var intPayment = res["payment"];

		lblAdvance.innerHTML = intAdvance;

		lblPayment.innerHTML = intPayment + " Ls";
	}

	return "";
}

/**
 * Calculate leasing
 *
 * This function get which of leasing companies is selected and calls
 * that campany's function which does all the work
 *
 */
function calculateLeasing()
{
	var lblAlert = document.getElementById("lblAlert");

	var price = document.getElementById("price").value;

	var advance = document.getElementById("advance").value;

	var period = document.getElementById("period").value;

	var company = getRadioValue("radLeasingCompany");

	if (company == "gemoney")
	{
		lblAlert.innerHTML = calculateLeasingGEMONEY(price, advance, period);
	}
	else
	if (company == "lateko")
	{
		lblAlert.innerHTML = calculateLeasingLATEKO(price, advance, period);
	}
}


function toggleFilters(show)
{
	var filters = document.getElementById("filters");

	var lblShow = document.getElementById("lblShow");
	var lblHide = document.getElementById("lblHide");

	if (show == undefined)
	{
		show = !(filters.className == "visible");
	}

	if (show)
	{
		filters.className = "visible";

		lblShow.className = "hidden";
		lblHide.className = "visible";

		document.cookie = "CookieShowFilters=1;;/;";
	}
	else
	{
		filters.className = "hidden";

		lblShow.className = "visible";
		lblHide.className = "hidden";

		document.cookie = "CookieShowFilters=0;;/;";
	}
}

/**
 * Radio buttons: returns checked value
 *
 * @param radios_name string Name of radio elements
 * @return string
 */
function getRadioValue(radios_name)
{
	var radioObj = document.getElementsByName(radios_name);

	if(!radioObj) return "";

	var radioLength = radioObj.length;

	if(radioLength == undefined)
	{
		return (radioObj.checked ? radioObj.value : "");
	}

	for (var i=0; i<radioLength; i++)
	{
		if (radioObj[i].checked)
		{
			return radioObj[i].value;
		}
	}

	return "";
}

/**
 * Checks for address hash string. If it changed from last time we checked
 * select specified tab. This is necessary for back button's proper working
 *
 * @param string strHash Hash string (with # in front) from previous check
 */
function checkLocationHash(strHash)
{

	if (document.location.hash != strHash && document.location.hash != "")
	{
		openTAB(document.location.hash.substring(1));

		var strHash = document.location.hash;
	}

	setTimeout("checkLocationHash('"+strHash+"')", 500);
}

function confirm_action(location){
	if (confirm('Vai tiešām vēlaties veikt šo darbību?')){
		document.location = webroot+location;
		return true;
	}else{
		return false;
	}
}


/**
 * Changes product background color to #efefef if product
 * is selected, otherwise, use #ffffff as background color
 *
 * IE return new value before, while other browsers returns
 * old value so we swap colors according to browser
 *
 * @param srcElementId Id of the checkbox
 * @param dstElementId Id of the div to change background
 */
function selectProduct(srcElementId, dstElementId, product_id)
{

	if ($('#'+srcElementId).is(':checked')){
		var color = "#efefef";
	}else{
		var color = "#ffffff";
	}

	$('#'+dstElementId).css('background-color', color);
	$('#'+dstElementId+' div.buy').css('background-color',  color);

	$.ajax({
	  type: 'GET',
	  url: webroot+'lv/admin/products/select/' + product_id + '/true'
	});
}

/**
 * Show dialog
 */
function showDialog(url, name)
{
	window.open(url, name, 'width=800,height=800,status=0,toolbar=1,resizable=0,scrollbars=1,location=1,menubar=1,directories=1');
}

/**
 * Print email link (protection from spambots)
 * If javascript is disabled, nothing is visible
 *
 * @param string p1 Part 1 - this is username
 * @param string p2 Part 2 - this is domain
 * @param string p3 Part 3 - this is TLD
 */

function writemail(p1, p2, p3)
{
	document.write("<a href='mailto:"+p1+"@"+p2+"."+p3+"'>"+p1+"@"+p2+"."+p3+"</a>");
}

function changeCheckoutType()
{
	var user_type = $("input[name=data\\[Checkout\\]\\[user_type\\]]:checked").val();

	var payment_type = document.getElementById("CheckoutPaymentType").value;

	var f_block = document.getElementById("f_block");

	var j_block = document.getElementById("j_block");

	if (user_type == "j")
	{
		f_block.style.display = "none";
		j_block.style.display = "block";

		document.getElementById("block02").style.display = (payment_type == 2 ? "block" : "none");
		document.getElementById("block03").style.display = (payment_type == 3 ? "block" : "none");
	}
	else
	{
		f_block.style.display = "block";
		j_block.style.display = "none";

		document.getElementById("block01").style.display = "none";
		//document.getElementById("block03").style.display = "none";

		if (payment_type == 3)
		{
			document.getElementById("block03").style.display = "none";
		}
		else if (payment_type == 2)
		{
			document.getElementById("block01").style.display = "block";
		}
	}
}

/**
 *
 *
 *
 */
function refreshDelivery(){
	var delivery = $("input[name=data\\[Checkout\\]\\[delivery_type\\]]:checked").val()
	if (delivery == '0')
	{
		document.getElementById("divDelivery0").style.display = "block";
		document.getElementById("divDelivery1").style.display = "none";
	}
	else
	if (delivery == '1')
	{
		document.getElementById("divDelivery0").style.display = "none";
		document.getElementById("divDelivery1").style.display = "block";
	}

	if ($('#CheckoutDeliveryPickup').val() == '11'){
		$('#other-delivery-info').show();
	}else{
		$('#other-delivery-info').hide();
	}
}

/*
 * Copyright (C) 2007 GE Money
 * http://www.gemoney.lv
 * Unauthorized redistribution is strictly prohibited.
 * This product (software and/or documentation) is furnished under a License/Purchase Agreement
 * and may be used only in accordance with the terms of such agreement.
 * Created by VIG
 * JS edited by Sandis Kampe
 */

function GEMoneyLeasingCalculation()
{

	this.log10 = function (x)
	{
			return Math.log(x)/Math.log(10)
	}

	this.pow_ed = function ($a, $b)
	{
		if ($a == 0) {
			if ($b == 0) {
				return false;
			} else {
				return 0;
			}
		}
		if ($b == 0) {
			return 1;
		}
		if (Math.round($b) == $b) {
			$r = 1;
			for ($i = 0; $i < $b; $i++) {
				$r *= $a;
			}
			for ($i = 0; $i < -$b; $i++) {
				$r /= $a;
			}
		} else if ($a < 0) {
			return false;
		} else {
			if (Math.abs($b) > .5) {
				return this.pow_ed($a, Math.round($b)) * this.pow_ed($a, $b - Math.round($b));
			}
			$r = 1;
			$mult = Math.log($a) * $b;
			$prod = 1;
			for ($i = 1; $i < 100; $i++) {
				$prod *= $mult / $i;
				$r += $prod;
				if ($i > 100 || this.log10(Math.abs($prod)) < -10) {
					break;
				}
			}
		}
		return $r;
	}

	this.paymentSchedule = function ($price, $month, $apr_year, $downpayment_value, $residual_value, $monthly_payment)
	{
		$monthly_payment = Math.round($monthly_payment*100)/100;

		if ((typeof $apr_year != 'object') || (typeof $apr_year != 'array'))
		{
			$tmp_apr = $apr_year;
			$apr_year = [];
			for ($i = 0; $i < 72; $i++) {
				$apr_year[$i] = $tmp_apr;
			}
		}

		$apr = [];
		for ($i = 0; $i < $apr_year.length; $i++) {
			$apr[$i] = $apr_year[$i] / 1200;
		}

		$loan = $principal_sum = Math.round($price*100)/100 - Math.round($downpayment_value*100)/100 - Math.round($residual_value*100)/100;

		$_credit = $price - $downpayment_value;

		$cond_type = 0;

		while (($apr_year[$cond_type]) && $apr_year[$cond_type] == 0) {
			$cond_type++;
		}

		if ($apr_year[$cond_type]) {
			$month_prc = $apr_year[$cond_type] / 100;
			$apr_average = $apr_year[$cond_type];
		} else {
			$month_prc = 0;
			$apr_average = 0;
		}

		if ($month_prc > 0) {
			if ($cond_type == 0) {
				$month_sum = $_credit * ($month_prc / 12 / (1 - this.pow_ed((1 + $month_prc / 12), - $month)));
			} else {
				if ($month <= $cond_type) {
					$month_sum = $_credit / $month;
				} else {
					$b_13 = this.pow_ed(1 + ($month_prc / 12), $month - $cond_type);
					$month_sum = Math.ceil($b_13 * $_credit / (($b_13 - 1) / ($month_prc / 12) + $b_13 * $cond_type) * 100) / 100;
				}
			}
		} else {
			$month_sum = $_credit / $month;
		}

		$pmt_1 = Math.round($month_sum*100)/100;

		if (!$monthly_payment || $monthly_payment == $pmt_1) {
			/**
			 * Fixed term
			 */
			$monthly_payment = $pmt_1;
			$creditas = $_credit - $month_sum * $cond_type;

			if ($creditas <= 0) {
				$m24 = $_credit / $month_sum;

			} else {

				if (1 - $month_prc / 12 * $creditas / $month_sum > 0) {
					$m24 = $cond_type + ( - Math.log(1 - $month_prc / 12 * $creditas / $month_sum) / Math.log(1 + $month_prc / 12));
				} else {
					$m24 = $_credit / $month_sum;
				}
			}
			$m24 = Math.round($m24);

			$month_prec = $m24;
			$g4 = $month_sum * $m24;
		} else {
			/**
			 * Fixed payment
			 */
			$creditas = $_credit - $monthly_payment * $cond_type;
			if ($creditas <= 0) {
				$term = $_credit / $monthly_payment;
			} else {
				if (1 - $month_prc / 12 * $creditas / $monthly_payment > 0) {
					$term = $cond_type + ( - this.log10(1 - $month_prc / 12 * $creditas / $monthly_payment) / this.log10(1 + $month_prc / 12));
				} else {
					$term = $_credit / $monthly_payment;
				}
			}
			$month_prec = $term;

			$g4 = $term * $monthly_payment;
			$month = Math.ceil($term);
		}

		$monSum = Math.round($g4*100)/100;

		$monthly_payment_final = $monSum - ($month - 1) * $monthly_payment;

		$interest = [];
		$principal = [];
		$principal_remaining = [];


		for ($x = 0; $x < $month - 1; $x++) {
			$interest[$x] = Math.round((($principal_sum + $residual_value) * $apr[$x])*100)/100;
			$principal[$x] = $monthly_payment - $interest[$x];
			$principal_remaining[$x] = $principal_sum;
			$principal_sum -= $principal[$x];
		}

		$interest[$month - 1] = Math.round(($monthly_payment_final - $principal_sum)*100)/100;
		$principal[$month - 1] = $principal_sum;
		$principal_remaining[$month - 1] = $principal_sum;

		$total = [Math.round($loan*100)/100,Math.round(($monSum - $loan)*100)/100,Math.round($monSum*100)/100];

		$item = [];

		for ($x = 0; $x < $month; $x++) {
			if ($x == $month - 1) {
				$item.push({'class': ($x % 2 ? 'even' : 'odd'), 'td1': $x + 1, 'td2': Math.round($principal_remaining[$x]*100)/100, 'td3': Math.round($principal[$x]*100)/100, 'td4': Math.round($interest[$x]*100)/100, 'td5': Math.round($monthly_payment_final*100)/100});
			} else {
				$item.push({'class': ($x % 2 ? 'even' : 'odd'), 'td1': $x + 1, 'td2': Math.round($principal_remaining[$x]*100)/100, 'td3': Math.round($principal[$x]*100)/100, 'td4': Math.round($interest[$x]*100)/100, 'td5': Math.round($monthly_payment*100)/100});
			}
		}

		$percentArray = {'0': Math.round(($total[1] / $total[0] * 100 / $month_prec)*100)/100, '1': Math.round(($total[1] / $total[0] * 100 / $month_prec * 12)*100)/100, '2': Math.round($apr_average*100)/100};
		$re = {'summa': Math.round($loan*100)/100, 'items': $item, 'total': $total,'percent': $percentArray};
		return $re;
	}

	this.aprc = function aprc($_CREDIT, $_TERM_MONTH, $_COMM_SUM, $_INV_DATE, $_M_DAT, $_M_SUM, $_DELIVE_SUM)
	{
		$s = 0;
		$time_intervals = [];

		$_INV_DATE = -1;

		for($trm = 1; $trm <= $_TERM_MONTH; $trm++) {

			$_M_DAT[$trm] = new Date($_M_DAT[$trm].getYear(), $_M_DAT[$trm].getMonth(), $_M_DAT[$trm].getDate(), 0, 0, 0);
			$time_intervals[$trm] = Math.round(($_M_DAT[$trm].getTime() - $_INV_DATE) / 86400 / 1000) / 365;
			$s += $_M_SUM[$trm];
		}

		if ($s > $_CREDIT - $_DELIVE_SUM || $_COMM_SUM > 0) {
			$m_aprc = $m_aprc1 = $m_aprc2 = $m_xpsum = $m_xpsum1 = $m_xpsum2 = 0;
			$m_aprcnew = 1;
			$m_delta = .1;
			$m_i = 0;
			while (true) {

				$m_xpsum = $_COMM_SUM + $_DELIVE_SUM;

				for ($trm = 1; $trm <= $_TERM_MONTH; $trm++) {
					$m_xpsum += $_M_SUM[$trm] / this.pow_ed(1 + $m_aprc, $time_intervals[$trm]);
				}
				switch (true) {
					case $m_i == 0:
							$m_xpsum1 = $m_xpsum;
							$m_aprc1 = $m_aprc;
							$m_aprc = $m_aprc+$m_delta;
							break;
						case $m_i == 1:
							$m_xpsum2 = $m_xpsum;
						$m_aprc2 = $m_aprc;
						$m_aprc = $m_aprc1 + $m_delta * ($_CREDIT - $m_xpsum1) / ($m_xpsum2 - $m_xpsum1);
						break;
						default:
							$m_aprcnew = $m_aprc2 + ($_CREDIT - $m_xpsum2) / (($m_xpsum - $m_xpsum1) / ($m_aprc - $m_aprc1));
							$m_aprc1 = $m_aprc2;
							$m_xpsum1 = $m_xpsum2;
							$m_aprc2 = $m_aprc;
						$m_xpsum2 = $m_xpsum;
						$m_aprc = $m_aprcnew;
				}
				if (Math.round($m_aprcnew*1000000)/1000000 == Math.round($m_aprc2*1000000)/1000000 || $m_i > 10) {
					$m_aprc = $m_aprcnew;
						break;
				}
				$m_i = $m_i + 1;
			}
			$_aprc  = $m_aprc * 100;
		} else {
				$_aprc  = 0;
		}
		return $_aprc ;
	}


	this.gpl = function ($sum, $term, $dwn, $comm, $apr)
	{
		$dwn = parseFloat($dwn);
		$comm = parseFloat($comm);
		$schedule = this.paymentSchedule($sum, $term, $apr, $dwn, 0, false);

		$payments = [];
		$dates = [];
		$date = 0;
		$i = 1;
		$month = 365.2425*24*60*60*1000/12;
		for(k in $schedule['items']) {
			$payments[$i] = $schedule['items'][k]['td5'];
			$date += $month;
			$dates[$i] = new Date(parseInt($date));
			$i++;
		}
		$gpl = this.aprc($sum - $dwn, $term, $comm, 0, $dates, $payments, 0);
		$gpl = Math.round($gpl*100)/100;
		return {'gpl': $gpl, 'payment': $schedule['items'][0]['td5']};
	}
}


/**
* Duplicates <input type=select> element and adds
* new ID to the new element. Requires reference to the original element
* as parameter
*/
/*function duplicateCategoryField(elem) {
   newelem = elem.cloneNode(false);
   newelem.value = "";

   var newname = elem.name;
   var start = newname.lastIndexOf('[');
   var end = newname.lastIndexOf(']');
   var number = newname.substring(start+1,end)*1 + 1;

   newname = newname.substring(0,start) + '[' + number + ']';
   newelem.name = newname;
   //alert(elem.options.item(1).);
   elem.parentNode.appendChild(document.createElement("br"));
   elem.parentNode.appendChild(newelem);

   newelem.options.add(elem.options);
}*/


function duplicateCategoryField($id)
{
	var elem = document.getElementById($id);
	$(elem).clone().insertAfter(elem);
}

function enableElement($id){
	document.getElementById($id).className="enabled";
}

function addFormField($el_id) {
	var elem = document.getElementById($el_id);
	var id = document.getElementById("id").value;

	id = (id - 1) + 2;
	document.getElementById("id").value = id;

	$(elem).clone().attr("id", 'field_'+id).appendTo($('#divTxt'));

	//elem = document.getElementById("field_"+id);
	//$("div#field_"+id+" a").attr("id", 'del_'+id);
	//$("div#field_"+id+" a").attr("rel", 'field_'+id);

	$("div#field_"+id+" a").attr({
    	id: "del_"+id,
    	rel: "field_"+id
    });

	//$("del_"+id).addClass("delete");
	//$("div#field_"+id+" a").removeClass("hidden");

	document.getElementById("del_"+id).className="delete";

	refresha();

    // $("#SubcategoryDiv").text($(elem).clone().attr("name"));
	//$("#divTxt").append("<div id='row" + id + "'".$(elem).clone()."</div>");
}

function removeFormField(id) {
	var id_n = document.getElementById("id").value;
	//$(id).remove();
	$(id).remove();
	//id_n = (id_n - 1);
	//document.getElementById("id").value = id_n;
}

function IsNumeric(sText)
{
	var ValidChars = "0123456789.";
	var IsNumber=true;
	var Char;

	for (i = 0; i < sText.length && IsNumber == true; i++)
	{
		Char = sText.charAt(i);
		if (ValidChars.indexOf(Char) == -1)
		{
			IsNumber = false;
		}
	}

	return IsNumber;
}


/**
 * Format price (eg return number with two digits after comma)
 *
 * @param float value Price
 * return float
 */
function formatPrice(value)
{
	var result= Math.floor(value) + ".";
	var cents = 100 * (value-Math.floor(value)) + 0.5;
	result += Math.floor(cents / 10);
	result += Math.floor(cents % 10);
	return result;
}


function refreshCheckoutTotal(changed_product_id)
{
	if (confirm("Vai tiešām vēlaties nomainīt preču daudzumu?"))
	{
		$("#CheckoutProductQuantity"+changed_product_id).val($("#Basket"+changed_product_id).val());

		$('#Basket'+changed_product_id).parent().parent().children('div:first').children('span').html(('Ls '+roundNumber($("#CheckoutProductQuantity"+changed_product_id).val() * $('#CheckoutProductPrice'+changed_product_id).val(), 2)).replace('.',','));
		
		$.ajax({
			url: webroot+"lv/basket/change_quantity/"+changed_product_id+"/"+$("#Basket"+changed_product_id).val(),
			cache: false
		});
	}
	else
	{
		$("#Basket"+changed_product_id).val($("#CheckoutProductQuantity"+changed_product_id).val());
	}

	var grand_total = 0;

	$(".product_quantity").each(function(a){
		var id = parseInt($(this).attr("rel"));
		var price = $("#CheckoutProductPrice"+id).val();

		if (IsNumeric($(this).val()))
		{
			grand_total += ($(this).val() * price);
		}
	});

	$(".total .price").html("Ls "+formatPrice(grand_total));

}