﻿var VIPTicketCombosPanel = Class.create(Panel, {
	initialize: function ($super, passportReference, tridionPanelId, panelPosition) {
		$super(passportReference, tridionPanelId);
		this.panelId = 'VIPTicketCombo';
		this.panelPosition = panelPosition;
		this.strParams = [];
		this.classPrefix = 'viptc';
    },
    doWork: function () {
	
		this.calendarInput = this.panelHTML.select('[name=dateOfArrival]')[0];
		this.adultInput = this.panelHTML.select('[name=inputAdultQuantity]')[0];
		this.childInput = this.panelHTML.select('[name=inputChildQuantity]')[0];
		
		this.__setupCalendarWithCallback(this.calendarInput, function () {
			var data = this.panelHTML.select('form')[0].serialize(true);
			new Ajax.Request('/home.aspx/GetVIPTicketComboInfo', {
				contentType: 'application/json',
				postBody: Object.toJSON({
					strStartDate: data.dateOfArrival,
					strVirtualCatalogName: 'Ecommerce - UO Main Online'
				}),	
				onSuccess: function (response) {
					this.data = response.responseJSON.d.evalJSON();
					//console.log(this.data);
					this.dataPark1 = this.__filterDayTicketByDay(this.data.Edj);
					
					var bt = this.panelHTML.select('.park1Table')[0];
					bt.update('');
					this.__generateRowsFor2PricesEvent('dp1', 'productVariantCatalog', this.dataPark1, bt, this.adultInput, this.childInput);

					
					this.validateFields();
				}.bind(this)
			});	
		}.bind(this));
		this.__setupInput(this.adultInput);
		this.__setupInput(this.childInput);
		
		this.__setupAddToCart();
		this.panelHTML.select('.park1Table')[0].update('');	
		
		this.validateFields();
		
	},
	__filterDayTicketByDay: function (dataCollection) {
        var newData = $A();
        dataCollection.each(function (item) {
            newData.push(item);
        });
        var newDataHash = $H();
        newData.each(function (item) {
            if (newDataHash.get(item.Des) == undefined) {
                newDataHash.set(item.Des, {
				description: item.Des,
				productID1: '',
				productID2: '',
				variantID1: '',
				variantID2: '',
				catalog1: '',
				catalog2: '',
				stringPrice1: '',
				stringPrice2: '',
				stringTotalPrice: '-',
				price1: '',
				price2: '',
				popupKey: '',
				descriptionTicket: ''
                });
            }
            var currentItem = newDataHash.get(item.Des);
			currentItem.descriptionTicket = item.Det;
			currentItem.popupKey = item.Des.substring(0,1);
            if (item.Vde == "Adult") {
				currentItem.eventID1 = item.Eid.trim();
				currentItem.plu1 = item.PLU.trim();
				currentItem.resourceID1 = item.Rid.trim();
				currentItem.date1 = item.De;
				currentItem.stringPrice1 = '$ ' + (parseFloat(item.Pri)).toFixed(2);
				currentItem.price1 = parseFloat(item.Pri);
            }
            else {
				currentItem.eventID2 = item.Eid.trim();
				currentItem.plu2 = item.PLU.trim();
				currentItem.resourceID2 = item.Rid.trim();
				currentItem.date2 = item.De;
				currentItem.stringPrice2 = '$ ' + (parseFloat(item.Pri)).toFixed(2);
				currentItem.price2 = parseFloat(item.Pri);
            }
        });
        return newDataHash;
    },
	__generateRowsFor2PricesEvent: function(setIdentifier, inputName, dataCollection, el, input1, input2) {
		var rowTemplate = new Template('<tr><td><input type="radio" name="' + inputName + '" value="#{eventID1}|#{eventID2}|#{plu1}|#{plu2}|#{resourceID1}|#{resourceID2}|#{date1}|#{date2}" /> <a href="javascript:void(0);" id="popup_#{popupKey}">#{description}</a></td><td>#{stringPrice1}</td><td>#{stringPrice2}</td><td class="' + setIdentifier + 'tp">#{stringTotalPrice}</td></tr>');
		var html = '';
		
		dataCollection.each(function (pair) {
			html += rowTemplate.evaluate(pair.value);
		});		
		el.update(html);
		
		this.__generateTotalPrice2Prices(setIdentifier, dataCollection, input1, input2);
		
		[input1, input2].each(function (input) {
			input.observe('keyup', function (event) {
				this.__generateTotalPrice2Prices(setIdentifier, dataCollection, input1, input2);
			} .bind(this));
		}.bind(this));
		
		el.select('a').each(function (aEl) {
			aEl.onClickWithContext(this, function (event) {

				var aClass = aEl.readAttribute('id');
				if (aClass.startsWith('popup')) {
					var splitted = aClass.split('_');
					var days = splitted[1];
					var item = null;
					var popup = $('DescriptionTicket');
					var left = parseInt((800 - popup.getWidth()) / 2);
					item = this.__getFilteredEventItemByDay(dataCollection, days);
					var description = popup.select('.description')[0];
					description.update(item.descriptionTicket);
					popup.show();
					popup.setStyle({'left': left + 'px'});
					
				}
			});
		}.bind(this));
		
		el.select('input[type=radio]').each(function (inputRadio) {
			inputRadio.onClickWithContext(this, function () {
				this.__validateSubmit();
				this.__removeHighlightRow();
				this.__removeChecks();
				inputRadio.up(1).addClassName('selectedTr');				
				var formData = this.panelHTML.select('form')[0].serialize(true);								
				this.saveValueChanged('radio/' + this.classPrefix  + inputName, formData[inputName]);				
				this.saveValueChanged('checkbox/' + this.classPrefix  + 'subProduct', '');
			});
		} .bind(this));
	},
	__getFilteredEventItemByDay: function (dataCollection, day) {
		var result = null;
		dataCollection.each(function (item) {
            if (item.value.popupKey == day) {
                result = item;
            }
		});
		return result.value;
	},
	_formatDataAndSend: function (data) {
		var ppqc = data.productVariantCatalog.split('|');
		var dataFormatted1 = {
			eventID: ppqc[0].trim(),
			plu: ppqc[2].trim(),
			resourceID: ppqc[4].trim(),
			qty: data.inputAdultQuantity,
			date: ppqc[6].trim(),
			catalogName: data.hdnVirtualCatalog
		};
		var dataFormatted2 = {
			eventID: ppqc[1].trim(),
			plu: ppqc[3].trim(),
			resourceID: ppqc[5].trim(),
			qty: data.inputChildQuantity,
			date: ppqc[7].trim(),
			catalogName: data.hdnVirtualCatalog
		};
		this.passportReference.addEventToCart(dataFormatted1);
		this.passportReference.addEventToCart(dataFormatted2);
    },
    _validateInputData: function (data) {
		var adultQuantity = jsHelper.toInt(data.inputAdultQuantity);
		var childQuantity = jsHelper.toInt(data.inputChildQuantity);
		return (data.productVariantCatalog != undefined && (adultQuantity > 0 || childQuantity > 0));
    }
});
