var DutyCalculationProductInterface = Class.create();

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.url_param		= (config.url_param)?config.url_param:'subcategory';
		this.is_sub			= (config.issub)? config.issub : false;
		this.ajaxLoadingEffect = null;
		trigger				 = (config.start_on_load)?config.start_on_load: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));
		//Event.observe($(this.listenerId), 'change', this.onChangeSelect.bind());
		
	},
	
	onChangeSelect: function(objEvent)
	{
		//alert(this.listenerId + ' value = ' + $(this.listenerId).value );
		if( $(this.listenerId).value ==0)
		{
			$(this.acceptorId).value = '';
			fireEvent( $(this.acceptorId), 'change' );
			$(this.acceptorId).disabled="disabled";
			
		}
	else
		{
			if(this.ajaxLoadingEffect == null)
			{
				this.ajaxLoadingEffect = new AjaxLoadingEffect({'containerId':this.containerId});
			}
			this.ajaxLoadingEffect.setLoadingEffect();
			if ($('country_to'))
			{
				var countryTo = $('country_to').value
				new Ajax.Request(this.url + this.url_param + '/' + this.acceptorId + '/' + $(this.listenerId).value + '/' + countryTo + '/', 
					{
		    	    	'onSuccess':this.successLoading.bind(this)
		            });
			}
			else if ($('delivery_address'))
			{
				var deliveryAddress = $('delivery_address').value
				new Ajax.Request(this.url + this.url_param + '/' + this.acceptorId + '/' + $(this.listenerId).value + '/' + deliveryAddress + '/', 
					{
		    	    	'onSuccess':this.successLoading.bind(this)
		            });
			}
			else
			{
				new Ajax.Request(this.url + this.url_param + '/' + this.acceptorId + '/' + $(this.listenerId).value + '/',
					{
			    	   	'onSuccess':this.successLoading.bind(this)
			        });
			}
		}	
	},
	
	successLoading: function(objResponce)
	{
		responceText = objResponce.responseText.strip();
		Element.replace( $(this.acceptorId), responceText );
		
		if(!this.is_sub)
		{
			new DutyCalculationProductInterface({
				'acceptor': this.itemsFieldId,
				'listen': this.acceptorId,
				'url': this.url,
				'containerId':this.containerId,
				'issub': true,
				'url_param' : 'items'});
			$(this.itemsFieldId).value = '';
			$(this.itemsFieldId).disabled="disabled";	
		}
				
		if(this.ajaxLoadingEffect != null){
			this.ajaxLoadingEffect.removeLoadingEffect();
		}		
	}

	
});


/**

*/
var DutyCalculationCountriesInterface = Class.create();

DutyCalculationCountriesInterface.prototype = ({

	initialize: function (config)
	{
		this.countryToFieldId	 = config.import_to_field;
		
		this.url				 = config.url;
		this.itemsTableContainer = (config.itemsTableContainer) ? config.itemsTableContainer : false;
		this.ajaxLoadingEffect	 = null;
		this.containerId		 = config.containerId;
		this.categoryFieldId	 = config.categoryField;	
		this.subCategoryFieldId	 = config.subCategoryField;
		this.itemsFieldId		 = config.itemsField;
		this.deliveryTypeSelectId= config.deliveryTypeSelectId;
		
		this.additionalCostsContainerId 		= config.additionalCostsContainerId;
		this.taxesChargerLocallyNoteContainerId = config.taxesChargerLocallyNoteContainerId;
		this.infoAboutPackageNoteContainerId 	= config.infoAboutPackageNoteContainerId;
		
		var trigger				 = (config.already_loaded)? config.already_loaded : false;
		var expressDeliveryTypeSelectValue = 3;
		
		this.TAXES_CHARGED_NORMALLY_MODE 	= 1;
		this.TAXES_CHARGED_LOCALLY_MODE 	= 2;
		
		if(!trigger)
		{
			Event.observe(document, 'dom:loaded', this.setCatchers.bind(this) );
		}
		else
		{	
			this.setCatchers();
		}
	},

	setCatchers: function()
	{
		if( $(this.countryToFieldId).value == 0 ){
			$(this.categoryFieldId).disabled = "disabled";
			this.disabledInputs();
		}
		this.bfx =this.onChangeSelect.bind(this);
		Event.observe( $(this.countryToFieldId), 'change', this.bfx );
	},
	
	onChangeSelect: function(objEvent)
	{
		var countryId = $(this.countryToFieldId).value;
		
		if( countryId == 0)
		{		
 			$(this.categoryFieldId).disabled = "disabled";
			this.disabledInputs();
		}
		
		else
		{
			if ($(this.categoryFieldId) == null)
			{
				Event.stopObserving( $(this.countryToFieldId), 'change', this.bfx);
				return;
			}
			if(this.ajaxLoadingEffect == null)
			{
				this.ajaxLoadingEffect = new AjaxLoadingEffect({'containerId':this.containerId});
			}
			
			if(counrtiesProperties[countryId] != null) {
				
				if(counrtiesProperties[countryId]) {
					// if current country is with taxes charged locally
					this.setPageViewMode(this.TAXES_CHARGED_LOCALLY_MODE);
					areTaxesChargedLocally = true;
					return;
				}
				else {
					this.setPageViewMode(this.TAXES_CHARGED_NORMALLY_MODE);
					areTaxesChargedLocally = false;
				}
			}
				
			this.disabledInputs();
			
			this.ajaxLoadingEffect.setLoadingEffect();			
			new Ajax.Request(this.url + 'country_to/' + this.categoryFieldId + '/' + $(this.countryToFieldId).value +'/', {
	    	    'onSuccess':this.successLoading.bind(this)
	            });
		}
	},
	
	successLoading: function(objResponce)
	{
		$(this.categoryFieldId).disabled = "";
		
		var responceText = objResponce.responseText.strip();
		Element.replace( $(this.categoryFieldId), responceText );
		
		new DutyCalculationProductInterface({
			'acceptor': this.subCategoryFieldId,
			'listen': this.categoryFieldId,
			'url': this.url,
			'containerId':this.containerId,
			'itemsField': this.itemsFieldId});
		
		if(this.ajaxLoadingEffect != null)
		{
			this.ajaxLoadingEffect.removeLoadingEffect();
		}
	},
	
	disabledInputs: function()
	{
		$(this.subCategoryFieldId).disabled = "disabled";
		$(this.itemsFieldId).disabled = "disabled";

		$(this.categoryFieldId).value = '';
		$(this.subCategoryFieldId).value= '';
		$(this.itemsFieldId).value = '';
	},
	
	setPageViewMode: function(mode)
	{
		if(mode === this.TAXES_CHARGED_NORMALLY_MODE){
			$(this.itemsTableContainer).show();
			$(this.additionalCostsContainerId).show();
			$(this.taxesChargerLocallyNoteContainerId).hide();
			$(this.infoAboutPackageNoteContainerId).show();
			
		}
		else if(mode == this.TAXES_CHARGED_LOCALLY_MODE) {
			$(this.itemsTableContainer).hide();
			$(this.additionalCostsContainerId).hide();
			$(this.taxesChargerLocallyNoteContainerId).show();
			$(this.infoAboutPackageNoteContainerId).hide();
		}
	}
});



