/**
 * Date helper object.
 */
var DateHelper = {
	dateDifference : null,
		
	init : function() {
		if ( !this.dateDifference ) {
			if ( serverClientDateDifferrence ) {
				this.dateDifference = serverClientDateDifferrence;
			}
			else {
				this.dateDifference = 0;
			}
		}
	},
	
	serverNow : function() {
		this.init();
		
		var now = new Date();
		now.setSeconds( now.getSeconds()-this.dateDifference , 0);
		return now;
	},
	
	/**
	 * Returns true for high years
	 * @return boolean
	 */
	isHighYear : function(year) {
		if ( year % 4 != 0 ) {
			return false;
		}
		if ( year % 100 != 0 ) {
			return true;
		}
		if ( year % 400 != 0 ) {
			return false;
		}
		return true;
	},
		
	/**
	 * Returns true if date is valid
	 * @return boolean
	 */
	isValidDate : function(day, month, year) {
		if ( day<1 || day>31 ) {
			return false;
		}
		if ( month<1 || month >12 ) {
			return false;
		}
		if ( year<1 || ( year>=100 && year <1000 ) ) {
			return false;
		}
		var yearC = year;
		if ( year<100 ) {
			if ( year >= 30 ) {
				yearC = 1900 + year;
			}
			else {
				yearC = 2000 + year;
			}
		}
		
		if ( day>30 && ( month == 4 || month == 6 || month == 9 || month == 11 ) ) {
			return false;
		}
		
		if ( month == 2 && day>29 ) {
			return false;
		}
		
		if ( month == 2 && day==29 && !this.isHighYear(yearC) ) {
			return false;
		}
		return true;
	},
	
	/**
	 * Returns true if date is already in the past
	 * @return boolean
	 */
	isInThePast : function(day, month, year) {
		var now = this.serverNow();
		
		now.setHours(0, 0, 0, 0);
		
		var nowNum = now.getFullYear()*10000 + (1+now.getMonth())*100 + now.getDate();
		var givenNum = year*10000 + month*100 + day*1;
		
		if ( nowNum > givenNum ) {
			return true;
		}
		return false;
	},
	
	/**
	 * Returns true if date is already in the past
	 * @return boolean
	 */
	isToday : function(day, month, year) {
		var now = this.serverNow();
		
		now.setHours(0, 0, 0, 0);
		
		var nowNum = now.getFullYear()*10000 + (1+now.getMonth())*100 + now.getDate();
		var givenNum = year*10000 + month*100 + day*1;
		
		if ( nowNum == givenNum ) {
			return true;
		}
		return false;
	},
	
	/**
	 * Returns the hours now
	 * @return int
	 */
	getHoursNow : function() {
		var now = this.serverNow();
		return now.getHours();
	},
	
	/**
	 * Returns the minutes now
	 * @return int
	 */
	getMinutesNow : function() {
		var now = this.serverNow();
		return now.getMinutes();
	},
	
	/**
	 * Returns true if the given date is a weekend (Saturday or Sunday)
	 */
	isWeekend : function(day, month, year) {
		var date1 = new Date();
		date1.setFullYear(year, month-1, day);
		date1.setHours(0, 0, 0, 0);
		var weekDay = date1.getDay();
		return ( weekDay == 0 || weekDay == 6 ); 
	}
};

/**************************************************************************************/

/**
 * Order for processor 
 */
