var DutyCalculationProductInterface = Class.create();

var sendingShipmentWeightRequest = false;

DutyCalculationProductInterface.prototype = ({

	initialize: function (config)
	{
		/*
		this.body = null;
		this.winContainer = 'win-form';
		this.options = {};
		this.options['navigatorContainer'] 			= config['navigatorContainer'];
		this.options['navigatorContainerUrl'] 		= config['navigatorContainerUrl'];
		this.options['societyDepartmentContainer'] 	= config['societyDepartmentContainer'];

		this.options['loadingEffectID'] = 'loadingEffect';
		this.options['loadingEffectCSS']= 'winLoadingEffect';
		*/
		this.acceptorId	 	= config.acceptor;
		this.listenerId	 	= config.listen;
		this.url			= config.url;
		this.containerId	= config.containerId;
		this.itemsFieldId   = (config.itemsField)?config.itemsField:'';
		this.countryField	= (config.countryField)?config.countryField:'dtc_country_to';
		this.companyField	= 'dtc_is_company';
		this.importActivityField = 'dtc_import_activity'
		this.url_param		= (config.url_param)?config.url_param:'subcategory';
		this.is_sub			= (config.issub)? config.issub : false;
		this.is_item		= (config.isitem)? config.isitem : false;
		this.ajaxLoadingEffect = null;
		trigger				 = (config.start_on_load)?config.start_on_load:false;
		this.productNameFieldId = config.productNameField;
		this.extCategoryFieldId = (config.extCategoryField) ? config.extCategoryField : false;
		this.dutyRuleListenerId = (config.dutyRuleListener) ? config.dutyRuleListener : false;
		this.antidumpingListenerId = (config.antidumpingListener) ? config.antidumpingListener : false;
		this.quantityBlock = (config.quantityFieldsContainer)?config.quantityFieldsContainer:false;
		this.quantityUnitFieldId = (config.quantityUnitField)?config.quantityUnitField:false;		
		this.weightListenerId 	= (config.weightListener)?config.weightListener:false;
		this.weightBlock = (config.weightFieldsContainer)?config.weightFieldsContainer:false;
//		this.isCompanyFieldId = false;
//		this.importActivity = false;		
		this.countryManufactureBlock = (config.countryManufactureBlock) ? config.countryManufactureBlock : false;
//		if (this.is_item) {
//			this.isCompanyFieldId = 'dtc_is_company';
//			this.importActivity = 'dtc_import_activity';
//		}
		
		this.isWidget = (config.isWidget) ? config.isWidget : false;
		
		if(trigger)
		{
			Event.observe(document, 'dom:loaded', this.setCatchers.bindAsEventListener(this) );
		}
		else
		{
			this.setCatchers();
		}	
	},

	setCatchers: function()
	{			
		Event.observe($(this.listenerId), 'change', this.onChangeSelect.bindAsEventListener(this));
		if (this.is_item) {
			if ($(this.dutyRuleListenerId))
			{
				Event.observe($(this.dutyRuleListenerId), 'change', this.showQuantityBlock.bind(this));
				Event.observe($(this.weightListenerId), 'change', this.showWeightBlock.bind(this));
				Event.observe($(this.antidumpingListenerId), 'change', this.showCountryManufactureBlock.bind(this));
			}
			
			if ($(this.companyField))
			{
				this.companyChangeFunction = this.onChangeSelect.bind(this); 
				this.importActivityChangeFunction = this.onChangeSelect.bind(this);
				Event.observe($(this.companyField), 'change', this.companyChangeFunction);
				Event.observe($(this.importActivityField), 'change', this.importActivityChangeFunction);
			}
		}
	},
	
	showQuantityBlock: function() {
		if ($(this.dutyRuleListenerId).value != 0 && $(this.dutyRuleListenerId).value != '') {
			if ($(this.quantityBlock).style.display == 'none') {
				Element.down($(this.quantityBlock), 'select').selectedIndex = 0;
				
				if ((this.isWidget && $(this.dutyRuleListenerId).value != 'pcs') || !this.isWidget)
				{
					$(this.quantityBlock).show();
				}
				else
				{
					$(this.quantityBlock).hide();
				}
				
				var inputs = $(this.quantityBlock).getElementsByTagName('input');
				for (var i = 0; i < inputs.length; i++)
				{		
					Element.extend(inputs[i]);
					if ($(inputs[i].id).hasClassName('txt'))
					{
						if (!$(inputs[i].id).hasClassName('txt-sm'))
						{
							$(inputs[i].id).addClassName('txt-sm');
						}
						$(inputs[i].id).value = exampleProductQuantity;
						break;
					}
					
//					if (this.isWidget && $(this.dutyRuleListenerId).value != 'pcs')
//					{
//						$(inputs[i].id).value = '';
//					}						
				}				
			}
		}
		else {
			$(this.quantityBlock).hide();
		}
	},
	
	showWeightBlock: function() {
		if ($(this.weightListenerId).value != 0) {
			if ($(this.weightBlock).style.display == 'none') {
				$(this.weightBlock).show();
				if (Element.down($(this.weightBlock), 'select'))
				{
					Element.down($(this.weightBlock), 'select').selectedIndex = 0;
					
					var inputs = $(this.weightBlock).getElementsByTagName('input');
					for (var i = 0; i < inputs.length; i++)
					{		
						Element.extend(inputs[i]);
						if ($(inputs[i].id).hasClassName('txt'))
						{						
							if (!$(inputs[i].id).hasClassName('txt-sm'))
							{
								$(inputs[i].id).addClassName('txt-sm');
							}
							$(inputs[i].id).value = exampleProductWeight;
							break;
						}
					}
				}
			}
		}
		else {
			$(this.weightBlock).hide();
		}		
	},
	
	showCountryManufactureBlock: function() {
		if ($(this.antidumpingListenerId).value != 0) {
			if ($(this.countryManufactureBlock).style.display == 'none') {
				Element.down($(this.countryManufactureBlock), 'select').value = '';
				$(this.countryManufactureBlock).show();
			}								
		}
		else {
			$(this.countryManufactureBlock).hide();
		}		
	},		
	
	onChangeSelect: function(objEvent)
	{	
//		if (this.itemsFieldId) {
//			if ($(this.itemsFieldId) == null) {
//				Event.stopObserving($(this.dutyRuleListenerId), 'change', this.showQuantityBlock.bind(this));
//				Event.stopObserving($(this.weightListenerId), 'change', this.showWeightBlock.bind(this));
//				Event.stopObserving($(this.antidumpingListenerId), 'change', this.showCountryManufactureBlock.bind(this));
//				Event.stopObserving($(this.isCompanyFieldId), 'change', this.onChangeSelect.bind(this));
//				Event.stopObserving($(this.importActivity), 'change', this.onChangeSelect.bind(this));				
//			}
//		}
		
		var productCategoryPattern = /dtc_product_category|category([0-9])*$/;

		if($(this.listenerId).value == '' || $(this.listenerId).value == ' ' || $(this.listenerId).value == '  ')
		{
//			if (!this.is_item) {
//				Event.stopObserving($(this.dutyRuleListenerId), 'change');
//				Event.stopObserving($(this.weightListenerId), 'change');
//				Event.stopObserving($(this.antidumpingListenerId), 'change');
//				Event.stopObserving($(this.isCompanyFieldId), 'change');
//				Event.stopObserving($(this.importActivity), 'change');	
//			}
				
			if ($(this.dutyRuleListenerId))
			{
				if ($(this.quantityBlock))
				{
					$(this.dutyRuleListenerId).value = 0;
					$(this.quantityBlock).hide();
				}
				if ($(this.weightBlock))
				{
					$(this.weightListenerId).value = 0;
					$(this.weightBlock).hide();
				}
				if ($(this.countryManufactureBlock))
				{
					$(this.antidumpingListenerId).value = 0;
					$(this.countryManufactureBlock).hide();
				}
			}

			if ($(this.acceptorId)) {
				$(this.acceptorId).disabled = true;
				$(this.acceptorId).selectedIndex = 0;
			}
			
			if(this.listenerId.match(productCategoryPattern)){
//				postfix = this.listenerId.substr("dtc_product_category".length)
				$(this.itemsFieldId).disabled = true;
				$(this.itemsFieldId).value = '';
			}			
		}
		else
		{					
			if ((!this.is_item && !this.is_sub) || this.is_sub) {
				if ($(this.dutyRuleListenerId))
				{
					$(this.dutyRuleListenerId).value = 0;
					$(this.quantityBlock).hide();
					$(this.weightListenerId).value = 0;
					$(this.weightBlock).hide();
					if ($(this.antidumpingListenerId))
					{
						$(this.antidumpingListenerId).value = 0;
						$(this.countryManufactureBlock).hide();
					}
				}
			}
			
			if(this.ajaxLoadingEffect!= null)
			{
				if(Prototype.Browser.IE)
				{
					this.ajaxLoadingEffect.removeLoadingEffect();
					this.ajaxLoadingEffect = null;
				}
			}
			
			this.ajaxLoadingEffect = new AjaxLoadingEffect({'containerId':this.containerId});
			this.ajaxLoadingEffect.setLoadingEffect();			
			if(this.listenerId.match(productCategoryPattern))
			{
//				postfix = this.listenerId.substr("dtc_product_category".length)
				
				$(this.itemsFieldId).disabled = true;
				$(this.itemsFieldId).value = '';
				
				if ($(this.dutyRuleListenerId))
				{
					$(this.dutyRuleListenerId).value = 0;
					this.showQuantityBlock();
					$(this.weightListenerId).value = 0;				
					this.showWeightBlock();
				}
			}

			var isCompany;
			var importActivity;
			var signleProduct;

			if ($(this.companyField))
			{
				if ($(this.companyField).value == '') {
					isCompany = -1;
				}
				else {
					isCompany = $(this.companyField).value;
				}
				
				importActivity = ($(this.importActivityField).value == '') ? -1 : $(this.importActivityField).value;		
			}
			else
			{
				isCompany = -1;
			}

			if ($('product_keys')) {
				if ($('product_keys').value != '')
				{
					singleProduct = 0;
				}
				else
				{
					singleProduct = 1;
				}
			}
			else {
				singleProduct = 1;
			}			
			
			
			var requestUrl = this.url 
								+ this.url_param + '/' 
								+ this.acceptorId + '/' 
								+ $(this.listenerId).value + '/' 
								+ $(this.countryField).value + '/' 

			if (this.extCategoryFieldId) {
				requestUrl += $(this.extCategoryFieldId).value + '/'; 
			}								
								
			if (this.is_item)
			{
				if ($(this.dutyRuleListenerId))
				{
					requestUrl += isCompany + '/' 
						+ importActivity + '/'
						+ singleProduct + '/';
				}
			}

			requestUrl += encodeURIComponent($(this.productNameFieldId).value) + '/';
			
			new Ajax.Request(requestUrl, {
	    	    'onSuccess':this.successLoading.bind(this)
			});
	            
		}	
	},
	
	successLoading: function(objResponce)
	{		
		
		responceText = objResponce.responseText;
		// $(this.acceptorId + 'Container' in case of cutom select
		if ($(this.acceptorId)) {
			
			Element.replace( $(this.acceptorId ), responceText );
			
//			for (var i = 0; i < $(this.acceptorId).options.length; i++)
//			{
//				
//				if (!isNumber($(this.acceptorId).options[i].value))
//				{
//					$(this.acceptorId).options[i].disabled = true;
//				}
//			}
		}	
		
		if(!this.is_sub && !this.is_item)
		{
			new DutyCalculationProductInterface({
				'acceptor': this.itemsFieldId,
				'listen': this.acceptorId,
				'url': this.url,
				'containerId':this.containerId,
				'issub': true,
				'url_param' : 'items',
				'productNameField':this.productNameFieldId,
				'extCategoryField':this.extCategoryFieldId,				
				'dutyRuleListener' : this.dutyRuleListenerId,
				'antidumpingListener' : this.antidumpingListenerId,
				'quantityUnitField' : this.quantityUnitFieldId,
				'quantityFieldsContainer' : this.quantityBlock,
				'itemsField' : this.itemsFieldId,
				'weightListener' : this.weightListenerId,
				'weightFieldsContainer' : this.weightBlock,
				'countryManufactureBlock' : this.countryManufactureBlock,
				'countryField' : this.countryField,
				'isWidget' : this.isWidget
			});
		}
		if (this.is_sub) {
			
			if ($(this.dutyRuleListenerId))
			{
				Event.stopObserving($(this.dutyRuleListenerId), 'change', this.showQuantityBlock.bindAsEventListener(this));
				Event.stopObserving($(this.weightListenerId), 'change', this.showWeightBlock.bindAsEventListener(this));
				Event.stopObserving($(this.antidumpingListenerId), 'change');
			}
			
			var stopObserveItem;
			for (var i = 0; i < DutyCalculationItems.length; i++)
			{
				if (DutyCalculationItems[i].itemsFieldId == this.itemsFieldId) {
					stopObserveItem = DutyCalculationItems[i];
					DutyCalculationItems.splice(i, 1);
				}
			}		
			
			if (stopObserveItem)
			{				
				if ($(this.companyField))
				{
					Event.stopObserving($(this.companyField), 'change', stopObserveItem.companyChangeFunction);
					Event.stopObserving($(this.importActivityField), 'change', stopObserveItem.importActivityChangeFunction);
				}
			}
			
			if (this.quantityUnitFieldId)
			{
				var newItem;			
				newItem = new DutyCalculationProductInterface({
								'acceptor': this.quantityUnitFieldId,
								'listen': this.itemsFieldId,
								'itemsField' : this.itemsFieldId,
								'url': this.url,
								'containerId':this.containerId,
								'isitem': true,
								'url_param' : 'duty_rule',
								'productNameField':this.productNameFieldId,
								'extCategoryField':this.extCategoryFieldId,
								'dutyRuleListener' : this.dutyRuleListenerId,
								'antidumpingListener' : this.antidumpingListenerId,
								'quantityUnitField' : this.quantityUnitFieldId,
								'quantityFieldsContainer' : this.quantityBlock,
								'weightListener' : this.weightListenerId,
								'weightFieldsContainer' : this.weightBlock,
								'countryManufactureBlock' : this.countryManufactureBlock,
								'countryField' : this.countryField,
								'isWidget' : this.isWidget
				});
				DutyCalculationItems.push(newItem);
			}
		}
		
		if(this.ajaxLoadingEffect != null){
			this.ajaxLoadingEffect.removeLoadingEffect();
		}		
	}

	
	
});