var DutyAddProduct = Class.create();

DutyAddProduct.prototype = ({

	initialize: function (config)
	{
		this.url				 = config.url;
		this.maxProduct			 = config.maxProducts;
		this.containerId		 = config.containerId;
		this.categoryFieldId	 = config.categoryField;	
		this.subCategoryFieldId	 = config.subCategoryField;
		this.itemsFieldId		 = config.itemsField;
		this.countryFieldId		 = config.countryFieldId;
		
		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;		
		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";
				
		objDivContainer.innerHTML = innerEtalon;
		var objInputs = objDivContainer.getElementsByTagName('input');

		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;
			objSelects[i].value = 0;
		}
		
		new DutyCalculationCountriesInterface({
						'import_to_field': this.countryFieldId,
						'url': this.url,
						'containerId': this.containerId + this.lastIndex,
						'categoryField': this.categoryFieldId + this.lastIndex,
						'subCategoryField': this.subCategoryFieldId + this.lastIndex,
						'itemsField'	: this.itemsFieldId + this.lastIndex,
						'already_loaded': true});
		
		if( $(this.countryFieldId).value )
		{
			new DutyCalculationProductInterface({
				'acceptor': this.subCategoryFieldId + this.lastIndex,
				'listen': this.categoryFieldId + this.lastIndex,
				'url': this.url,
				'containerId':this.containerId + this.lastIndex,
				'itemsField': this.itemsFieldId + 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 );
		
		$(this.etalonBlock + this.lastIndex).down('div[class="TitleBox"]').show();
		
		objDivContainer.style.display = "";
		
	
		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 == 'IcoForm InfIco')
			{
				objTooltips.setCatcher(objNewTooltips[iTooltipsIndex]);
			}
		}
		
		var closeLink  = Element.down($(objDivContainer.id),'img[alt="Close"]');
		
		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] );
				}
			}
		}
		
		this._setProductEnumeration();
	},
	
	deleteProduct: function( objDeleteClick )
	{
		var objContainerLink = Event.findElement(objDeleteClick,'a');
		var objContainer = objContainerLink.up('div[class="GreyBox"]')
		
		var id_element = objContainer.id;
		Element.remove(objContainer);
		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();
		}
		this._setProductEnumeration();		
	},
	
	/**
	 * @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;
		}
	}
});


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)
			{
				aSelectBoxes[i].disabled = "";
			}
		}
	}
	
});


 

function fireEvent (element,event) 
{
	if (document.createEventObject){
		// dispatch for IE
		var evt = document.createEventObject();
		return element.fireEvent('on'+event,evt)
	}

	else{
		// dispatch for firefox + others
		var evt = document.createEvent("HTMLEvents");
		evt.initEvent(event, true, true ); // event type,bubbling,cancelable
		return !element.dispatchEvent(evt);
	}
}
