var historicalCalculator = new Class({
    initialize: function(fundsStartDates, fundsStartPrices, fundsSCHAEndPrices, getResultsURL, errorMessages) {    	
    	this.fundsStartDates      = fundsStartDates;
    	this.fundsSCHAStartPrices = fundsStartPrices;
    	this.fundsSCHAEndPrices   = fundsSCHAEndPrices;
    	this.getResultsURL        = getResultsURL;
    	this.errorMessages        = errorMessages;
    	
    	this.DAY                  = 60 * 60 * 24;
		this.fundSCHA             = 0;  	    	    	
    	this.currentTimestamp     = $('currentTimestamp').get('value').toInt();
    	this.currentDate          = $('currentDate').get('value');
    	this.buyCommissionPercen  = $('buyCommissionPercen').get('value').toInt();

		this.fundChanger          = $('fundChanger');    	
		this.startDate            = $('calculatorStartDate');
		this.startDate.addEvent('click', function() {
			displayCalendar(this.startDate, 'dd.mm.yyyy', this.startDate);	
		}.bind(this));
		this.startDateSCHA        = $('startDateSCHA');
		this.startDateError       = $('startDateError');
		
        this.endDate              = $('calculatorEndDate');
		this.endDate.addEvent('click', function() {
			displayCalendar(this.endDate, 'dd.mm.yyyy', this.endDate);	
		}.bind(this));          
		this.endDateSCHA          = $('endDateSCHA');		
		this.endDateError         = $('endDateError');
		this.totalInvestment      = $('totalInvestment');
		this.securitiesQuantity   = $('securitiesQuantity');
		this.calculateButton      = $('historicalCalculatorCalculate');
		this.resultDiv            = $('historicalCalculatorResults');
				
		this.run();
	},
	
	run: function() {
		this.fundChanger.addEvent('change', function() {
			if(this.fundChanger.get('value') == 0) {
				this.startDate.getParent().setStyle('display', 'none');
				this.endDate.getParent().setStyle('display', 'none');
				this.totalInvestment.getParent().setStyle('display', 'none');
				this.securitiesQuantity.getParent().setStyle('display', 'none');				
				this.calculateButton.getParent().setStyle('display', 'none');				
			} else {
				this.startDate.getParent().setStyle('display', 'inline');
				this.endDate.getParent().setStyle('display', 'inline');
				this.totalInvestment.getParent().setStyle('display', 'block');
				this.securitiesQuantity.getParent().setStyle('display', 'block');
				this.calculateButton.getParent().setStyle('display', 'block');				
				this.reset(true);
			}			
		}.bind(this) );
				
		//updateStartDate & updateEndDate executing by calendar.js	

		this.totalInvestment.addEvents({
		    'change': function() { 	
		    	if(this.totalInvestment.get('value').contains(',')) {
		    		this.totalInvestment.set('value', this.totalInvestment.get('value').replace(',', '.'));
		    	}		    	
		    	if($type(this.totalInvestment.get('value').toFloat())!='number') {
		    		this.reset(false);
		    	} else {
		    		this.totalInvestment.set( 'value', this.totalInvestment.get('value').toFloat() );		    		
			    	if(this.fundChanger.get('value') == 0) {
			    		this.reset(false);
			    		alert(this.errorMessages['selectFund']);			    
			    	} else {
			    		this.getTotalInvestment();	
			    	}		    			
		    	}
		    }.bind(this)
		});
		
		this.securitiesQuantity.addEvents({
		    'change': function() {
		    	if($type(this.securitiesQuantity.get('value').toInt())!='number') {
		    		this.reset(false);
		    	} else {
		    		this.securitiesQuantity.set( 'value', this.securitiesQuantity.get('value').toInt() );
			    	if(this.fundChanger.get('value') == 0) {
			    		this.reset(false);
			    		alert(this.errorMessages['selectFund']);			    
			    	} else {
			    		this.getSecuritiesQuantity();	
			    	}		    			
		    	}
		    }.bind(this)
		});
		
		this.calculateButton.addEvent('click', function() {
			var errors = new Hash();
			if(this.fundChanger.get('value') == 0) {
				errors.set('selectFund', this.errorMessages['selectFund']);			    
			}
			if($type(this.securitiesQuantity.get('value').toInt())!='number') {
				errors.set('inputSecuritiesQuantity', this.errorMessages['inputSecuritiesQuantity']);
			}
			
			if( errors.getLength() > 0 ) {
				var errorMessage = '';
				errors.each( function(error, errrorID) {
					errorMessage += error + "\n";
				});
				alert(errorMessage);
			} else {
				this.getResults();
			}							
		}.bind(this) );	
	},
    
    reset: function(withDates) {
    	this.totalInvestment.set('value', '');
    	this.securitiesQuantity.set('value', '');
    	
    	if(withDates) {
   		   	this.setDefaultStartDate();
   		   	this.setDefaultFundSCHA();
				  	
   		   	this.endDate.set('value', this.currentDate);
   		   	this.setDefaultSCHAEndPrice();	
    	}    	
    },
    
    setDefaultStartDate: function() {
    	var startDate = new Date( this.fundsStartDates.get(this.fundChanger.get('value')).toInt() * 1000 );
    	var day   = ( startDate.getDate() < 10 ) ? '0' + startDate.getDate() : startDate.getDate();
    	var month = ( ( startDate.getMonth() + 1 ) < 10 ) ? '0' + ( startDate.getMonth() + 1 ) : startDate.getMonth() + 1;
    	this.startDate.set('value', day + '.' + month + '.' + startDate.getFullYear() );    	
    },
    
    setDefaultFundSCHA: function() {
    	this.fundSCHA = this.fundsSCHAStartPrices.get(this.fundChanger.get('value')).toFloat();
    	this.startDateSCHA.set('html', this.fundSCHA.round(2)).getParent().setStyle('display', 'inline');    	
    },

    setDefaultSCHAEndPrice: function() {
    	this.endDateSCHA.set('html', this.fundsSCHAEndPrices.get(this.fundChanger.get('value')).toFloat().round(2)).getParent().setStyle('display', 'inline');    	
    },

	//Execution of this method added to calendar.js
    updateStartDate: function() {
    	this.reset(false);
    	
    	var errorMessages = false;
    	this.startDateError.setStyle('display', 'none');
    	
    	var startDateTimestamp     = this.getTmiestamp(this.startDate);
		var fundStartDateTimestamp = this.fundsStartDates.get(this.fundChanger.get('value')).toInt();		
		if( startDateTimestamp < fundStartDateTimestamp ) {
			errorMessages = this.errorMessages['startDateToEarly'];	
		} else if( startDateTimestamp >= this.getTmiestamp(this.endDate) ) {
			errorMessages = this.errorMessages['startDateToLate'];			
		}
		
		if(errorMessages) {
			this.setDefaultStartDate();
   		   	this.setDefaultFundSCHA();   		   	
			this.startDateError.set('html', errorMessages).setStyle('display', 'block');			
		} else {						
			this.gettingSCHAStart();			
			new Request.JSON({
				url: '/calculator/getfundscha/' + startDateTimestamp + '/' + this.fundChanger.get('value') + '/', 
				onComplete: function(SCHAInfo){										
    				this.fundSCHA = SCHAInfo.SCHAPrice.toFloat();
    				this.startDateSCHA.set('html', this.fundSCHA.round(2))
			    	
					this.gettingSCHAEnd();	
				}.bind(this)
			}).send();
		}			
    },
  
    //Execution of this method added to calendar.js
    updateEndDate: function() {
    	var errorMessages = false;
    	this.endDateError.setStyle('display', 'none');
    	
    	var endDateTimestamp       = this.getTmiestamp(this.endDate);				
		if( endDateTimestamp < (this.getTmiestamp(this.startDate)+this.DAY) ) {
			errorMessages = this.errorMessages['endDateToEarly'];	
		} else if( endDateTimestamp > this.currentTimestamp ) {
			errorMessages = this.errorMessages['endDateToLate'];			
		}
		
		if(errorMessages) {
   		   	this.endDate.set('value', this.currentDate);
   		   	this.setDefaultSCHAEndPrice();
			this.endDateError.set('html', errorMessages).setStyle('display', 'block');			
		} else {						
			this.gettingSCHAStart();
			new Request.JSON({
				url: '/calculator/getfundscha/' + endDateTimestamp + '/' + this.fundChanger.get('value') + '/', 
				onComplete: function(SCHAInfo){										
    				this.endDateSCHA.set('html', SCHAInfo.SCHAPrice.toFloat().round(2))
			    	
					this.gettingSCHAEnd();
				}.bind(this)
			}).send();
		}    	
    },
    
    gettingSCHAStart: function() {
		this.totalInvestment.set('readonly', true);
		this.securitiesQuantity.set('readonly', true);
		this.calculateButton.set('disabled', true);    	
    },
    
    gettingSCHAEnd: function() {
		this.totalInvestment.set('readonly', false);
		this.securitiesQuantity.set('readonly', false);
		this.calculateButton.set('disabled', false);    	
    },    
    
	getTmiestamp: function(el) {
		var dateArray = el.get('value').toString().split('.');
		//var date = new Date(dateArray[2], dateArray[1].toInt() - 1, dateArray[0], 00, 00, 00);
		return (Date.UTC(dateArray[2], dateArray[1].toInt() - 1, dateArray[0], 00, 00, 00))/1000;
	},

    getTotalInvestment: function() { 			
		var fundSCHA        = this.fundSCHA;
		var totalInvestment = this.totalInvestment.get('value').toInt();
		var buyCooficient   = 1 + ( this.buyCommissionPercen / 100 );
									
		var securitiesQuantity = totalInvestment / ( fundSCHA * buyCooficient );
		securitiesQuantity = securitiesQuantity.toInt();

		if( securitiesQuantity > 0 ) {		
			this.securitiesQuantity.set('value', securitiesQuantity); 					
		} else {
			this.totalInvestment.set('value', (fundSCHA * buyCooficient).round(2) );				
			this.securitiesQuantity.set('value', 1);					
		}		
    },
    
    getSecuritiesQuantity: function() {
		var fundSCHA           = this.fundSCHA;
		var securitiesQuantity = this.securitiesQuantity.get('value').toInt();
		var buyCooficient      = 1 + ( this.buyCommissionPercen / 100 );

		if( securitiesQuantity > 0 ) {
			this.totalInvestment.set('value', ( fundSCHA * securitiesQuantity * buyCooficient ).round(2) );				
			this.securitiesQuantity.set('value', securitiesQuantity); 					
		} else {
			this.totalInvestment.set('value', (fundSCHA * buyCooficient).round(2) );				
			this.securitiesQuantity.set('value', 1);					
		}  
    },
	
	getResults: function() {
		this.resultDiv.empty();
		this.resultDiv.addClass('ajax-loader');
		new Request.HTML({
			url:this.getResultsURL + '/' + 
				this.fundChanger.get('value') + '/' + 
				this.getTmiestamp(this.startDate) +  '/' +
				this.getTmiestamp(this.endDate) +  '/' +  
				this.securitiesQuantity.get('value') + '/' + 
				this.totalInvestment.get('value') + '/',
			onSuccess: function(responseTree, responseElements, responseHTML, responseJavaScript) {
				this.resultDiv.removeClass('ajax-loader');
				this.resultDiv.set('html', responseHTML);	
			}.bind(this)					
		}).send();
	}    
});