function formatMoney(n, c, d, t){
	var c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "," : d, t = t == undefined ? "." : t, s = n < 0 ? "-" : "", i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
	return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
};

EbayTodayCalc = Class.create({
	initialize: function(elemId, options) {

		this.elemId = elemId;
		this.calcElem = jQuery('#'+this.elemId);
		this.options = options || { };    
        
		this.currentMethodsData = this.options.defaultData;
		this.country = options.defaultCountry || 'usa';

		this.setToCountry();
		this.setAllWeights();		
		this.setDeliveryMethodsData(this.currentMethodsData);
		//this.setFirstActiveWeight();
		this.calculate();

        
        
		//if (this.country != 'usa') {
		//	this.setCountryFrom(this.country);
		//}
                
        for (var _currency in this.options.currencies) {
            if (this.options.currencies[_currency].country == this.country) {
                this.setSign(this.options.currencies[_currency].sign);
            }
        }
        

		return this;
	},
      
	calculate: function() {

		//var producePrice = $(this.elemId).down('.producePrice').value.replace(',','.').replace('[^0-9\.,]','');
		var producePrice = this.calcElem.find('.producePrice').first().val();
		producePrice = producePrice.replace(',','.').replace('[^0-9\.,]','');

		if (isNaN(producePrice)) {
			producePrice = parseFloat(producePrice);
			if (isNaN(producePrice)) {
				producePrice = 0;
			}
		}
		if (producePrice == '') {
			producePrice = 0;
		}
		this.setProducePrice(producePrice);
		producePrice = parseFloat(producePrice);
         
		//var produceDelivery = $(this.elemId).down('.produceDelivery').value.replace(',','.').replace('[^0-9\.,]','');
		var produceDelivery = this.calcElem.find('.produceDelivery').first().val();
		produceDelivery = produceDelivery.replace(',','.').replace('[^0-9\.,]','');

		if (isNaN(produceDelivery) || produceDelivery == '') {
			produceDelivery = parseFloat(produceDelivery);
			if (isNaN(produceDelivery) || produceDelivery == '') {
				produceDelivery = 0;
			}
		}
		this.setProduceDelivery(produceDelivery);
		produceDelivery = parseFloat(produceDelivery);
         
		if (isNaN(produceDelivery)) {
			produceDelivery = 0;
		}
         
		var producePriceAndDelivery = producePrice + produceDelivery;
		var ourComission = 0;
		settings = this.getCurrentSettings();
		if (producePrice > 0 || produceDelivery > 0) {
			minComission = settings.minComission;
			maxComission = settings.maxComission;

			ourComission = Math.round(producePriceAndDelivery * 0.1 * 100, 2) / 100;
			if (ourComission < minComission) {
				ourComission = minComission;
			} else if (ourComission > maxComission) {
				ourComission = maxComission;
			}
		}
         
		this.setOurComission(ourComission);
		this.setProducePriceAndDelivery(producePriceAndDelivery + ourComission);
         
		var deliveryPrice = this.getDeliveryPrice();
		if (deliveryPrice > 0) {
			var allPrice = parseFloat(deliveryPrice) + parseFloat(producePriceAndDelivery) + parseFloat(ourComission);
			//allPriceRUB = allPrice * settings.toRub;
			this.setAllPrice(allPrice);
		//this.setAllPriceRub(allPriceRUB);
		} else {
	// error
	}
	},
      
	setAllPrice: function (val) {
		val = Math.round(val*100, 2) / 100;
		val = formatMoney(val, 2, '.', ' ');
		//$(this.elemId).down('.allPrice').innerHTML = val;
		this.calcElem.find('.allPrice').first().html(val);
	},
      
	setAllPriceRub: function (val) {
		return ;
		val = Math.round(val*100, 2) / 100;
		val = formatMoney(val, 2, '.', ' ');
		//$(this.elemId).down('.allPriceRUB').innerHTML = val;
		this.calcElem.find('.allPriceRUB').first().html(val);
	},
      
	setOurComission: function (val) {
		val = formatMoney(val, 2, '.', ' ');
		//$(this.elemId).down('.ourComission').innerHTML = val;
		this.calcElem.find('.ourComission').first().html(val);
	},
      
	setProducePriceAndDelivery: function (val) {
		val = Math.round(val*100, 2) / 100;
		val = formatMoney(val, 2, '.', ' ');
		//$(this.elemId).down('.producePriceAndDelivery').innerHTML = val;
		this.calcElem.find('.producePriceAndDelivery').first().html(val);
	},
      
	setProduceDelivery: function (val) {
		if (val == 0) {
			val = '';
		}
		//$(this.elemId).down('.produceDelivery').value = val;
		this.calcElem.find('.produceDelivery').first().val(val);
	},
      
	setProducePrice: function (val) {
		if (val == 0) {
			val = '';
		}
		//$(this.elemId).down('.producePrice').value = val;
		this.calcElem.find('.producePrice').first().val(val);
	},
      
	setSign: function(sign) {
/*
		$(this.elemId).down('.producePriceSign').innerHTML = sign;
		$(this.elemId).down('.produceDeliverySign').innerHTML = sign;
		$(this.elemId).down('.ourComissionSign').innerHTML = sign;
		$(this.elemId).down('.producePriceAndDeliverySign').innerHTML = sign;
		$(this.elemId).down('.deliveryPriceSign').innerHTML = sign;
		$(this.elemId).down('.allPriceSign').innerHTML = sign;
*/
		this.calcElem.find('.producePriceSign').first().html(sign);
		this.calcElem.find('.produceDeliverySign').first().html(sign);
		this.calcElem.find('.ourComissionSign').first().html(sign);
		this.calcElem.find('.producePriceAndDeliverySign').first().html(sign);
		this.calcElem.find('.deliveryPriceSign').first().html(sign);
		this.calcElem.find('.allPriceSign').first().html(sign);
	},
      
	getCurrentSettings: function () {
		country = this.country;
		for (var _currency in this.options.currencies) {
			if (this.options.currencies[_currency].country == country) {
				return this.options.currencies[_currency];
			}
		}
	},
      
	setCountryFrom: function(country, countryStore) {

		countryTo = this.calcElem.find('.deliveryToCountry').first().val()
		
		this.country = country.toLowerCase();
		for (var _currency in this.options.currencies) {
			if (this.options.currencies[_currency].country == country) {
				this.setSign(this.options.currencies[_currency].sign);
			}
		}
		this.countryChange();
		this.setToCountry(countryTo);
		this.calculate();
		try {
			if (countryStore) {
				//$(this.elemId).down('.deliveryStoreCountry').innerHTML = countryStore;
				calcElem.find('.deliveryStoreCountry').first().html(countryStore);
			}
		} catch (e) {}
        
	},
      
	getCountryFrom: function() {
		return this.country;
	},
      
	setDeliveryMethodsData: function(data) {

		var calc = this;
        
		result = '<ul>';
		i = 1;
        
		data.each(function(v) {
			addon = ' checked="checked"';
			if (i>1) {
				addon = '';
			}            
			// onchange="getCalculator().deliveryMethodChange()"
            if(v.id != 25) {
                result += '<li><div class="'+calc.elemId+'-deliveryMethodPrice-'+v.id+' calcDeliveryMethodPrice"></div><label><input type="radio" name="'+calc.elemId+'-deliveryMethod" methodId="'+calc.elemId+'-deliveryMethod-'+v.id+'" class="deliveryMethod" value="'+v.id+'"'+addon+'>'+v.name+'</label><br /><div class="calc-delivery-method-desc">'+v.descr+'</div></li>';            			
                i++;
            }
		});

		result += '</ul>';
        
		//$(this.elemId).down('.deliveryMethods').innerHTML = result;
		this.calcElem.find('.deliveryMethods').first().html(result);

		// Обработка onchange для RadioButton'ов
		/*
		$$('#' + this.elemId + ' .deliveryMethod').each(function(e){
			e.onclick =	 function(){
			calc.deliveryMethodChange()
		}
		*/
		this.calcElem.find('.deliveryMethod').click(function(){
			calc.deliveryMethodChange();
		});
        
		this.setMethodWeight();
        
	},
      
	setDeliveryMethods: function() {
		countryFrom = this.country;
		countryTo = this.getToCountry();
		var calc = this;
        
		new Ajax.Request('/package/getDeliveryMethodsForCountry/', {
			parameters: {
				'country_id': countryTo,
				'located': countryFrom
			},
			onComplete: function(transport) {
				methodsData = eval('(' + transport.responseText + ')');
				calc.setDeliveryMethodsData(methodsData);
			}
		});
        
	},
      
	getToCountry: function() {
		//return $(this.elemId).down('.deliveryToCountry').value;
		return this.calcElem.find('.deliveryToCountry').val();
	},
      
	setAllWeights: function () {
		country = this.country;
		for (var _currency in this.options.currencies) {
			if (this.options.currencies[_currency].country == country) {
                /*
				sel = $(this.elemId).down('.produceWeight');
				sel.innerHTML = '';
				*/
				sel = this.calcElem.find('.produceWeight');
				sel.html('');
				for (i = 0; i < this.options.currencies[_currency].allWeight.length; i++) {
/*
					temp = 'до ' + this.options.currencies[_currency].allWeight[i] + ' грамм  ';
					opt = document.createElement("option");
					optTxt = document.createTextNode(temp);
					opt.appendChild(optTxt);
					opt.setAttribute("value", this.options.currencies[_currency].allWeight[i]);
					sel.appendChild(opt);
*/
					sel.append('<option value="'+this.options.currencies[_currency].allWeight[i]+'">'+ 'до ' + this.options.currencies[_currency].allWeight[i] + ' грамм  '+'</option>');
				}
				break;
			}
		}
	},
      
	setFirstActiveWeight: function () {
		
		//var calc = this;
		/*
		weights = $(this.elemId).down('.produceWeight').childElements();
		select = true;
		weights.each(function(weight) {
			if (weight.disabled) {
                
			} else {
				if (select) {
					$(calc.elemId).down('.produceWeight').value = weight.value;
				}
				select = false;
			}
		})
		*/

		this.calcElem.find('.produceWeight').val(this.calcElem.find('.produceWeight option:enabled').first().val());

/*
		calc.calcElem.find('.produceWeight').children().each(function(i, weight){
			if (!weight.disabled) {
				calc.calcElem.find('.produceWeight').val(weight.value);
				return false;
			}
		});
		*/
	},
      
	setToCountry: function (countryTo) {

		country = this.country;

		for (var _currency in this.options.currencies) {
			if (this.options.currencies[_currency].country == country) {
				//sel = $(this.elemId).down('.deliveryToCountry');
				//sel.innerHTML = '';
				sel = this.calcElem.find('.deliveryToCountry').first();
				sel.html('');
				
				for (i = 0; i < this.options.currencies[_currency].toCountries.length; i++) {
					temp = this.options.currencies[_currency].toCountries[i];
					if (temp.id) {
						//opt = document.createElement("option");
						//optTxt = document.createTextNode(temp.name);
						//opt.appendChild(optTxt);
						//opt.setAttribute("value", temp.id);
						//sel.appendChild(opt);
						sel.append('<option value="'+temp.id+'">'+temp.name+'</option>');
					}
				}

				//sel.val(countryTo);

				if(sel.children('option[value="'+countryTo+'"]').length) {
					sel.val(countryTo);
				}else{
					this.countryChange();
				}

				break;
			}
		}
	},
      
	countryChange: function () {
		countryFrom = this.country;
		countryTo = this.getToCountry();
		var calc = this;

		if (countryTo == '3159') {
			this.calcElem.find('.deliveryToCity').first().css({display : 'table-row'});
		} else {
			this.calcElem.find('.deliveryToCity').first().css({display : 'none'});
		}
                         
        scriptName = ((constants.isLocal == 1) ? '/getDeliveryMethodsData.php/?' : '/get-delivery-methods/?');
        
            new Ajax.Request(scriptName + countryTo + '_' + countryFrom, {  
		    //new Ajax.Request('/get-delivery-methods/?' + countryTo + '_' + countryFrom, {
		    //new Ajax.Request('/getDeliveryMethodsData.php/?' + countryTo + '_' + countryFrom, {
			    method: 'get',
			    onComplete: function(transport) {
				    oldMethodId = calc.getSelectedDeliveryMethod();
				    calc.currentMethodsData = transport.responseText.evalJSON(true);        
				    calc.setDeliveryMethodsData(calc.currentMethodsData);
				    calc.setAllWeights();
				    calc.setMethodWeight();
			    }
		    });
        
	},
      
	weightChange: function() {
		this.setMethodPrice();
	},
      
	deliveryMethodChange: function () {
		this.setMethodWeight();
	},
      
	getSelectedDeliveryMethod: function() {
/*
		methods = $$('#' + this.elemId + ' .deliveryMethod');

		selected = 0;
		methods.each(function(method) {
            
			if (method.checked) {
				selected = method.value;
			}
		});
 */

		selected = 0;
		this.calcElem.find('.deliveryMethod').each(function(i, method){            
            if (method.checked) {
				selected = method.value;                
				return false;
			}
		});

		return selected;
	},
      
	setMethodWeight: function() {
          
		methodId = this.getSelectedDeliveryMethod();
		selectedWeight = this.getSelectedWeight();
          
		var calc = this;          
          
		if (this.currentMethodsData) {

/*
			weights = $(this.elemId).down('.produceWeight').childElements();

			var needSelectFirst = true;
			var oldWeight = $(this.elemId).down('.produceWeight').value;	
              
			weights.each(function(weight) {
                  
				calc.currentMethodsData.each (function(method, key){
					// выбран метод
					if (methodId == method.id) {
                        
						enabled = false;
						// доступные веса
						for (var w in method.data) {
							if (w == weight.value) {
								enabled = "disabled";
								break;
							}
						}
						if (enabled) {
							weight.disabled = "";
							if (weight.value == oldWeight) {
								needSelectFirst = false;
							}
						} else {
							weight.disabled = "disabled";
						}
          
					}
				});
			});
              
			if (needSelectFirst == true) {
				this.setFirstActiveWeight();
			}
  */
			weights = this.calcElem.find('.produceWeight').first().children();
			var needSelectFirst = true;
			var oldWeight = this.calcElem.find('.produceWeight').first().val();

			jQuery.each(weights, function(i, weight){
				jQuery.each(calc.currentMethodsData, function(i, method){
					// выбран метод
					/*if (methodId == method.id) {
						enabled = false;
						// доступные веса
						for (var w in method.data) {
							if (w == weight.value) {
								//enabled = "disabled";
								break;
							}
						}
						if (enabled) {
							//weight.disabled = "";
							if (weight.value == oldWeight) {
								needSelectFirst = false;
							}
						} else {
							//weight.disabled = "disabled";
						}
					}*/
				});
			});

			//if (needSelectFirst == true) {
				//this.setFirstActiveWeight();
			//}
		}
	
		this.setMethodPrice();
	},
      
	getSelectedWeight: function() {
		//return $(this.elemId).down('.produceWeight').value;
		return this.calcElem.find('.produceWeight').val();
	},
      
	setMethodPrice: function() {
        
		price = 0;
		weigth = this.getSelectedWeight();
		var calc = this;
         
		methodId = this.getSelectedDeliveryMethod();        
         
        var sign = '';
        for (var _currency in calc.options.currencies) {
            if (calc.options.currencies[_currency].country == calc.country) {
                sign = calc.options.currencies[_currency].sign;
            }
        }
         
		if (this.currentMethodsData) {
            price = null;
			jQuery.each(calc.currentMethodsData, function(i, method){
				if (methodId == method.id) {
					for (var w in method.data) {
						if (parseFloat(weigth) <= parseFloat(w)) {

							price = method.data[w];
							break;
						}
					}
				}
                
                for (var w in method.data) {                    
                    var insertion = '';
                    if (parseFloat(weigth) <= parseFloat(w)) {
                        var oneKgPrice = 1000 *  method.data[w] / w;
                        insertion = formatMoney(method.data[w], 2, '.', ' ')+' '+sign+'<div>'+formatMoney(oneKgPrice, 2, '.', ' ')+sign+' за 1 кг.<br />при выбранном<br />весе посылки</div>';         
                        jQuery('.' + calc.elemId + '-deliveryMethodPrice-' + method.id).html(insertion);                 
                        break;
                    }                                        
                }
                
                
                    
                var maxMethodWeight = 0;            
                jQuery.each(method.data, function(objKey, objVal){
                    maxMethodWeight = objKey;                        
                });
                
                var methodActive = true;
                if (parseFloat(weigth) > maxMethodWeight) {
                    methodActive = false;
                    jQuery('.' + calc.elemId + '-deliveryMethodPrice-' + method.id).html('Превышен макс. вес');  
                }    
                
                if (methodActive) {
                    jQuery('input[methodId=' + calc.elemId + '-deliveryMethod-' + method.id + ']').attr('disabled', '');  
                } else {
                    jQuery('input[methodId=' + calc.elemId + '-deliveryMethod-' + method.id + ']').attr('disabled', 'disabled');  
                }                
                
                
                if (jQuery('input[methodId=' + calc.elemId + '-deliveryMethod-' + method.id + ']').attr('checked') &&
                    jQuery('input[methodId=' + calc.elemId + '-deliveryMethod-' + method.id + ']').attr('disabled')) {
                    
                    jQuery.each(jQuery('input[name=' + calc.elemId + '-deliveryMethod'+']'), function(objKey, objVal){                        
                        if (!jQuery(objVal).attr('disabled')) {
                            jQuery(objVal).attr('checked', 'checked');
                            methodId = jQuery(objVal).val();
                            return false;                            
                        }
                    });
                }
                
                if (price === null) {
                    if (methodId == method.id) {
                        for (var w in method.data) {
                            if (parseFloat(weigth) <= parseFloat(w)) {

                                price = method.data[w];
                                break;
                            }
                        }
                    }
                }
                
                
			});
			/*
			calc.currentMethodsData.each (function(method, key){
				if (methodId == method.id) {
					for (var w in method.data) {
						if (weigth == w) {
                            
							price = method.data[w];
							break;
						}
					}
      
				}
			});
			*/
		}
         
		if (price > 0) {
			this.setDeliveryPrice(price);
			this.calculate();
		}
	},
      
	getDeliveryPrice: function () {
		//delivprice = $(this.elemId).down('.deliveryPrice').innerHTML;
		delivprice = this.calcElem.find('.deliveryPrice').first().html();
		delivprice = delivprice.replace(/\s/i,'');
		return delivprice;
	},
      
	setDeliveryPrice: function (val) {
		val = formatMoney(val, 2, '.', ' ');
		this.calcElem.find('.deliveryPrice').first().html(val);
		//$(this.elemId).down('.deliveryPrice').innerHTML = val;
	}/*,
      
      formatMoney: function(c, d, t){
            var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "," : d, t = t == undefined ? "." : t, s = n < 0 ? "-" : "", i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
            return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
      }*/
      
});

jQuery(document).ready(function(){
    jQuery('.calculator .country a').click(function(){

        link = jQuery(this);

        link.parent().parent().find('.country').each(function(){
                jQuery(this).removeClass('current');
        });

        link.parents('.calculator').first().find('.deliveryStoreCountry').first().html(link.html());
        link.parent().addClass('current');
    });
});

	
/*
    function unselectAllCountries(elemId) {

		

        $$( '#' + elemId + ' .country').each(function (v) {
            v.style.backgroundColor = 'white';
            v.firstChild.style.color = '#834119';            
            v.firstChild.style.textDecoration = 'underline';
        });
    }
    
    function setCurrentCountry(obj) {
		if(obj.up('#calculator')) {
			unselectAllCountries('calculator');
		}else{
			unselectAllCountries('smartmenu-calculator');
		}
        
        obj.style.backgroundColor = '#E6F3E5';
        obj.firstChild.style.textDecoration = 'none';
        obj.firstChild.style.color = 'black';
    }
*/
