var SubTariffSelector = jQuery.Class.create({
	init: function(tariffs, savedPeriods, currentTariff, payPal) {
		this.tariffs = tariffs;
		this.periods = savedPeriods;
		//console.log(this.tariffs);
		//console.log(this.periods);
		this.currSystem =  $('#currSystem');
		this.currentTariff = currentTariff;
		this.methodTitle = $('#subTariffSelector')[0];
		this.tariffLinks = $('#tariffsLinks')[0];
		this.tariffButton = $('#tariffButton')[0];
		this.tariffFooter = $('#tariffFooter')[0];
		this.cost = $('#cost')[0];
		this.period = $('#period')[0];
		//$(this.selector).bind("change", {parent:this, sender: this.selector}, 
		//	function(eventData) { eventData.data.parent.updateInfo(eventData.data.sender); });
		this.costs = $('#costs')[0];
		this.costsForDay = $('#costsForDay')[0];
		this.subTariffHidden = $('#subTariffHidden')[0];
		this.paymentSelectorForm = $('#paymentSelectorForm');
		this.paymentSelectorForm.bind('submit', {parent: this}, function(e) {
			e.data.parent.getFormCode();
			e.preventDefault();
		});
		this.payPal = payPal;
		this.hideEmptyCells();
		this.messages = general.tariff;
		this.paymentType = (location.href.indexOf('/sms')==-1) ? 'emoney' : 'sms';
		//this.baseUrl = (location.href.indexOf('/turbo')==-1) ? '/turbolight/' : '/turbo/'+this.paymentType+'/';
		this.baseUrl = (location.pathname.indexOf('/turbo')==-1) ? '/payments/'+this.paymentType+'/tariff/' : '/turbo/'+this.paymentType+'/';
		//console.log('this.baseUrl ', this.baseUrl);
		this.remarksArea = $('.system-remarks');
	},
	
	setPremiumUrl: function(premiumUrl) {
		if(typeof(premiumUrl)=='undefined') {
			var premiumUrl = '/turbo';
		}
		this.premiumUrl = premiumUrl+'/';
		//this.baseUrl = (location.href.indexOf(premiumUrl)==-1) ? '/payments/'+this.paymentType+'/tariff/' : this.premiumUrl+this.paymentType+'/';
		this.baseUrl = (location.href.indexOf(premiumUrl)==-1) ? '/turbolight/'+this.paymentType+'/' : this.premiumUrl+this.paymentType+'/';
	},

	hideEmptyCells: function() {
		// Show all cells
		var rows = [this.tariffLinks.cells, this.costs.cells, this.costsForDay.cells, this.tariffButton.cells, this.tariffFooter.cells];
		for(var rowIndex=0; rowIndex < rows.length; rowIndex++) {
			var tmpRowCells = rows[rowIndex];
			for(var i=0; i < tmpRowCells.length; i++) {
				//console.log(tmpRowCells[i]);
				$(tmpRowCells[i]).show();
			}
		}
		// Hide unused cells
		var rows = [this.costs.cells, this.costsForDay.cells, this.tariffButton.cells, this.tariffFooter.cells];
		var hidenIndexes = [];
		for(var rowIndex=0; rowIndex < rows.length; rowIndex++) {
			var tmpRowCells = rows[rowIndex];
			for(var i=0; i < tmpRowCells.length; i++) {
				if(this.costs.cells[i].innerHTML =='' || $(this.costs.cells[i]).find('.tariff-cell').html() =='') {
					$(tmpRowCells[i]).hide(); //style.display = 'none';
					hidenIndexes.push(i);
				}
			}
		}
		for(var j=0; j < hidenIndexes.length; j++) {
			$(this.tariffLinks.cells[hidenIndexes[j]]).hide() ;//.style.display = 'none';
		}
	},
	
	updateInfo: function(sender) {
		var selectedId = sender.value;
		var index = 0;
		//console.log('tariffs');
		//console.log(this.tariffs);
		for(var i in this.tariffs) {
			if(i=='indexOf') { // Dirty hack for IE
				continue;
			}
			var currPeriods = this.periods[this.tariffs[i].id];
			//console.log('currPeriods', currPeriods);
			if(typeof(currPeriods)=='undefined') {
				//this.vipPeriods.cells[index].innerHTML = '';
				this.costs.cells[index].innerHTML = '';
				this.costsForDay.cells[index].innerHTML = '';
				this.tariffButton.cells[index].innerHTML = '';
				index++;
				continue;
			}
			// Обновление данных в таблице с тарифами
			var drawed = false;
			for(var j=0; j < currPeriods.length; j++) {
				//console.log(currPeriods[j].id+'-'+selectedId);
				if((currPeriods[j].mode_id == selectedId)) {
					if (currPeriods[j].tariff_id == this.currentTariff) {
						this.cost.innerHTML = currPeriods[j].amount+' '+currPeriods[j].unit;
						this.period.innerHTML = currPeriods[j].period;
						this.subTariffHidden.value = currPeriods[j].id;
						this.methodTitle.innerHTML = currPeriods[j].mode;
						this.currSystem.val(currPeriods[j].mode_id);
					}
					drawed = true;
					this.costs.cells[index].innerHTML = '<div class="tariff-cell">'+currPeriods[j].amount+' '+currPeriods[j].unit+'</div>';
					this.costsForDay.cells[index].innerHTML = '<div class="tariff-cell"><span class="costLable">'+(Math.round(currPeriods[j].day_amount*100)/100)+'</span><br/>'+
						'<span class="currencyLable">'+currPeriods[j].unit+'/'+this.messages.day+'</span></div>';
					if(typeof(currPeriods[j].id)!='undfined') {
						this.tariffButton.cells[index].innerHTML = '<div class="tariff-cell"><input type="button" value="'+this.messages.make_payment_sms+
							'" onclick="subTariffSelector.selectSubTariff('+currPeriods[j].id+');" /></div>';
					}
				}
			}
			if(selectedId==3) { // Plimus
				this.remarksArea[0].innerHTML = this.messages.plimusRemarks;
			} else {
				this.remarksArea[0].innerHTML = '';
			}
			if(selectedId==5) { // EXWM PayPal
				$('.remindCodeLink').show();
			} else {
				$('.remindCodeLink').hide();
			}
			if( selectedId==1 || selectedId==4) { // WM
				$('#wmBanners').show();
			} else {
				$('#wmBanners').hide();
			}
			if(!drawed) {
				this.costs.cells[index].innerHTML = '';
				this.costsForDay.cells[index].innerHTML = '';
				this.tariffButton.cells[index].innerHTML = '';
			}
			index++;
		}
		// Обновление ссылок в таблице с тарифами
		var index = 1;
		for(var i in this.tariffs) {
			if(i=='indexOf') { // Dirty hack for IE
				continue;
			}
			// Проверяем что тариф есть для палтежных систем вообще
			if(typeof(this.periods[this.tariffs[i].id])!='undefined') {
				var currPeriods = this.periods[this.tariffs[i].id];
			} else {
				index++;
				continue;
			}
			for(var j=0; j < currPeriods.length; j++) {
				// Проверяем что данная платежная система есть в этом тарифе
				if((currPeriods[j].mode_id == selectedId)) {
					var jqAnchor = $(this.tariffLinks.cells[index-1]).find('a');
					//console.log(jqAnchor);
					if(jqAnchor.length>0) {
						jqAnchor.attr('href', 'javascript:void(0)');
					}
				}
			}
			index++;
		}
		this.hideEmptyCells();
	},
	
	getFormCode: function() {
		//var paymentSystemId = $('#currSystem').val();
		var subTariffId = $('#subTariffHidden').val();
		var paymentFormArea = $('#paymentForm');
		//console.log(window.files);
		var payPal = /*(this.payPal) ? 1 :*/ 0;
		$.ajax({
			async: false,
			type: "GET",
			url: "/payments/emoney/drawPremiumFormCode/"+subTariffId+"/"+payPal,
			success: function(msg){
				paymentFormArea.html(msg);
			}
		});
		paymentFormArea.find('form')[0].submit();
	},
	
	selectSubTariff: function (subTariffId) {
		$('#subTariffHidden').val(subTariffId);
		this.getFormCode();
	}
});