
var calculator_searchform = Class.create({
	
	calculator: null,
	elements: {
		container: null,
		form: null,
		originalCategoryOptions: null,
        dates : {
            calendar : null,
            earliestSeasonStart : null,
            minCalculationDate : null,
            currentDate : null
        },
		fields: {
            producttype : null,
			supercategory: null,
			category: null,
			persongroup: null,
			desireddate: null
		}
	},
	inProgress: false,

	initialize: function(calculator) {
	
		if(calculator) {
			this.calculator = calculator;
		}
		
		// get elements
		var main = this.calculator.mainframe;
		
		this.elements.container = main.getElementsBySelector(".t_searchform")[0];
		this.elements.form = $(this.elements.container.getElementsByTagName("form")[0]);
		

        this.elements.fields.packagecategory = this.elements.form.getElementsBySelector('select[name="package.category"]')[0];
		this.elements.fields.supercategory = this.elements.form.getElementsBySelector('select[name="supercategory"]')[0];

        this.elements.fields.producttype = this.elements.form.getElementsBySelector('input[name="product.type"]')[0];

		this.elements.fields.category = this.elements.form.getElementsBySelector('select[name="category"]')[0];
		this.elements.fields.persongroup = this.elements.form.getElementsBySelector('select[name="persongroup"]')[0];
		this.elements.fields.desireddate = this.elements.form.getElementsBySelector('input[name="desireddate"]')[0];
		this.elements.fields.validFromLabels = this.elements.form.getElementsBySelector(".t_valid label");
		this.elements.fields.validFromContainer = this.elements.form.getElementsBySelector(".t_valid")[0];

        if( this.elements.fields.category != null ) {
		    this.elements.fields.category.disabled = true;
        }

        if( this.elements.fields.supercategory != null ) {
		    this.elements.fields.supercategory.observe("change",this.onSupercategoryChange.bind(this))
        }
		
		this.elements.form.onsubmit = this.search.bind(this);
		
		
		if($("ticketing_calendar")) {
			var cal = new elementsCalendar({
				button : 'ticketing_calendar',
				output : "singleinput",
				input: "desireddate",
				updateFieldOnStartup : true
			});

            var possibleDate = this.calculator.ticketing.seasonstart;
            var initialDate = new Date();
            initialDate.setHours(0, 0, 0, 0);
            if( initialDate <  possibleDate) {
                initialDate = possibleDate;
            }
            cal.calendar.date = initialDate;
            cal.calendar.dateStr = cal.calendar.date;
            cal.updateDateField(cal.calendar.date);


            this.elements.dates.calendar = cal;
            this.elements.dates.earliestSeasonStart = possibleDate;
            this.elements.dates.minCalculationDate = initialDate;

		}
		


        if( this.elements.fields.category != null ) {
            var categoryOptions = this.elements.fields.category.getElementsBySelector("option");
            this.elements.originalCategoryOptions = new Array(categoryOptions.length);
            for( var i=0; i<categoryOptions.length; i++ ) {
                var option = new Element('option', { 'value': categoryOptions[i].value});
                option.innerHTML= categoryOptions[i].innerHTML;
                option.className = categoryOptions[i].className;
                this.elements.originalCategoryOptions[i] = option;
            }
        }
		
		// hide all valid from labels
		for(var e=0; e<this.elements.fields.validFromLabels.length; e++) {
			this.elements.fields.validFromLabels[e].setStyle({
				display: "none"
			});
		}
		
		this.elements.fields.validFromContainer.setStyle({visibility:"hidden"});

        if( this.elements.fields.supercategory != null ) {
		    this.onSupercategoryChange();
        } else
        if( this.elements.fields.packagecategory != null ) {
            this.onPackageCategoryChange();
        }
		
		// check if there is a direct entry an add eventlisteners to the ticket list
		if(this.calculator.mainframe.getElementsBySelector(".t_searchresults form").length > 0) {
			this.addEventListenerResults();
		}
	},
	
	search: function () {

		if(!this.inProgress) {
			this.elements.form.setAttribute("action", this.calculator.ticketing.locationURL );
			this.elements.form.request({
                method: "POST",
				parameters: {snippet: true},
				onComplete: this.searchComplete.bind(this)
			});
			this.inProgress = true;
			
			var resultsContainer = this.calculator.mainframe.getElementsBySelector(".t_searchresults")[0];
			if(!resultsContainer) {
				this.calculator.mainframe.insert('<div class="t_searchresults"></div>');
				resultsContainer = this.calculator.mainframe.getElementsBySelector(".t_searchresults")[0];
			}
			resultsContainer.innerHTML = '<div class="t_progress">' + calculator_translate("loadingTicketsMessage") + '</div>';
		}
		
		return false;
	},
	
	searchComplete: function (transport) {

		var results = this.calculator.mainframe.getElementsBySelector(".t_searchresults")[0];
		results.replace(transport.responseText);
		this.addEventListenerResults();
		this.inProgress = false;

	},
	
	addEventListenerResults: function () {

		var forms = this.calculator.mainframe.getElementsBySelector(".t_searchresults form");
		for(var i=0; i<forms.length; i++) {
			forms[i].onsubmit = this.addToWatchlist.bind(this,forms[i]);
		}
		
		// check for collapseable containers
		var resultBoxes = this.calculator.mainframe.getElementsBySelector(".t_searchresults .t_resultbox");
		if(resultBoxes.length > 1) {
			// make them collapseable
			
			var handle = null;
			var results = null;
			
			for(var i=0; i<resultBoxes.length; i++) {
				handle = resultBoxes[i].getElementsBySelector(".t_handler")[0];
				results = resultBoxes[i].getElementsBySelector(".t_results")[0];
				
				handle.observe("click", this.resultBoxToogle.bind(this,resultBoxes[i],handle,results));
				resultBoxes[i].removeClassName("up");
				results.hide();
			}
			
			// open first box
			var firstResultBox = resultBoxes[0];
			this.resultBoxToogle(firstResultBox,firstResultBox.getElementsBySelector(".t_handler")[0],firstResultBox.getElementsBySelector(".t_results")[0]);
		}

	},
	
	resultBoxToogle: function (box,handle,results) {
		if(box.hasClassName("up")) {
			results.hide();
			box.removeClassName("up");
		}
		else {
			results.show();
			box.addClassName("up");
		}
	},
	
	addToWatchlist: function (form) {

		form.request({
            parameters: {snippet: true},
			onComplete: this.addToWatchlistComplete.bind(this)
		});
		
		return false;
	},
	
	addToWatchlistComplete: function () {
		this.calculator.watchlist.refresh();
		window.location.href = "#t_watchlist";
	},

    onPackageCategoryChange : function() {
        // display all form elements
        this.elements.fields.validFromContainer.setStyle({visibility:"visible"});
    },

	onSupercategoryChange: function () {
		
		// display all form elements
		this.elements.fields.validFromContainer.setStyle({visibility:"visible"});

        if( this.elements.fields.persongroup != null ) {
		    this.elements.fields.persongroup.up().setStyle({visibility:"visible"});
        }

        var selectedValue = "";
        var selectedOption = null;
        if( this.elements.fields.supercategory != null ) {
            var selectedSuperCategory = this.elements.fields.supercategory.options[this.elements.fields.supercategory.selectedIndex];
            selectedValue = selectedSuperCategory.value;
            selectedOption = $(selectedSuperCategory);

            var hideGroupCategories = selectedOption.hasClassName( "t_nosubtype");
            var count = 0;
            var optionsWithValue = 0;
            var lastOptionWithValue = null;
            var firstOptionWithValue = null;

            // filter the subcategories dependend on the supercategory selection
            var categoryOptions = this.elements.fields.category.getElementsBySelector("option");

            for( var i=0; i<categoryOptions.length; i++ ) {
                categoryOptions[i].remove();
            }

            for(var i=0; i<this.elements.originalCategoryOptions.length; i++) {
                var option = this.elements.originalCategoryOptions[i];
                if(option.hasClassName(selectedValue)) {
                    count++;
                    if(count==1) {
                        option.selected = true;
                    }
                    this.elements.fields.category.insert(option,this.elements.fields.category);

                    if(option.value.length > 0) {
                        optionsWithValue++;

                        if( firstOptionWithValue == null ) {
                            firstOptionWithValue = option;
                        }
                        lastOptionWithValue = option;
                    }
                }
            }

            this.elements.fields.category.disabled = false;

            //if(count < 2 || selectedValue == "") {
            if( hideGroupCategories || selectedValue == "" ) {
                $(this.elements.fields.category.parentNode).setStyle({display:"none"});
            }
            else {
                $(this.elements.fields.category.parentNode).setStyle({display:""});
            }

            if(optionsWithValue < 2) {
                if(lastOptionWithValue) {
                    $(lastOptionWithValue).setAttribute("selected","selected");
                    $(this.elements.fields.category.parentNode).setStyle({display:"none"});
                }
            } else {
                // always select first
                if( firstOptionWithValue != null ) {
                    $(firstOptionWithValue).setAttribute("selected","selected");
                    firstOptionWithValue.parentNode.selectedIndex = firstOptionWithValue.index;
                    //$(this.elements.fields.category.parentNode).hide();
                    //$(this.elements.fields.category.parentNode).show();
                    //$(firstOptionWithValue).show();
                }
            }
        }
		
		
		// display suitable label for date selection
		for(var e=0; e<this.elements.fields.validFromLabels.length; e++) {
			if(this.elements.fields.validFromLabels[e].hasClassName(selectedValue) && selectedValue != "") {
				this.elements.fields.validFromLabels[e].setStyle({
					display: ""
				});
			} else if (e==0 && selectedValue == ""){
                this.elements.fields.validFromLabels[e].setStyle({
					display: ""
				});
            } else {
				this.elements.fields.validFromLabels[e].setStyle({
					display: "none"
				});
			}			
		}

        if( selectedOption != null ) {

            // display valid from container if type matches
            if( selectedOption.hasClassName("t_nodate") ) {
                // hide
                this.elements.fields.validFromContainer.setStyle({visibility:"hidden"});

                var currentDate = this.elements.dates.calendar.calendar.date;
                if( this.elements.dates.minCalculationDate != currentDate ) {
                    // remember current selection
                    this.elements.dates.currentDate = currentDate;

                    var hiddenSelectedDate = this.elements.dates.minCalculationDate;
                    // update current date to minimum
                    // don't know why, but these 2 fields have also to be set
                    this.elements.dates.calendar.calendar.date = hiddenSelectedDate;
                    this.elements.dates.calendar.calendar.dateStr = hiddenSelectedDate;
                    this.elements.dates.calendar.updateDateField( hiddenSelectedDate);
                }
            } else {
                // restore old value
                var currentDate = this.elements.dates.calendar.calendar.date;
                var previousDate = this.elements.dates.currentDate;
                if( previousDate != null && previousDate != currentDate ) {
                    // don't know why, but these 2 fields have also to be set
                    this.elements.dates.calendar.calendar.date = previousDate;
                    this.elements.dates.calendar.calendar.dateStr = previousDate;

                    // update to previous
                    this.elements.dates.calendar.updateDateField( previousDate );
                }
            }


            // disable persongroup's if necessary
            if(selectedOption.hasClassName("t_nopersongroup")) {
                this.elements.fields.persongroup.up().setStyle({visibility:"hidden"});
            }

            // set proper product_type
            if( selectedOption.hasClassName( 't_type_package' ) ) {
                this.elements.fields.producttype.value = 'bundle';
            } else {
                // default to type ticket ( t_type_ticket )
                this.elements.fields.producttype.value = 'ticket';
            }
        }
		
	}
	
});