/**

*/
var DutyCalculationCountriesInterface = Class.create();

DutyCalculationCountriesInterface.prototype = ({

	initialize: function (config)
	{
		this.blockId					= config.blockId;
		this.sekoAdAllow		 		= false;
		this.countryToFieldId	 		= config.import_to_field;
		this.provinceToFieldId	 		= config.import_to_province_field;	
		this.countryFromFieldId	 		= (config.import_from_field) ? config.import_from_field : false;
		this.url				 		= config.url;		
		this.ajaxLoadingEffect	 		= null;
		this.containerId		 		= config.containerId;
		this.productNameFieldId			= config.productNameField;
		this.categoryFieldId	 		= config.categoryField;	
		this.subCategoryFieldId	 		= config.subCategoryField;
		this.itemsFieldId		 		= config.itemsField;
		this.countryManufactureFieldId 	= (config.countryManufactureField) ? config.countryManufactureField : false;
		this.hCurrencies		 		= (config.countryCurrencies) ? config.countryCurrencies : false;
		this.currencyField		 		= (config.currencyField) ? config.currencyField : false;
		
		this.companyListenerId 			= (config.companyListener) ? config.companyListener : false;
		this.companyFieldId				= (config.companyField) ? config.companyField : false;
		
		this.importActivityFieldId		= (config.importActivityField) ? config.importActivityField : false;
		
		this.weightBlock				= (config.weightBlock) ? config.weightBlock : false;
		this.weightTaxListenerId 		= (config.weightTaxListener) ? config.weightTaxListener : false;
		this.costTaxListenerId 			= (config.costTaxListener) ? config.costTaxListener : false;
		
		var trigger				 		= (config.already_loaded)? config.already_loaded : false;
		
//		this.alreadyLoaded 				= trigger;
		
		this.dutyRuleListenerId			= (config.dutyRuleListener) ? config.dutyRuleListener : false;
		this.antidumpingListenerId		= (config.antidumpingListener) ? config.antidumpingListener : false;
		this.quantityBlock			 	= (config.quantityFieldsContainer)? config.quantityFieldsContainer : false;
		this.quantityUnitFieldId 		= (config.quantityUnitField)? config.quantityUnitField : false;
		
		this.weightListenerId			= (config.weightListener) ? config.weightListener : false;
		
		this.countryManufactureBlock 	= (config.countryManufactureBlock) ? config.countryManufactureBlock : false;		
		
		this.notCoveredFieldId			= (config.notCoveredField);
		
		this.productValueFieldId		= (config.productValueField);
		this.productValueCurrencyFieldId= (config.productValueCurrencyField);
		
		if(!trigger)
		{
			Event.observe(document, 'dom:loaded', this.setCatchers.bind(this) );			
		}
		else
		{	
			this.setCatchers();
			this.disabledInputs();
		}
		
		this.autosuggest = (config.autosuggest) ? new autoSuggest({'url':config.autoSuggestUrl, 'elementId':this.productNameFieldId, 'numberOfOptions':7}) : false;
	},

	setCatchers: function()
	{		
		this.bfx=this.onChangeSelect.bind(this);
		
		Event.observe( $(this.productNameFieldId), 'change', this.bfx );
		
		Event.observe( $(this.countryToFieldId), 'change', this.bfx );
		if (this.countryFromFieldId)
		{
			Event.observe( $(this.countryFromFieldId), 'change', this._showhideGetQuoteBtn.bind(this) );
//			Event.observe( $(this.countryFromFieldId), 'change', this._setManufactureCountry.bind(this) );			
//			Event.observe( $(this.countryFromFieldId), 'change', this._setDefaultCurrency.bind(this) );
			this._showhideGetQuoteBtn();
		}
		
//		if ($('dtc_shipping_cost'))
//		{
			Event.observe( $('dtc_shipping_cost'), 'change', this.checkCifForShipmentWeight.bind(this) );
			Event.observe( $('dtc_shipping_cost_currency'), 'change', this.checkCifForShipmentWeight.bind(this) );

			Event.observe( $('dtc_insurance_cost'), 'change', this.checkCifForShipmentWeight.bind(this) );
			Event.observe( $('dtc_insurance_costs_currency'), 'change', this.checkCifForShipmentWeight.bind(this) );
			
			Event.observe( $(this.productValueFieldId), 'change', this.checkCifForShipmentWeight.bind(this) );
			Event.observe( $(this.productValueCurrencyFieldId), 'change', this.checkCifForShipmentWeight.bind(this) );			
//		}		
		
		if (this.companyListenerId)
		{
			Event.observe($(this.companyListenerId), 'change', this.showImporterDetails.bind(this));
			Event.observe($(this.companyFieldId), 'change', this.showImportActivity.bind(this));
			Event.observe($(this.importActivityFieldId), 'change', this.showImportActivityFields.bind(this));
		}
		
		Event.observe($(this.notCoveredFieldId), 'change', this.showProductFields.bind(this));		
	},
	
	onChangeSelect: function(objEvent)
	{
		if (objEvent.target == $(this.productNameFieldId) && this.autosuggest)
		{
			if (!this.autosuggest.allowCategoryPrediction)
			{
				return false;
			}
		}
		
		this.checkCifForShipmentWeight();
		
		if ($(this.categoryFieldId) == null)
		{
			Event.stopObserving( $(this.countryToFieldId), 'change', this.bfx);
			return;				
		}

		if( $(this.countryToFieldId).value == 0)
		{
			this.disabledInputs();
			$(this.weightTaxListenerId).value = 0;
			$(this.costTaxListenerId).value = 0;
			$(this.companyListenerId).value = 0;
			$(this.weightBlock).hide();			
			$(this.quantityBlock).hide();
			
			$(this.antidumpingListenerId).value = 0;
			$(this.countryManufactureBlock).hide();
			
			this.hideCompanyIndividual();	
			this.hideImportActivity();
			this.hideImportedCost();
			this.hideImportedWeight();
		}
		else
		{					
			if(this.ajaxLoadingEffect != null && Prototype.Browser.IE)
			{
				this.ajaxLoadingEffect.removeLoadingEffect();
			}
			
			this.ajaxLoadingEffect = new AjaxLoadingEffect({'containerId':this.containerId});
			this.disabledInputs();
			this.ajaxLoadingEffect.setLoadingEffect();			
			new Ajax.Request(this.url + 'country_to/' + this.categoryFieldId + '/' + $(this.countryToFieldId).value + '/' + encodeURIComponent($(this.productNameFieldId).value) + '/', {
	    	    'onSuccess':this.successLoading.bind(this)
	            });
			
			if (objEvent.target == $(this.countryToFieldId))
			{
				new Ajax.Request(this.url + 'country_to_provinces/' + this.provinceToFieldId + '/' + $(this.countryToFieldId).value + '/', {
		    	    'onSuccess':this.provincesSuccessLoading.bind(this)
		            });
			}
		}
		
//		if( $(this.countryToFieldId).value == 0)
//		{
//			this.disabledInputs();
//		}
		this._showhideGetQuoteBtn();
		
	},
	
	_setManufactureCountry: function(evt)
	{
		if ($(this.countryManufactureFieldId) == null) {
			return;				
		}		
		if ($(this.countryManufactureFieldId).value) {
			return;
		}


		var selectedIndex = 0;
		var manufactureSelect = $(this.countryManufactureFieldId);		
		for (var i = 0; i<manufactureSelect.options.length;i++) {
			if ($(this.countryFromFieldId).value == manufactureSelect.options[i].value) {
				selectedIndex = i;
			}
		}
		
//		custom select case
//		getCustomSelectBySelectId(this.countryManufactureFieldId).selectOption(selectedIndex, true);

//		common select case		
		$(this.countryManufactureFieldId).selectedIndex = selectedIndex;
	},
	
	_checkShippingCostValue: function(evt)
	{
//		var cource_500_pounds = (aAllCurrencies[$('dtc_shipping_cost_currency').value])?aAllCurrencies[$('dtc_shipping_cost_currency').value]:0;
//		
//		if(this.sekoAdAllow && cource_500_pounds && parseFloat( $('dtc_shipping_cost').value)/cource_500_pounds  >= 500){
//			$('get_seko').show();
//		} else {
//			$('get_seko').hide();
//		}
		
	},
	
	_showhideGetQuoteBtn: function(evt)
	{
		if (!$('get_shipping_estimate_btn'))
		{
			return false;
		}
		
		if ($(this.countryFromFieldId).value !=0 && $(this.countryToFieldId).value !=0) {
//			$(this.productNameFieldId).style.color = '#000';
			$(this.productNameFieldId).removeClassName('txt-sm');
		}		
//		else {
//			if ($(this.productNameFieldId).value != exampleBrandName) {
//				$(this.productNameFieldId).style.color = '#a3a3a3';
//			}
//		}
		
		var country_from_val = $(this.countryFromFieldId).value;		
		
		if(country_from_val == objAllCountries.USA && BboxCountries[$(this.countryToFieldId).value]){
			if ($('get_shipping_estimate_btn'))
				$('get_shipping_estimate_btn').show();
		} else {
			if ($('get_shipping_estimate_btn'))
				$('get_shipping_estimate_btn').hide();
		}
		
		if( (country_from_val == objAllCountries.CHN || 
			 country_from_val == objAllCountries.HKG ||
			 country_from_val == objAllCountries.IND ||
			 country_from_val == objAllCountries.ARE ||
			 country_from_val == objAllCountries.THA
			 ) 
			&& $(this.countryToFieldId).value == objAllCountries.GBR ){
			this.sekoAdAllow = true;
			/*
			var cource_500_pounds = (aAllCurrencies[$('dtc_shipping_cost_currency').value])?aAllCurrencies[$('dtc_shipping_cost_currency').value]:0;
			if( cource_500_pounds && parseFloat( $('dtc_shipping_cost').value)/cource_500_pounds  < 500){
				$('get_seko').show();
			}
			*/
			this._checkShippingCostValue(null); 
		} else {
			//$('get_seko').hide();
			this.sekoAdAllow = false;
		}
		
	},
	
	_setDefaultCurrency: function(objEvent)
	{
		if($(this.countryFromFieldId).value && $(this.currencyField) )
		{
			$(this.currencyField).value = this.hCurrencies.get( $(this.countryFromFieldId).value  );
		}
	},
	
	provincesSuccessLoading: function(objResponce)
	{
		var responceText = objResponce.responseText;
		Element.replace( $(this.provinceToFieldId), responceText);
		if(this.ajaxLoadingEffect != null)
		{
			this.ajaxLoadingEffect.removeLoadingEffect();
		}		
	},
	
	successLoading: function(objResponce)
	{
		if (this.autosuggest)
		{
			this.autosuggest.allowCategoryPrediction = false;
		}
		var responceText = objResponce.responseText;
//		$(this.categoryFieldId + 'Container' in case of custom select
		Element.replace( $(this.categoryFieldId), responceText);		
		
//		for (var i = 0; i < $(this.categoryFieldId).options.length; i++)
//		{
//			if (!isNumber($(this.categoryFieldId).options[i].value))
//			{
//				$(this.categoryFieldId).options[i].disabled = true;
//			}
//		}		
		
		if (this.weightBlock && this.quantityBlock) {
			$(this.quantityBlock).hide();
			$(this.weightBlock).hide();
		}
		
		if (this.antidumpingListenerId)
		{
			$(this.antidumpingListenerId).value = 0;
		}
		if (this.countryManufactureBlock)
		{
			$(this.countryManufactureBlock).hide();
		}
		
		new DutyCalculationProductInterface({
			'acceptor': this.subCategoryFieldId,
			'listen': this.categoryFieldId,
			'url': this.url,
			'productNameField': this.productNameFieldId,
			'containerId':this.containerId,
			'itemsField': this.itemsFieldId,
			'countryField': this.countryToFieldId,
			'quantityUnitField': this.quantityUnitFieldId,
			'dutyRuleListener' : this.dutyRuleListenerId,
			'antidumpingListener' : this.antidumpingListenerId,
			'quantityFieldsContainer' : this.quantityBlock,
			'weightFieldsContainer' : this.weightBlock,
			'weightListener' : this.weightListenerId,
			'countryManufactureBlock' : this.countryManufactureBlock,
			'isWidget' : this.isWidget
		});

		//$('add_button_container').show();
		//$('separator' + this.blockId).show();		
		
		if(this.ajaxLoadingEffect != null)
		{
			this.ajaxLoadingEffect.removeLoadingEffect();
		}
	},
	
	showProductFields: function()
	{
		if ($(this.productNameFieldId))
		{
			if ($(this.productNameFieldId).value != '' && $(this.productNameFieldId).value != exampleBrandName && $(this.countryToFieldId).value)
			{		
				if ($(this.notCoveredFieldId).value == 1)
				{
					$('product_fields' + this.blockId).hide();
					$('product_value' + this.blockId).hide();
					$('not_covered' + this.blockId).show();
				}
				else
				{
					$('product_fields' + this.blockId).show();
					$('product_value' + this.blockId).show();
					$('not_covered' + this.blockId).hide();
					$(this.categoryFieldId).focus();
				}			
			}
		}
	},
	
	showImporterDetails: function()
	{
		if ($(this.companyListenerId).value == 1) {// || $(this.weightTaxListenerId).value != 0 || $(this.costTaxListenerId).value != 0) {
			if ($(this.companyListenerId).value != 0) {
				$("company_individual").show();
			}
			else {
				this.hideCompanyIndividual();
			}
		}
		else {
			this.hideCompanyIndividual();
			this.hideImportActivity();
		}
		
		if ($(this.weightTaxListenerId).value == 0) {			
			this.hideImportedWeight();
		}
		if ($(this.costTaxListenerId).value == 0) {
			this.hideImportedCost();
		}
	},
	
	showImportActivity: function() {
		if ($(this.companyFieldId).value == 0 && $(this.companyFieldId).value != '') {
			$("import_activity").show();
		}
		else {
			this.hideImportActivity();
			this.hideImportedCost();
			this.hideImportedWeight();
		}
	},
	
	showImportActivityFields: function() {
		if ($(this.importActivityFieldId).value == 1) {
			if ($(this.weightTaxListenerId).value != 0) {
				$("imported_weight").show();
//				Element.down($("imported_cost"), 'label').innerHTML = '&nbsp;';
			}
			else {
				this.hideImportedWeight();
			}
			if ($(this.costTaxListenerId).value != 0) {
				$("imported_cost").show();
			}
			else {
				this.hideImportedCost();
			}		
		}
		else {
			this.hideImportedCost();
			this.hideImportedWeight();
		}
	},
	
	hideCompanyIndividual: function() {
		$("company_individual").hide();
		Element.down($("company_individual"), 'select').selectedIndex = 0;
	},
	
	hideImportActivity: function() {
		$("import_activity").hide();
		Element.down($("import_activity"), 'select').selectedIndex = 0;
	},
	
	hideImportedWeight: function() {
		$("imported_weight").hide();
		Element.down($("imported_weight"), 'select').selectedIndex = 0;
		Element.down($("imported_weight"), 'input').value = exampleImportedWeight;
		Element.down($("imported_weight"), 'input').addClassName('txt-sm');
	},
	
	hideImportedCost: function() {

		$("imported_cost").hide();
		Element.down($("imported_cost"), 'select').selectedIndex = 0;
		Element.down($("imported_cost"), 'input').value = exampleImportedCost;
		Element.down($("imported_cost"), 'input').addClassName('txt-sm');
	},
	
	disabledInputs: function()

	{
//		for custom selects
//		getCustomSelectBySelectId(this.categoryFieldId).disable();
//		getCustomSelectBySelectId(this.subCategoryFieldId).disable();
//		getCustomSelectBySelectId(this.itemsFieldId).disable();
		
//		for common selects
		if ($(this.countryToFieldId).value == 0 /*|| !$(this.countryToFieldId).value == 0*/) {
			$(this.categoryFieldId).disabled = true;
			$(this.categoryFieldId).selectedIndex = 0;
		}
		$(this.subCategoryFieldId).disabled = true;
		$(this.subCategoryFieldId).selectedIndex = 0;
		$(this.itemsFieldId).disabled = true;
		$(this.itemsFieldId).selectedIndex = 0;
	},

	checkCifForShipmentWeight: function()
	{
		if (sendingShipmentWeightRequest)
		{
			return;
		}
		
		sendingShipmentWeightRequest = true;
		
//		var shippingCost = $('dtc_shipping_cost').value;
//		var shippingCurrency = $('dtc_shipping_cost_currency').value;
//		
//		var shippingCost = $('dtc_shipping_cost').value;
//		var shippingCurrency = $('dtc_shipping_cost_currency').value;
//		
//		var productKeys = $('product_keys').value.split(',');
//		
//		var productValue = new Array();
//		var productValueCurrency = new Array();
//		
//		for (var i = 0; i < productKeys; i++)
//		{
//			productValue[] = $('dtc_product_value').value;
//			productValueCurrency[] = $('dtc_value_currency').value;
//		}

		var postBody;
		if ($('calculation_form'))
		{
			postBody = $('calculation_form').serialize();
		}	
		if ($('ebay_calculator_clarification_form'))
		{
			postBody = $('ebay_calculator_clarification_form').serialize(); 
		}
		
		if (postBody)
		{
			new Ajax.Request(this.url + 'shipment_weight/', {
				'method': 'POST',
				'postBody': postBody,
			    'onSuccess':this.shipmentWeightSuccessLoading.bind(this)
	        });
		}
	},
	
	shipmentWeightSuccessLoading: function(objResponce)
	{
		var responceText = objResponce.responseText;
		eval(responceText);
		sendingShipmentWeightRequest = false;
	}	

});