var OrderIssueForm = {
	shipping_date_day_fld : undefined,
	shipping_date_month_fld : undefined,
	shipping_date_year_fld : undefined,
	shipping_date_error_span : undefined,
	shipping_date_error_tr : undefined,
	lang : 'lv',
	
	shipping_time_interval_fld : undefined,
	shipping_time_error_tr : undefined,
	shipping_time_error_span : undefined,
	
	exact_interval_from_h_fld : undefined,
	exact_interval_from_m_fld : undefined,
	exact_interval_till_h_fld : undefined,
	exact_interval_till_m_fld : undefined,

	exact_interval_error_tr : undefined,
	exact_interval_error_span : undefined,
	
	city_id_fld : undefined,
	city_error_tr : undefined,
	city_error_span : undefined,
	
	clarify_everything : undefined,
	
	formIsOk : true,
	
	messages : {
		ru : {
			1 : 'Такой даты не существует!',
			2 : 'Эта дата уже в прошлом!',
			3 : 'На сегодня доставка уже не возможна!',
			4 : 'Интервал уже в прошлом!',
			5 : 'Этот интервал уже нельзя выбрать!',
			6 : 'Доставка вне Рижского района на выходных не осуществляется!',
			7 : 'Исправьте, пожалуйста, информацию!',
			8 : 'Интервал не может быть менее одного часа!',
			9 : 'Доставка возможна только через два часа после оформления заказа!'
		},
		lv : {
			1 : 'Šāds datums neeksistē!',
			2 : 'Šāds datums jau ir pagājis!',
			3 : 'Šodien piegāde jau nav iespējama!',
			4 : 'Intervals jau ir pagatnē!',
			5 : 'Šo intervalu vairs nevar izvēlēties!',
			6 : 'Izējamās dienās piegāde ārpus Rīgas rajona netiek piedāvāta!',
			7 : 'Izlabojiet, lūdzu, informāciju!',
			8 : 'Intervāls nevar būt mazāks par vienu stundu!',
			9 : 'Piegāde ir iespējama ne atrāk ka divas stundas pēc pasūtījuma noformēšanas!'
		}
	},
	
	message : function(msgCode) {
		switch ( this.lang ) {
		case 'lv':
			return this.messages.lv[msgCode];
		case 'ru':
			return this.messages.ru[msgCode];
		default:
			return this.messages.ru[msgCode];
		}
	},
		
	initLang : function(lang) {
		this.lang = lang;
	},

	init : function() {
		this.shipping_date_day_fld    = $('shipping_date_day');
		this.shipping_date_month_fld  = $('shipping_date_month');
		this.shipping_date_year_fld   = $('shipping_date_year');
		this.shipping_date_error_span = $('shipping_date_error');
		this.shipping_date_error_tr   = $('shipping_date_error_tr');
		
		this.shipping_time_interval_fld = $('shipping_time_interval');
		this.shipping_time_error_tr     = $('shipping_time_error_tr');
		this.shipping_time_error_span   = $('shipping_time_error');

		this.exact_interval_from_h_fld = $('exact_interval_from_h');
		this.exact_interval_from_m_fld = $('exact_interval_from_m');
		this.exact_interval_till_h_fld = $('exact_interval_till_h');
		this.exact_interval_till_m_fld = $('exact_interval_till_m');
		
		this.exact_interval_error_tr = $('exact_interval_error_tr');
		this.exact_interval_error_span = $('exact_interval_error');
		
		this.city_id_fld     = $('city_id');
		this.city_error_tr   = $('city_error_tr');
		this.city_error_span = $('city_error');
		
		this.clarify_everything = $('clarify_everything');
	},

	highlightShippingDate : function(msgCode) {
		this.init();

		this.shipping_date_day_fld.setStyle({backgroundColor : '#FFAAAA'});
		this.shipping_date_month_fld.setStyle({backgroundColor : '#FFAAAA'});
		this.shipping_date_year_fld.setStyle({backgroundColor : '#FFAAAA'});
		
		this.shipping_date_error_span.update( this.message(msgCode) );
		this.shipping_date_error_tr.setStyle({display : ''});
	},
	
	unhighlightShippingDate : function() {
		this.init();

		this.shipping_date_day_fld.setStyle({backgroundColor : 'white'});
		this.shipping_date_month_fld.setStyle({backgroundColor : 'white'});
		this.shipping_date_year_fld.setStyle({backgroundColor : 'white'});

		this.shipping_date_error_span.update( '' );
		this.shipping_date_error_tr.setStyle({display : 'none'});
	},
	
	dateIsOk : function(day, month, year) {
		if ( !DateHelper.isValidDate( day, month, year ) ) {
			this.highlightShippingDate( 1 );
			return false;
		}
		else if ( DateHelper.isInThePast( day, month, year ) ) {
			this.highlightShippingDate( 2 );
			return false;
		}
		else if ( DateHelper.isToday( day, month, year ) && DateHelper.getHoursNow() >= 22 ) {
			this.highlightShippingDate( 3 );
			return false;
		}
		
		this.unhighlightShippingDate();
		return true;
	},
	
	showHideExactInterval : function(interval) {
		if ( interval == 'exact' ) {
			$('shipping_exact_time_tr').setStyle({display : ''});
		}
		else {
			$('shipping_exact_time_tr').setStyle({display : 'none'});
		}
	},
	
	highlightInterval : function(msgCode) {
		this.init();

		this.shipping_time_interval_fld.setStyle({backgroundColor : '#FFAAAA'});
		this.shipping_time_error_span.update( this.message(msgCode) );
		this.shipping_time_error_tr.setStyle({display : ''});
	},
	
	unhighlightInterval : function() {
		this.init();

		this.shipping_time_interval_fld.setStyle({backgroundColor : 'white'});
		this.shipping_time_error_span.update( '' );
		this.shipping_time_error_tr.setStyle({display : 'none'});
	},
	
	intervalIsOk : function(interval, day, month, year) {
		if ( DateHelper.isToday( day, month, year ) ) {
			var hoursNow = DateHelper.getHoursNow();
			var intervalEnd  = null;
			var acceptedTill = null;
			
			switch ( parseInt( interval ) ) {
			case 1:
				intervalEnd  = 14;
				acceptedTill = 11;
				break;
			case 2:
				intervalEnd  = 18;
				acceptedTill = 15;
				break;
			case 3:
				intervalEnd  = 24;
				acceptedTill = 22;
				break;
			case 4:
				intervalEnd  = 8;
				acceptedTill = 4;
				break;
			}
			
			if ( hoursNow >= intervalEnd ) {
				this.highlightInterval(4);
				return false;
			}
			
			if ( hoursNow >= acceptedTill ) {
				this.highlightInterval(5);
				return false;
			}
		}
		this.unhighlightInterval();
		return true;
	},
	
	getCorrectedInterval : function(interval, day, month, year) {
		if ( DateHelper.isWeekend(day, month, year) ) {
			return 5;
		}
		return interval;
	},

	getCityIntervalRawPrice : function(city_id, correctedInterval) {
		if ( !intervalPrices ) {
			return -1;
		}

		if ( !intervalPrices[city_id] ) {
			return -1;
		}
		
		return intervalPrices[city_id].timeIntervals[correctedInterval];
	},
	
	highlightCity : function(msgCode) {
		this.init();

		this.city_id_fld.setStyle({backgroundColor : '#FFAAAA'});
		this.city_error_span.update( this.message(msgCode) );
		this.city_error_tr.setStyle({display : ''});
	},
	
	unhighlightCity : function() {
		this.init();

		this.city_id_fld.setStyle({backgroundColor : 'white'});
		this.city_error_span.update( '' );
		this.city_error_tr.setStyle({display : 'none'});
	},
	
	cityIsOk : function(city_id, interval, day, month, year) {
		var finalInterval = this.getFinalInterval();
		var price = this.getCityIntervalRawPrice(city_id, finalInterval);
		
		if ( price>=0 ) {
			this.unhighlightCity();
			return true;
		}
		this.highlightCity(6);
		return false;
	},
	
	highlightExactInt : function(msgCode) {
		this.init();

		this.exact_interval_till_h_fld.setStyle({backgroundColor : '#FFAAAA'});
		this.exact_interval_till_m_fld.setStyle({backgroundColor : '#FFAAAA'});
		
		if ( msgCode == 9 ) {
			this.exact_interval_from_h_fld.setStyle({backgroundColor : '#FFAAAA'});
			this.exact_interval_from_m_fld.setStyle({backgroundColor : '#FFAAAA'});
		}
		
		this.exact_interval_error_tr.setStyle({display : ''});
		this.exact_interval_error_span.update( this.message(msgCode) );
	},
	
	unhighlightExactInt : function() {
		this.init();

		this.exact_interval_till_h_fld.setStyle({backgroundColor : 'white'});
		this.exact_interval_till_m_fld.setStyle({backgroundColor : 'white'});
		this.exact_interval_from_h_fld.setStyle({backgroundColor : 'white'});
		this.exact_interval_from_m_fld.setStyle({backgroundColor : 'white'});
		
		if ( this.exact_interval_error_tr ) {
			this.exact_interval_error_tr.setStyle({display : 'none'});
		}
		if ( this.exact_interval_error_span ) {
			this.exact_interval_error_span.update( '' );
		}
	},
	
	exactIntervalIsOk : function() {
		var fromH = this.exact_interval_from_h_fld.getValue();
		var fromM = this.exact_interval_from_m_fld.getValue();
		var tillH = this.exact_interval_till_h_fld.getValue();
		var tillM = this.exact_interval_till_m_fld.getValue();

		if ( (tillH*60+tillM*1) - (fromH*60+fromM*1) < 60 ) {
			this.highlightExactInt(8);
			return false;
		}
		
		var day = this.shipping_date_day_fld.getValue();
		var month = this.shipping_date_month_fld.getValue();
		var year = this.shipping_date_year_fld.getValue();

		if ( DateHelper.isToday(day, month, year) ) {
			var hoursNow = DateHelper.getHoursNow();
			if ( hoursNow+2 > fromH || ( hoursNow+2 == fromH && DateHelper.getMinutesNow() > fromM ) ) {
				this.highlightExactInt(9);
				return false;
			}
		}
		
		this.unhighlightExactInt();
		return true;
	},
	
	formIsValid : function() {
		this.init();
		
		//--------------- Validate the date ---------------
		var day = this.shipping_date_day_fld.getValue();
		var month = this.shipping_date_month_fld.getValue();
		var year = this.shipping_date_year_fld.getValue();
		
		if ( !this.dateIsOk(day, month, year) ) {
			return false;
		}
		
		//--------------- Validate the interval ---------------
		var interval = this.shipping_time_interval_fld.getValue();
		if ( interval != 'exact' ) {
			if ( !this.intervalIsOk(interval, day, month, year) ) {
				return false;
			}
		}
		else { // exact
			if ( !this.exactIntervalIsOk() ) {
				return false;
			}
		}
		
		//--------------- Validate the city ---------------
		var city_id = this.city_id_fld.getValue();
		if ( !this.cityIsOk(city_id, interval, day, month, year) ) {
			return false;
		}
		
		return true;
	},
	
	getFinalInterval : function() {
		var day = this.shipping_date_day_fld.getValue();
		var month = this.shipping_date_month_fld.getValue();
		var year = this.shipping_date_year_fld.getValue();
		var interval = this.shipping_time_interval_fld.getValue();

		if ( interval != 'exact' ) {
			return this.getCorrectedInterval(interval, day, month, year);
		}

		var fromH = this.exact_interval_from_h_fld.getValue();

		var interval2;
			
		if ( fromH >= 8 && fromH < 14 ) {
			interval2 = 1;
		}
		else if ( fromH >= 14 && fromH < 18 ) {
			interval2 = 2;
		}
		else if ( fromH >= 18 && fromH < 24 ) {
			interval2 = 3;
		}
		else if ( fromH >= 0 && fromH < 8 ) {
			interval2 = 4;
		}
		return this.getCorrectedInterval(interval2, day, month, year);
	},
	
	calculatePrice : function() {
		var interval = this.shipping_time_interval_fld.getValue();
		var city_id = this.city_id_fld.getValue();
		var clarify_everything = this.clarify_everything.getValue() == 1 ? true : false;
		
		var corrInterval = this.getFinalInterval();
		var price = this.getCityIntervalRawPrice(city_id, corrInterval);;
		if ( interval == 'exact' ) {
			price += intervalPrices[city_id].exactInterval;
		}

		return price + (clarify_everything ? 3 : 0);
	},
	
	formUpdated : function( place ) {
		this.init();
		
		this.formIsOk = this.formIsValid();
		
		if ( place == 'shipping_time' ) {
			var interval = this.shipping_time_interval_fld.getValue();
			this.showHideExactInterval(interval);
		}

		if ( this.formIsOk ) {
			var price = this.calculatePrice();
			$('thePrice').update( price );
			$('jsPrice').setValue( price );
		}
		else {
			$('thePrice').update( '??' );
			$('jsPrice').setValue( '' );
		}
	},
	
	submitFormIfOk : function() {
		this.init();
		this.formIsOk = this.formIsValid();
		if ( this.formIsOk ) {
			$('jsValidated').setValue(1);
			$('ShippingInfo').submit();
		}
		else {
			alert( this.message(7) );
		}
	}
};