var DutyAddProduct = Class.create();

DutyAddProduct.prototype = ({

	initialize: function (config)
	{		
		this.url				 = config.url;
		this.maxProduct			 = config.maxProducts;
		this.containerId		 = config.containerId;
		this.productNameFieldId  = config.productNameId;
		this.categoryFieldId	 = config.categoryField;	
		this.subCategoryFieldId	 = config.subCategoryField;
		this.itemsFieldId		 = config.itemsField;
		this.countryManufactureFieldId = config.countryManufactureField;
		this.countryFieldId		 = config.countryFieldId;
		this.countryFromField	 = config.importFromFieldId;
		this.currencyFieldId	 = config.currencyFieldId;
		this.lastBlockId		 = config.lastBlockId;
		this.addButtonId		 = config.addButtonId;
		//this.replacedIdHash		 = config.replacedHash;
		this.etalonBlock		 = config.etalonBlockId;
		
		this.productNamesHash	 = new Hash();
		this.lastIndex			 = (config.lastIndex)?config.lastIndex:1;
		this.lastBlockId		 = this.etalonBlock;
		this.beforeBlock		 = config.before_block;
		this.hCurrency			 = config.currenciesList;
		
		this.companyListenerId 			= config.companyListener;
		this.companyFieldId 			= config.companyField;
		this.importActivityFieldId 		= config.importActivityField;
		
		this.weightBlockId 				= config.weightBlock;
		this.weightTaxListenerId 		= config.weightTaxListener;
		this.costTaxListenerId 			= config.costTaxListener;
		
		this.weightListenerId			= config.weightListener;
		
		this.dutyRuleListenerId			= config.dutyRuleListener;
		this.antidumpingListenerId		= config.antidumpingListener;
		this.quantityBlock			 	= (config.quantityFieldsContainer)? config.quantityFieldsContainer : false;
		this.quantityUnitFieldId 		= (config.quantityUnitField)? config.quantityUnitField : false;					
		
		this.countryManufactureBlock	= config.countryManufactureBlock;
		
		this.autoSuggestUrl				= config.autoSuggestUrl;
		
		this.notCoveredField			= config.notCoveredField;
		
		this.productValueField			= config.productValueField;
		this.productValueCurrencyField	= config.productValueCurrencyField;
				
		Event.observe(document, 'dom:loaded', this.setCathers.bindAsEventListener(this) );
	},

	setCathers: function()
	{
		$(this.addButtonId).onclick = function()
		{
			return false; //IE fix
		}
		Event.observe($(this.addButtonId), 'click', this.createNewProductForm.bind(this) );
		
		var closedLinks = $$('a[rel="delete_product"]');
		for( var i=0;i<closedLinks.length;i++)
		{
			closedLinks[i].onclick = function()
			{
				return false; //IE fix
			}
			Event.observe( closedLinks[i], 'click', this.deleteProduct.bindAsEventListener(this) );
		}		
	},
	
	createNewProductForm: function()
	{
		var objEtalon  = $(this.etalonBlock);
		var objDivContainer = document.createElement('div');
		objDivContainer.className = objEtalon.className;
	
		var innerEtalon = objEtalon.innerHTML;
		Insertion.Before( $(this.beforeBlock),objDivContainer );
		objDivContainer.style.display = "none";

		Element.update(objDivContainer, innerEtalon);

		var objInputs = objDivContainer.getElementsByTagName('input');

		this.lastIndex++;		
		
		var objProductFields = Element.down(objDivContainer, 'span.product_fields');
		objProductFields.style.display = 'block';
		objProductFields.id = objProductFields.id + this.lastIndex;

		var objNotCoveredMessage = Element.down(objDivContainer, 'div.not_covered');
		objNotCoveredMessage.style.display = 'none';		
		objNotCoveredMessage.id = objNotCoveredMessage.id + this.lastIndex;		

		var objValueFields = Element.down(objDivContainer, 'span.product_value');
		objValueFields.id = objValueFields.id + this.lastIndex;			
		
		for(var i=0; i< objInputs.length; i++)
		{
			objInputs[i].id = objInputs[i].name = objInputs[i].id + this.lastIndex;
		}
		
		var objSelects = objDivContainer.getElementsByTagName('select');
		for( i=0;i< objSelects.length; i++)
		{
			if( objSelects[i].id == this.subCategoryFieldId ||  objSelects[i].id == this.itemsFieldId )
			{
				objSelects[i].disabled = "disabled";
			}

			objSelects[i].id = objSelects[i].name = objSelects[i].id + this.lastIndex;
			
//			common select case
			$(objSelects[i].id).selectedIndex = 0;
			
		}	

		var selectedIndex = 0;
//uncomment if you want to set country import from as a country of manufacture for the newly added product automatically
//		var manufactureSelect = $(this.countryManufactureFieldId + this.lastIndex);
//		for (i = 0; i<manufactureSelect.options.length;i++) {
//			if ($('dtc_country_from').value == manufactureSelect.options[i].value) {
//				selectedIndex = i;
//			}
//		}
		
//		common select case
		$(this.countryManufactureFieldId + this.lastIndex).selectedIndex = selectedIndex;

		Element.down($(objDivContainer), 'span[id="' + this.weightBlockId + '"]').id = this.weightBlockId + this.lastIndex;
		Element.down($(objDivContainer), 'span[id="' + this.quantityBlock + '"]').id = this.quantityBlock + this.lastIndex;
		Element.down($(objDivContainer), 'span[id="' + this.countryManufactureBlock + '"]').id = this.countryManufactureBlock + this.lastIndex;
		
		$(this.quantityBlock + this.lastIndex).hide();
		$(this.weightBlockId  + this.lastIndex).hide();
		$(this.countryManufactureBlock + this.lastIndex).hide();
		
		new DutyCalculationCountriesInterface({
			'blockId': this.lastIndex,
			'import_to_field': this.countryFieldId,
			'import_from_field': this.countryFromField,
			'url': this.url,
			'containerId': this.containerId + this.lastIndex,
			'productNameField': this.productNameFieldId + this.lastIndex, 
			'categoryField': this.categoryFieldId + this.lastIndex,
			'subCategoryField': this.subCategoryFieldId + this.lastIndex,
			'itemsField'	: this.itemsFieldId + this.lastIndex,
			'countryManufactureField'	: this.countryManufactureFieldId + this.lastIndex,
			'currencyField' : this.currencyFieldId + this.lastIndex,
			'countryCurrencies': this.hCurrency,						
			'already_loaded': true,
			'dutyRuleListener': this.dutyRuleListenerId + this.lastIndex,
			'antidumpingListener': this.antidumpingListenerId + this.lastIndex,
			'quantityFieldsContainer' : this.quantityBlock + this.lastIndex,
			'quantityUnitField': this.quantityUnitFieldId + this.lastIndex, 
			'companyListener': this.companyListenerId,
			'companyField': this.companyFieldId,
			'importActivityField': this.importActivityFieldId,
			'weightTaxListener': this.weightTaxListenerId,
			'weightBlock': this.weightBlockId + this.lastIndex,
			'costTaxListener': this.costTaxListenerId,
			'weightListener': this.weightListenerId + this.lastIndex,
			'countryManufactureBlock' : this.countryManufactureBlock + this.lastIndex,
			'autosuggest': true,
			'autoSuggestUrl': this.autoSuggestUrl,
			'notCoveredField': this.notCoveredField + this.lastIndex,
			'productValueField': this.productValueField,
			'productValueCurrencyField': this.productValueCurrencyField
		});
		
//		common select case
		$(this.currencyFieldId + this.lastIndex).value = this.hCurrency.get( $(this.countryFromField).value ) ? this.hCurrency.get( $(this.countryFromField).value ) : defaultCurrencyId; 
		
		$('dtc_product_name' + this.lastIndex).value = exampleBrandName;
		$('dtc_product_value' + this.lastIndex).value = exampleProductValue;
		$('dtc_product_value' + this.lastIndex).addClassName('txt-sm');
		
		if( $(this.countryFieldId).value )
		{
			new DutyCalculationProductInterface({
				'acceptor': this.subCategoryFieldId + this.lastIndex,
				'listen': this.categoryFieldId + this.lastIndex,
				'url': this.url,
				'productNameField': this.productNameFieldId + this.lastIndex,
				'containerId':this.containerId + this.lastIndex,
				'itemsField': this.itemsFieldId + this.lastIndex,
				'quantityFieldsContainer' : this.quantityBlock + this.lastIndex,
				'quantityUnitField' : this.quantityUnitFieldId + this.lastIndex,				
				'dutyRuleListener': this.dutyRuleListenerId + this.lastIndex,
				'antidumpingListener': this.antidumpingListenerId + this.lastIndex,
				'weightListener' : this.weightListenerId + this.lastIndex,
				'weightFieldsContainer' : this.weightBlockId + this.lastIndex,
				'countryManufactureBlock' : this.countryManufactureBlock + this.lastIndex
			});
		}	
		
		var objLabels = objDivContainer.getElementsByTagName('label');
		for(i=0; i< objLabels.length; i++ )
		{
			var label_for = objLabels[i].getAttribute('for');
			if( label_for != null && typeof(label_for)!= 'undefined' )
			{
				objLabels[i].setAttribute('for',label_for + this.lastIndex);
			}  
		}
		
		objDivContainer.id =this.etalonBlock + this.lastIndex;
		
		this.productNamesHash.set(this.lastIndex, this.etalonBlock + this.lastIndex );
		
		objDivContainer.style.display = "";
		
//		$(this.etalonBlock).getElementsByClassName('HeadLine')[0].style.display ='';
//		$(this.etalonBlock + this.lastIndex).getElementsByClassName('HeadLine')[0].style.display = '';
//		$('topSeparLine').hide();
		this.setKeysToInput(this.getAllProductObjectsId());
		
		if(this.getAllProductObjectsId().length == (this.maxProduct-1) )
		{
			$(this.addButtonId).hide();
		}

		//var objNewTooltips = $(objDivContainer.id).getElementsBySelector('span[class="IcoForm InfIco"]');
		
		
		var objNewTooltips = objDivContainer.getElementsByTagName('span');
		for(var iTooltipsIndex = 0; iTooltipsIndex < objNewTooltips.length; iTooltipsIndex++ )
		{
			if( objNewTooltips[iTooltipsIndex].className == 'ico-help')
			{
				objTooltips.setCatcher(objNewTooltips[iTooltipsIndex]);
			}
		}

		//var closeLink  = Element.down($(objDivContainer.id),'img[alt="Close"]');
		var closeLink  = Element.down($(objDivContainer.id),'div.sideOpt');
		closeLink.show();
		
		if( closeLink )
		{
			closeLink.onclick = function()
			{
				return false; //IE fix
			}
			Event.observe( closeLink, 'click', this.deleteProduct.bindAsEventListener(this) );
		}		
		if (!Prototype.Browser.IE)
		{
			var objSendFeedback = objDivContainer.down('a[rel="showWindow"]');
			new WindowModal(objSendFeedback);			
		}
		else
		{		
			var objSendLinks = objDivContainer.getElementsByTagName('a');
			for(var iSendLinks =0; iSendLinks < objSendLinks.length; iSendLinks ++)
			{
				if( objSendLinks[iSendLinks].rel == "showWindow")
				{
					new WindowModal( objSendLinks[iSendLinks] );
				}
			}
		}
		
//		if (objTooltips)
//		{
//			objTooltips.onReady();
//		}
		
		if ($('allow_companies').value)
		{
			fireEvent($(this.importActivityFieldId), 'change');
		}
		
		//this._createBBoxFields();
		
//		this._setProductEnumeration();
		//Event.observe( $('dtc_product_value'+ this.lastIndex), 'change', this._setBBoxValueChangeCatcher.bindAsEventListener(this,'dtc_product_value'+ this.lastIndex,'package_1_item_price_'+this.lastIndex) );
		//Event.observe( $('dtc_value_currency'+ this.lastIndex), 'change', this._setBBoxValueChangeCatcher.bindAsEventListener(this,'dtc_value_currency'+ this.lastIndex,'package_1_item_currency_'+this.lastIndex) );
	},
	
	_setBBoxValueChangeCatcher:function(objEvent, fieldSender, fieldAcceptor)
	{
		//_bboxValueCatcher(fieldSender, fieldAcceptor);
		//$(fieldAcceptor).value = $(fieldSender).value;
		return true;
	},
	
	deleteProduct: function( objDeleteClick )
	{		
		var objContainerLink = Event.findElement(objDeleteClick,'a');
		if (objContainerLink) {
			var objContainer = objContainerLink.up(1)
			var id_element = objContainer.id;
			Element.remove(objContainer);

			if (objTooltips)
				objTooltips.stopWatching(objContainerLink);
			
			if( id_element != this.etalonBlock )
			{
				var HashKey = id_element.sub(this.etalonBlock,'',1); 
			}

			this.productNamesHash.unset(HashKey);
			
			this.setKeysToInput( this.getAllProductObjectsId() );
					
			if(this.getAllProductObjectsId().length < (this.maxProduct-1) )
			{
				$(this.addButtonId).show();
			}
			
			if(this.getAllProductObjectsId().length == 0)
			{
//				$(this.etalonBlock).down('div[class="HeadLine"]').hide();
//				$('topSeparLine').show();
			}
			/*
			var bb_idContainer =  id_element.replace(new RegExp('product_block'),'');
			
			if(bb_idContainer && $('bbox_fields_'+bb_idContainer)){
				Element.remove( $('bbox_fields_'+bb_idContainer) );
			}
			*/ 
			
						
			this._setProductEnumeration();
			
			if ($('allow_companies').value)
			{
				fireEvent($(this.importActivityFieldId), 'change');
			}
		}
	},
	
	/**
	 * @return array
	 */
	getAllProductObjectsId: function()
	{
		return this.productNamesHash.keys();
	},
	
	setKeysToInput: function(aKeys)
	{
		var sKeys = '';
		for(i=0;i<aKeys.length;i++)
		{
			if(sKeys!='')
			{
				sKeys +=',';
			}
			sKeys += aKeys[i];
		}
		$('product_keys').value = sKeys;
		
	},
	
	_setProductEnumeration: function()
	{
		if(Prototype.Browser.IE)
		{
			this._setProductEnumerationIE();
			return;
		}
		var objSpansNums = $$('span[class="productNumber"]');
		this._setNums( objSpansNums );
	},
	
	_setProductEnumerationIE: function()
	{
		var objSpans = document.getElementsByTagName('span');
		var objProdNumsSpan = new Array();
		for(var i=0; i< objSpans.length; i++)
		{
			if(objSpans[i].className =='productNumber' )
			{
				objProdNumsSpan[objProdNumsSpan.length] = objSpans[i];
			}
		}
		this._setNums(objProdNumsSpan);
		
	},
	
	_setNums: function( objSpansNums )
	{
		for(var i=0; i< objSpansNums.length; i++)
		{
			objSpansNums[i].innerHTML = i+1;
		}
	},
	
	_createBBoxFields:function()
	{
		return;
		var bb_formName = 'bbox_estimate';
		bb_form = $(bb_formName);
		var bb_etalon = $('bbox_form_etalon').innerHTML;
		
		
		var bb_objDivContainer = document.createElement('p');
		bb_objDivContainer.innerHTML = bb_etalon;
		bb_objDivContainer.className = 'bbox_cnt';
		bb_objDivContainer.id = 'bbox_fields_' +this.lastIndex; 

		var AllPEls = $(bb_formName).select('p.bbox_cnt');		
		Insertion.After(AllPEls[AllPEls.length-1] ,bb_objDivContainer );
				
		var objInputs = bb_objDivContainer.getElementsByTagName('input');
		for(var i=0; i< objInputs.length; i++)
		{
			current_id = objInputs[i].id + '_' + this.lastIndex
			$(objInputs[i]).setAttribute('name',current_id);
			$(objInputs[i]).setAttribute('id',current_id);
		}
	}
	
	
});


var SelectBoxEnabling = Class.create();

SelectBoxEnabling.prototype = ({

	initialize: function (config)
	{
		this.formName	= config.formName;
		Event.observe(document, 'dom:loaded', this.enableSelects.bindAsEventListener(this) );
	},
	
	enableSelects: function()
	{
		var aSelectBoxes = $(this.formName).getElementsByTagName('select');
		for(var i=0;i<aSelectBoxes.length;i++)
		{
			if(aSelectBoxes[i].options.length >1)
			{
//				custom select case
//				getCustomSelectBySelectId(aSelectBoxes[i].id).enable();
				
//				common select case
				aSelectBoxes[i].disabled = false;
			}
		}
	}
	
});

/*
function _bboxValueCatcher(sender, acceptor)
{
	$(acceptor).value = $(sender).value;
	return true;	
}

function StartBboxFields(dcField, bboxField)
{
	$(bboxField).value = $(dcField).value;
	//Event.observe( $(dcField), 'change', function(){_bboxValueCatcher(dcField,bboxField)} );	
}
*/ 


function showBBoxPopup()
{
	var allBboxCnts = $('bbox_estimate').getElementsBySelector('p[class="bbox_cnt"]');
	$('hiddens_container').innerHTML = '';
	$('hiddens_container').style.fontSize = '1.2em';
	var allProductBoxes = new Array();
	var aCantFindImages = $$('div.GreyBox');
	for(i=0;i <aCantFindImages.length;i++){
		if( aCantFindImages[i].id.match(new RegExp('product_block'),'') ){
			allProductBoxes[allProductBoxes.length] = aCantFindImages[i];
		}
	}
	var isError = false;
	var productParams = '';
	var productErrors = '';
	for(var ItemsCount=0; ItemsCount < allProductBoxes.length; ItemsCount++)
	{
		var itemsContainer = allProductBoxes[ItemsCount];

		var itemBlockId = itemsContainer.id.replace(new RegExp('product_block'),'');
		//alert(itemBlockId);
		var bboxCntNum = (itemBlockId!='')?itemBlockId:'1';
		var categoryField  	= 'dtc_product_category'+itemBlockId;
		var subField		= 'dtc_product_category_sub'+itemBlockId;
		var itemField 		= 'dtc_product_item'+itemBlockId;
		var valueField		= 'dtc_product_value'+itemBlockId;
		var currencyField	= 'dtc_value_currency'+itemBlockId;
		var ErrorArray = _checkforErrors(categoryField,subField,itemField,valueField,currencyField);

		if( !ErrorArray.length && !isError)
		{
			_appendHiddenFields(categoryField,subField,itemField,valueField,currencyField, bboxCntNum);
			if(allProductBoxes.length > 1){
				productParams += '<i>Item No. ' + parseInt(ItemsCount+1) + '</i><br />';
			}
			productParams += '<span class="bbox_info"><strong>Product Name</strong>: ' +  $(categoryField).options[$(categoryField).selectedIndex].text;
			productParams += '<br /><strong>Product subcategory</strong>: ' +  $(subField).options[$(subField).selectedIndex].text;
			productParams += '<br /><strong>Product</strong>: ' +  $(itemField).options[$(itemField).selectedIndex].text;
			productParams += '<br /><strong>Product value</strong>: ' +  $(valueField).value +' ' + $(currencyField).options[$(currencyField).selectedIndex].text;
			productParams += '<br /></span>';
		}
		else
		{
			if( !isError){
				isError = true;
			}
			if( ErrorArray.length )
			{
				var additionalMessage = '';
				if( allProductBoxes.length > 1){
					additionalMessage = ' for Item No. ' + parseInt(ItemsCount+1);
				}
				for(var errCount=0; errCount < ErrorArray.length; errCount++)
				{
					var currentError = ErrorArray[errCount];
					productErrors += '<span class="ErrorTextPopup">' + currentError + additionalMessage + '</span><br />';
				}
				productErrors += '<br />';
			} //end if( ErrorArray.length )
		}
		
	}
	if( isError){
		productParams = productErrors;
	}
	Insertion.Bottom($('hiddens_container'), productParams);
	
	_createPopupLayer('bboxPopup', isError);
	
}