var RecipientInfoForm = {
	lang : 'lv',

	messages : {
		ru : {
			1 : 'Заполните обязательные поля!'
		},
		lv : {
			1 : 'Aizpildiet obligātus laukus!'
		}
	},
	
	message : function(msgCode) {
		switch ( this.lang ) {
		case 'lv':
			return this.messages.lv[msgCode];
		case 'ru':
			return this.messages.ru[msgCode];
		default:
			return this.messages.ru[msgCode];
		}
	},
		
	initLang : function(lang) {
		this.lang = lang;
	},

	unmarkIfFilled : function(elemId) {
		elem = $( elemId );
		if ( !(elem.getValue().strip().empty()) ) {
			elem.setStyle({backgroundColor : 'white'});
		}
	},
	
	submitFormIfOk : function() {
		var ok = true;
		var mandatoryFields = [ 'name', 'surname', 'phone' ];
		
		var elem;
		for ( var fieldNo=0; fieldNo<mandatoryFields.length; fieldNo++ ) {
			elem = $( mandatoryFields[fieldNo] );
			if ( elem.getValue().strip().empty() ) {
				elem.setStyle({backgroundColor : 'yellow'});
				ok = false;
			}
		}

		if ( ok ) {
			$('jsValidated').setValue(1);
			$('RecipientInfo').submit();
		}
		else {
			alert( this.message(1) );
		}
	}
};