function _checkforErrors(categoryField,subField,itemField,valueField,currencyField)
{
	var aErrors = new Array();
	if( !$(categoryField).value){
		aErrors[aErrors.length] = 'Please select Product Category'; 
	}
	if( !$(subField).value ){
		aErrors[aErrors.length] = 'Please select Product subcategory';
	}
	if( !$(itemField).value ){
		aErrors[aErrors.length] = 'Please select product';
	}

	val= parseFloat($(valueField).value);
	if(isNaN(val))
	{ 
		aErrors[aErrors.length] = 'Please provide Product Value';
	}	

	if( !$(currencyField).value ){
		aErrors[aErrors.length] = 'Please select currency of the product value';
	}
	return aErrors;
}

function _appendHiddenFields(categoryField,subField,itemField,valueField,currencyField, bboxCntNum)
{
		Element.append('hiddens_container', 'input', {type:'hidden', 
														 name: 'package_1_item_category_'+bboxCntNum,
														 id: 'package_1_item_category_'+bboxCntNum,
														 value: $(categoryField).value}, '');

		Element.append($('hiddens_container'), 'input', {'type':'hidden', 
														 name: 'package_1_item_subcategory_'+bboxCntNum,
														 'id': 'package_1_item_subcategory_'+bboxCntNum,
														 'value': $(subField).value}, '');

		Element.append($('hiddens_container'), 'input', {type:'hidden', 
														 name: 'package_1_item_product_'+bboxCntNum,
														 id: 'package_1_item_product_'+bboxCntNum,
														 value: $(itemField).value}, '');

		Element.append($('hiddens_container'), 'input', {type:'hidden', 
														 name: 'package_1_item_price_'+bboxCntNum,
														 id: 'package_1_item_price_'+bboxCntNum,
														 value: $(valueField).value}, '');

		Element.append($('hiddens_container'), 'input', {type:'hidden', 
														 name: 'package_1_item_currency_'+bboxCntNum,
														 id: 'package_1_item_currency_'+bboxCntNum,
													 	 value: $(currencyField).value}, '');

}

function _createPopupLayer( innerContentBlockId, isError )
{
	var overlayDiv = $('overlay');
	if( !overlayDiv){
		overlayDiv = document.createElement('div');
		overlayDiv.id="overlay";
		document.getElementsByTagName('body')[0].appendChild(overlayDiv);
	}
	
	overlayDiv.style.display = "block";
	
	var windowDiv = $('window');
	if( !windowDiv ){
		windowDiv = document.createElement('div');
		windowDiv.id="window";
		document.getElementsByTagName('body')[0].appendChild(windowDiv);
	}
	windowDiv.style.display = "block";
	windowDiv.className = "done";
	

	var lbContentDiv = document.createElement('div');
	lbContentDiv.id="lbContent";
	windowDiv.appendChild(lbContentDiv);

	var W = Utils.getViewportWidth();
	var H = Utils.getViewportHeight();

    var w_center = parseInt(W/2);
    var h_center = parseInt(H/2);


	var winFormDiv = document.createElement('div');
	winFormDiv.id="win-form";
	winFormDiv.style.visibility = "visible";
	winFormDiv.style.left = (w_center -170)+'px';
	winFormDiv.style.top = (100) + 'px';
	
	lbContentDiv.appendChild(winFormDiv);


	var innerDiv = document.createElement('div');
	innerDiv.className="inner";
	///innerDiv.
	winFormDiv.appendChild(innerDiv);
	
	if( $('popup-invalid-inputs') && $('bbox-add-inputs'))
	{
		if( isError ){
			$('popup-invalid-inputs').show();
			$('bbox-add-inputs').hide();
		} else {
			$('popup-valid-inputs').show();
			$('bbox-add-inputs').show();
		}
	}
	//alert($(innerContentBlockId).id );
	if( Prototype.Browser.IE){
		innerDiv.innerHTML = $(innerContentBlockId).innerHTML;
	} else {	
		innerDiv.appendChild( $(innerContentBlockId).down(0) );
	}
	
}