var SenderInfoForm = {
	lang : 'lv',

	messages : {
		ru : {
			1 : 'Заполните обязательные поля!'
		},
		lv : {
			1 : 'Aizpildiet obligātus laukus!'
		}
	},
	
	message : function(msgCode) {
		switch ( this.lang ) {
		case 'lv':
			return this.messages.lv[msgCode];
		case 'ru':
			return this.messages.ru[msgCode];
		default:
			return this.messages.ru[msgCode];
		}
	},
		
	initLang : function(lang) {
		this.lang = lang;
	},

	showHideNotApplicabbleFields : function(type) {
		var hide = false;
		if ( type == 'p' ) {
			hide = true;
		}
		var i;
		for ( i=1; i<=4; i++ ) {
			$('jur'+i).setStyle({display : hide ? 'none' : ''});
		}
	},
	
	unmarkIfFilled : function(elemId) {
		elem = $( elemId );
		
		if ( !(elem.getValue().strip().empty()) ) {
			elem.setStyle({backgroundColor : 'white'});
		}
	},
	
	submitFormIfOk : function() {
		var ok = true;
		var mandatoryFields;
		
		if ( $('person_type_physical').getValue() == 'physical' ) {
			mandatoryFields = [ 'your_name', 'your_surname', 'your_phone', 'your_email' ];
		}
		else {
			mandatoryFields = [ 'legal_name', 'registration_number', 'legal_address', 'your_name', 'your_surname', 'your_phone', 'your_email' ];
		}
		
		var elem;
		for ( var fieldNo=0; fieldNo<mandatoryFields.length; fieldNo++ ) {
			elem = $( mandatoryFields[fieldNo] );
			if ( elem.getValue().strip().empty() ) {
				elem.setStyle({backgroundColor : 'yellow'});
				ok = false;
			}
		}

		if ( ok ) {
			$('jsValidated').setValue(1);
			$('SenderInfo').submit();
		}
		else {
			alert( this.message(1) );
		}
	}
};

var PriceOrderForm = {
	lang : 'lv',

	messages : {
		ru : {
			1 : 'Ознакомьтесь, пожалуйста, с правилами доставки и подтвердите своё согласие!'
		},
		lv : {
			1 : 'Iepazinieties, lūdzu, ar piegādes noteikumiem, un apstipriniet savu piekrišanu!'
		}
	},
		
	message : function(msgCode) {
		switch ( this.lang ) {
		case 'lv':
			return this.messages.lv[msgCode];
		case 'ru':
			return this.messages.ru[msgCode];
		default:
			return this.messages.ru[msgCode];
		}
	},
			
	initLang : function(lang) {
		this.lang = lang;
	},

	submitFormIfOk : function() {
		if ($('agree').getValue()==1) {
			$('jsValidated').setValue(1);
			$('PriceOrderInfo').submit();
			return true;
		}
		else {
			alert( this.message(1) );
		}
		return false;
	}
};