function getUrlParamsForSekoSynergy()
{
	var product_count = 0;
	var string_params = '?';
	var allProductBoxes = new Array();
	var aCantFindImages = $$('div.GreyBox');	
	
	for(i=0;i <aCantFindImages.length;i++){
		if( aCantFindImages[i].id.match(new RegExp('product_block'),'') ){
			allProductBoxes[allProductBoxes.length] = aCantFindImages[i];
		}
	}

	for(var ItemsCount=0; ItemsCount < allProductBoxes.length; ItemsCount++)
	{
		var itemsContainer = allProductBoxes[ItemsCount];

		var itemBlockId = itemsContainer.id.replace(new RegExp('product_block'),'');
		//alert(itemBlockId);
		var bboxCntNum = (itemBlockId!='')?itemBlockId:'1';
		var categoryField  	= 'dtc_product_category'+itemBlockId;
		var subField		= 'dtc_product_category_sub'+itemBlockId;
		var itemField 		= 'dtc_product_item'+itemBlockId;
		var valueField		= 'dtc_product_value'+itemBlockId;
		var currencyField	= 'dtc_value_currency'+itemBlockId;
		
		string_params += 'category'+ItemsCount +'='+$(categoryField).value+'&';
		string_params += 'sub'+ItemsCount+'='+$(subField).value+'&';
		string_params += 'item'+ItemsCount+'='+$(itemField).value+'&';
		string_params += 'value'+ItemsCount+'='+$(valueField).value+'&';
		string_params += 'currency'+ItemsCount+'='+$(currencyField).value+'&';
		if( $('dtc_product_name'+itemBlockId).value == exampleBrandName){
			product_descr = '';
		} else {
			product_descr = $('dtc_product_name'+itemBlockId).value;
		}
		string_params += 'description'+ItemsCount+'='+product_descr+'&';
	}
	string_params+= 'prod_count='+allProductBoxes.length;
	string_params+= '&from='+$('dtc_country_from').value;
	string_params+= '&to='+$('dtc_country_to').value;
	string_params+= '&shipping_cost='+$('dtc_shipping_cost').value;
	string_params+= '&shipping_currency='+$('dtc_shipping_cost_currency').value;
	return string_params;
	
}

function _destroyPopupLayer( layerName )
{
	$(layerName).innerHTML = $('win-form').down('div.inner').innerHTML;
	//console.log( $(layerName).innerHTML );
	//$(layerName).appendChild( $('win-form').down('div.inner').down(0));
	
	/*
	Element.remove('overlay');
	Element.remove('window');
<div id="overlay"/>
<div id="window" class="loading"/>	 
	*/
	
	$('overlay').style.display ="";
	
	Element.remove( $('window').down(0) );
	$('window').className = "loading";
	$('window').style.display = "";
	if( $('popup-invalid-inputs') && $('bbox-add-inputs'))
	{
		$('popup-invalid-inputs').hide();
		$('popup-valid-inputs').hide();
	}		

	//Element.clearChildren( $('window') );
}
