﻿/*
*******************************************************
****** CLIENT API OF THE AVAILABILITY-PRICE-PAGE *******
*******************************************************
*/

//this class is responsible to provide an client-api for the availability-price page
function AvailabilityPriceManager()
{    
    //members
    this.contractEnd = "";
    this.monthNames = null; //May,Jun,Jul,Aug...
    this.monthNamesLong = null; //May,June,July,August...
    this.dayNamesShort = null;//Mo,Tu,We,Th..
    this.additionalServiceTypeTextList = null; // Associative array of the AdditionalServiceType with the corresponding Text e.G: = { "abc":200, "xyz": 300};
    this.isCalenderScrolling = false;
    this.isMonthCalenderScrolling = false;
    this.nbrVisibleMonthCalenderElements = 12; //defines how many month-calender elements are visible at the same time    
    this.nbrVisibleCalenderElements = 4; //defines how many calender-elements are visible at the same time
    this.nbrOfMonthsToJump = 2; //defines how many months should be jumped by clicking on the arrows
    this.selectedMonth = 0;
    this.selectedYear = 0;
    this.selectedDate = "";
    this.currentMonthCalIndex = 0; //index of the first visible month-calender element
    this.currentCalIndex = 0; //index of the first visible calender element
    this.elementIndexToJumpTo = 0;
    this.nbrCalElements = 0;
    this.nbrMonthCalElements = 0;
    this.availabilityAndPriceServiceURL = "";
    this.dateDurationPricesServiceURL = "";
    this.periodPriceListServiceURL = "";
    this.getExtraCostsURL = "";
    this.accommodationCode = "";
    this.storedDuration = 0;
    this.aapPriceResult = null;
    this.bookingBaseURL = "";
    this.onRequestInfoHTML = "";
    this.isPeriodePriceListDataLoaded = false;
    this.msgGlobalCalenderError = "";
    this.msgErrObjectSoldOut = "";
    this.isDatePreSelected = false;
    this.selectorAccoDetailInfoBox = "";
    this.selectorAccoDetailBookingButton = "";
    this.selectorAccoDetailBookingDate = "";
    this.selectorAccoDetailBookingPrice = "";
    this.selectorExtraCosts = "";
    
    //Initialize is loaded after the object was created
    this.Initialize = function () {
    	//load the full mont-calender structure
    	this.LoadMonthCalender();

    	//load the calender structur without the days    
    	this.LoadCalenders();

    	//populate the first two calender elements
    	var calenderElements = this.GetCalenderElements();
    	if (calenderElements.length >= 2) {
    		var month = this.GetDatePartFromISODate(this.selectedDate, "month");
    		var year = this.GetDatePartFromISODate(this.selectedDate, "year");

    		this.PopulateCalender(calenderElements.filter("table[month=" + month + "][year=" + year + "]"));

    		for (var i = 1; i < this.nbrVisibleCalenderElements; i++) {
    			month = parseInt(month) + 1;
    			if (month == 13) {
    				month = 1;
    				year = parseInt(year) + 1;
    			}
    			this.PopulateCalender(calenderElements.filter("table[month=" + month + "][year=" + year + "]"));
    		}
    	}

    	//populate the dropdownlist duration
    	this.LoadDurationPriceData();

    	if (this.selectedDate == "") {
    		this.HideAllCalenders();
    		this.HidePeriodPriceList();
    	}
    }
    
    //set the selected month and year from the month-calender
    this.SetSelectedMonthYear = function (lnkMonth, month, year) {
    	if (this.selectedMonth != month || this.selectedYear != year) {
    		this.selectedMonth = month;
    		this.selectedYear = year;
    		this.elementIndexToJumpTo = $(lnkMonth).attr("id").replace('lnkMonthCal', '');
    		this.AnimateCalender("", this.selectedMonth, this.selectedYear);
    	}

    	//dismark all month-calender elements
    	//$("#divMonthSliderGateInner").children().css("background-color", "");
    	$("#divMonthSliderGateInner").children().removeClass('ui-state-hover');
    	//mark the current month-calender element
    	//$(lnkMonth).css("background-color", "#b5cbe4").next().eq(0).css("background-color", "#b5cbe4");
    	$(lnkMonth).addClass('ui-state-hover noBorder');
    	if (this.nbrVisibleCalenderElements == 2) {
    		$(lnkMonth).next().eq(0).addClass('ui-state-hover noBorder');
    	}
    	else if (this.nbrVisibleCalenderElements == 3) {
    		$(lnkMonth).next().eq(0).addClass('ui-state-hover noBorder')
				.next().eq(0).addClass('ui-state-hover noBorder');
    	}
    	else if (this.nbrVisibleCalenderElements == 4) {
    		$(lnkMonth).next().eq(0).addClass('ui-state-hover noBorder')
				.next().eq(0).addClass('ui-state-hover noBorder')
				.next().eq(0).addClass('ui-state-hover noBorder');
    	}
    	return false;
    }
    
    //set the selected date from the calender
    this.SetArrivalDate = function (calenderIndex, date) {
    	this.HideAjaxLoader();

    	if (this.selectedDate == date)
    		return false;

    	this.selectedDate = date;
    	var month = parseInt(this.GetDatePartFromISODate(this.selectedDate, "month"));
    	var year = parseInt(this.GetDatePartFromISODate(this.selectedDate, "year"));
    	this.selectedMonth = month - 1;
    	this.selectedYear = year;
    	this.elementIndexToJumpTo = calenderIndex;

    	//put the calender to the right position
    	if (calenderIndex > parseInt(this.currentCalIndex)) {
    		this.AnimateCalender('', this.selectedMonth, this.selectedYear);
    	}

    	this.ShowAjaxLoader();
    	this.LoadDurationPriceData();
    }
    
          
    
    //gets the width of an single month-calender element
    this.GetMonthCalenderElementWidth = function()
    {
        return $("#divMonthSliderGateInner").children("a").eq(0).width();
    }
    
    //gets the width of an single calender element
    this.GetCalenderElementWidth = function()
    {
        return $("#divDuplexCalendarGateInner").children("div").eq(0).width();
    }
    
    //sets the visibility of the month-calender arrows
    this.SetMonthCalenderArrowVisibility = function(btnType, isVisible)
    {
        var displayValue = (isVisible) ? "visible" : "hidden";
        if (btnType == 'left')
            $(".linkMonthSliderButtonLeft").css("visibility", displayValue);
        else if (btnType == 'right')
            $(".linkMonthSliderButtonRight").css("visibility", displayValue);
    }
    
    //sets the visibility of the calender arrows
    this.SetCalenderArrowVisibility = function(btnType, isVisible)
    {
        var displayValue = (isVisible) ? "visible" : "hidden";
        if (btnType == 'left')
            $(".linkDuplexCalendarButtonLeft").css("visibility", displayValue);
        else if (btnType == 'right')
            $(".linkDuplexCalendarButtonRight").css("visibility", displayValue);
    }
    
    //animates the monthCalender
    this.AnimateMonthCalender = function(direction)
    {                
        if (this.isMonthCalenderScrolling)
            return false;
                                
        this.isMonthCalenderScrolling = true;
            
        var monthCalenderElementWidth = this.GetMonthCalenderElementWidth() + 1;
         
        if (direction == 'right')
        {                
            if (this.currentMonthCalIndex == 0)
            {
                this.isMonthCalenderScrolling = false;
                return false;
            }

            $("#divMonthSliderGateInner").animate({"left": "+=" + monthCalenderElementWidth + "px"}, "fast", function(target){target.isMonthCalenderScrolling = false;}(this));                              
            this.currentMonthCalIndex--;
        }
        else if (direction == 'left')
        {
            if (this.currentMonthCalIndex == (this.nbrMonthCalElements - this.nbrVisibleMonthCalenderElements))
            {
                this.isMonthCalenderScrolling = false;
                return false;
            }
            
            if (this.nbrMonthCalElements <= this.nbrVisibleMonthCalenderElements)
            {
                this.isMonthCalenderScrolling = false;
                return false;
            }
            
            $("#divMonthSliderGateInner").animate({"left": "-=" + monthCalenderElementWidth + "px"}, "fast", function(target){target.isMonthCalenderScrolling = false;}(this));                                                              
            this.currentMonthCalIndex++;
        }

        return false;
    }

    //animates the calender
    this.AnimateCalender = function (direction, month, year) {
    	if (this.isCalenderScrolling)
    		return false;

    	this.isCalenderScrolling = true;

    	var isJumpSearch = false;
    	var calenderElements = this.GetCalenderElements();

    	var calenderElementWidth = this.GetCalenderElementWidth() + 2;

    	if (direction != "") { //if animated bei arrow it goes here
    		if (this.currentCalIndex == 1)
    			pixelToAnimate = calenderElementWidth;
    		else
    			pixelToAnimate = calenderElementWidth * this.nbrOfMonthsToJump; //jump x months so multiply by number of months to scroll
    	}
    	else //if animated by click on the month-calender it goes here
    	{
    		direction = (this.elementIndexToJumpTo > this.currentCalIndex) ? 'left' : 'right';
    		pixelToAnimate = (this.elementIndexToJumpTo > this.currentCalIndex) ? (this.elementIndexToJumpTo - this.currentCalIndex) * calenderElementWidth : (this.currentCalIndex - this.elementIndexToJumpTo) * calenderElementWidth;
    		this.currentCalIndex = this.elementIndexToJumpTo;
    		isJumpSearch = true;
    	}

    	if (direction == 'right') {
    		if (this.currentCalIndex == 0 && isJumpSearch == false) {
    			this.isCalenderScrolling = false;
    			return false;
    		}

    		$("#divDuplexCalendarGateInner").animate({ "left": "+=" + pixelToAnimate + "px" }, "slow", function (target) { target.isCalenderScrolling = false; } (this));
    		if (!isJumpSearch) {
    			this.currentCalIndex = parseInt(this.currentCalIndex) - parseInt(this.nbrOfMonthsToJump);
    			if (this.currentCalIndex < 0)
    				this.currentCalIndex = 0;
    			for (var i = 0; i < this.nbrOfMonthsToJump; i++) {
    				this.PopulateCalender(calenderElements.eq(parseInt(this.currentCalIndex) + i));
    			}
    		}
    	}
    	else if (direction == 'left') {
    		if (this.currentCalIndex > (this.nbrCalElements - this.nbrVisibleCalenderElements)) {
    			if (!isJumpSearch) {
    				this.isCalenderScrolling = false;
    				return false;
    			}
    		}

    		$("#divDuplexCalendarGateInner").animate({ "left": "-=" + pixelToAnimate + "px" }, "slow", function (target) { target.isCalenderScrolling = false; } (this));
    		if (!isJumpSearch) {
    			for (var i = 0; i < this.nbrVisibleCalenderElements; i++) {
    				this.PopulateCalender(calenderElements.eq(parseInt(this.currentCalIndex) + parseInt(this.nbrVisibleCalenderElements) + i));
    			}
    			this.currentCalIndex = parseInt(this.currentCalIndex) + parseInt(this.nbrOfMonthsToJump);
    		}
    	}

    	if (isJumpSearch) {
    		for (var i = 0; i < this.nbrVisibleCalenderElements; i++) {
    			this.PopulateCalender(calenderElements.eq(parseInt(this.currentCalIndex) + i));
    		}
    	}

    	this.MarkMonthCalElement(this.currentCalIndex);

    	return false;
    }

    //returns the contract end
    this.GetContractEnd = function()
    {
        if (this.contractEnd == null || this.contractEnd == "" || this.contractEnd.length != 10)
        {                            
            $("#divBookingTableList").html("<div style='margin-top:10px;'><b>" + this.msgGlobalCalenderError + "</b></div>").next().eq(0).hide();  
            return null;         
        }

        var myDate = new Date(parseInt(this.GetDatePartFromISODate(this.contractEnd, "year")), parseInt(this.GetDatePartFromISODate(this.contractEnd, "month"))-1, parseInt(this.GetDatePartFromISODate(this.contractEnd, "day")));

        if (isNaN(myDate) || myDate <= new Date())
        {            
            $("#divBookingTableList").html("<div style='margin-top:10px;'><b>" + this.msgGlobalCalenderError + "</b></div>").next().eq(0).hide();             
            return null;
        }

        return myDate;
    }
    
    //if the month-calender is loaded this function will be fired
    this.OnMonthCalenderLoaded = function () {
    	var monthCalenderElements = this.GetMonthCalenderElementes();
    	this.nbrMonthCalElements = monthCalenderElements.length;

    	//mark the current calendar elements
    	for (var i = 0; i < this.nbrVisibleCalenderElements; i++) {
    		monthCalenderElements.eq(i).addClass('ui-state-hover noBorder');
    	}
    }

    //if the calender is loaded this function will be fired
    this.OnCalendersLoaded = function()
    {
        var calenderElements = this.GetCalenderElements();  
        this.nbrCalElements = calenderElements.length;
    }

    //Loads the month calender row
    this.LoadMonthCalender = function()
    {
        var contractEnd = this.GetContractEnd();

        if (contractEnd == null)
            return false;

        var now = new Date();
        now.setDate(1);

        var idCounter = 0;

        while(!(now.getFullYear() == contractEnd.getFullYear() && now.getMonth() == contractEnd.getMonth()))
        {
            $("#divMonthSliderGateInner").append("<a id=\"lnkMonthCal" + idCounter + "\" month=\"" + (now.getMonth()+1) + "\" year=\"" + now.getFullYear()  + "\" href=\'#\' onClick=\"return apManager.SetSelectedMonthYear(this," + now.getMonth() + "," + now.getFullYear() + ")\"><span>" + this.monthNames[now.getMonth()] + "</span>" + now.getFullYear() + "</a>");
            now.setMonth(now.getMonth()+1);          
            idCounter++;
        }
        $("#divMonthSliderGateInner").append("<a id=\"lnkMonthCal" + idCounter + "\" month=\"" + (now.getMonth()+1) + "\" year=\"" + now.getFullYear()  + "\" href=\'#\' onClick=\"return apManager.SetSelectedMonthYear(this," + now.getMonth() + "," + now.getFullYear() + ")\"><span>" + this.monthNames[now.getMonth()] + "</span>" + now.getFullYear() + "</a>");

        this.OnMonthCalenderLoaded();                                                              
    }

    //Loads the calender
    this.LoadCalenders = function()
    {
        var contractEnd = this.GetContractEnd();
        if (contractEnd == null)
            return false;        

        var now = new Date();
        now.setDate(1);

        var idCounter = 0;
        
        while(!(now.getFullYear() == contractEnd.getFullYear() && now.getMonth() == contractEnd.getMonth()))   
        {            
            var calenderContentRaw = "<div id=\"divCal" + idCounter + "\" class=\"divDuplexCalendarMonthView\">";
            calenderContentRaw +=           "<table id=\"tblCal" + idCounter + "\" class=\"tableDuplexCalendar\" cellspacing=\"0\" month=\"" + (parseInt(now.getMonth())+1) + "\" year=\"" + now.getFullYear() + "\">";
            calenderContentRaw += "             <caption class=\"ui-state-default noBorder\">" + this.monthNamesLong[now.getMonth()] + " " + now.getFullYear() + "</caption>";
            calenderContentRaw +=               "<thead>";
            calenderContentRaw +=                   "<tr>";

            for (var i=0; i<7; i++)
            	calenderContentRaw += "<th class=\"ui-state-hover\">" + this.dayNamesShort[i] + "</th>";

            calenderContentRaw +=                   "</tr>";
            calenderContentRaw +=               "</thead>";
            calenderContentRaw +=               "<tbody>";
            calenderContentRaw +=               "</tbody>";
            calenderContentRaw +=           "</table>";
            calenderContentRaw +=           "<div style=\"margin-top:50px;\">Loading</div>";
            calenderContentRaw +=    "</div>";
            $("#divDuplexCalendarGateInner").append(calenderContentRaw);
            now.setMonth(now.getMonth()+1);           
            idCounter++; 
        }

        var calenderContentRaw = "<div id=\"divCal" + idCounter + "\" class=\"divDuplexCalendarMonthView\">";
        calenderContentRaw +=           "<table id=\"tblCal" + idCounter + "\" class=\"tableDuplexCalendar\" cellspacing=\"0\" month=\"" + (parseInt(now.getMonth())+1) + "\" year=\"" + now.getFullYear() + "\">";
        calenderContentRaw += "             <caption class=\"ui-state-default noBorder\">" + this.monthNamesLong[now.getMonth()] + " " + now.getFullYear() + "</caption>";
        calenderContentRaw +=               "<thead>";
        calenderContentRaw +=                   "<tr>";

        for (var i=0; i<7; i++)
        	calenderContentRaw += "<th class=\"ui-state-hover\">" + this.dayNamesShort[i] + "</th>";

        calenderContentRaw +=                   "</tr>";
        calenderContentRaw +=               "</thead>";
        calenderContentRaw +=               "<tbody>";
        calenderContentRaw +=               "</tbody>";
        calenderContentRaw +=           "</table>";
        calenderContentRaw +=           "<div style=\"margin-top:50px;\">Loading</div>";
        calenderContentRaw +=    "</div>";
        $("#divDuplexCalendarGateInner").append(calenderContentRaw);

        this.OnCalendersLoaded();               
    }

    //populates the calender with days and
    this.PopulateCalender = function (calenderElement) {
    	if (calenderElement.attr("class") != "tableDuplexCalendar")
    		return;

    	var calIndex = calenderElement.attr("id").substr(6);

    	if (!calenderElement.attr("isPopulated")) {
    		var month = parseInt(calenderElement.attr("month"));
    		var year = parseInt(calenderElement.attr("year"));

    		//create the params for the ajax call                                   
    		var params = { accommodationCode: this.accommodationCode, month: { Year: year, Month: month, Day: 1} };

    		//perform the ajax-call                                       
    		$.ajax({
    			type: "POST",
    			contentType: "application/json; charset=utf-8",
    			dataType: "json",
    			url: this.availabilityAndPriceServiceURL,
    			data: JSON.stringify(params),
    			success: function (data) {

    				//delete the loading-progress message
    				calenderElement.next().remove();

    				//daten übernehmen
    				var aapMonth = data.d;

    				//create the day-string for the calender
    				var days = "";
    				for (var i = 0; i < aapMonth.ws.length; i++) {
    					days += "<tr>";

    					for (var x = 0; x < aapMonth.ws[i].ds.length; x++) {
    						var cellContent = "";
    						var cellAttributes = "";
    						var cellClass = "";

    						switch (aapMonth.ws[i].ds[x].p) {
    							case "A": //Available start day
    								cellClass = "tdArrivalPossible";
    								cellAttributes = " day=\"" + aapMonth.ws[i].ds[x].t1 + "\"";
    								cellContent = "<a href='#' onClick=\"apManager.SetArrivalDate(" + calIndex + ", '" + aapMonth.ws[i].ds[x].dt.Year + "-" + aapMonth.ws[i].ds[x].dt.Month + "-" + aapMonth.ws[i].ds[x].dt.Day + "'); return false;\" title='" + aapMonth.ws[i].ds[x].t2 + "'>" + aapMonth.ws[i].ds[x].t1 + "</a>";
    								break;
    							case "O": //Ohter month
    								cellContent = "&nbsp;";
    								break;
    							case "F": //Free but no start day
    								cellClass = "tdArrivalNotPossible";
    								cellAttributes = " day=\"" + aapMonth.ws[i].ds[x].t1 + "\"";
    								cellContent = aapMonth.ws[i].ds[x].t1;
    								break;
    							case "N": //Not bookable
    								cellClass = "tdBooked";
    								cellContent = aapMonth.ws[i].ds[x].t1;
    								break;
    						}

    						//check for special price
    						if (aapMonth.ws[i].ds[x].sp && cellContent != "&nbsp;") {
    							cellClass = cellClass + " tdSpecialprice";
    						}

    						days += "<td class='" + cellClass + "'" + cellAttributes + ">" + cellContent + "</td>";
    					}

    					days += "</tr>";
    				}

    				//append the days to the calender-element
    				calenderElement.children("tbody").append(days);

    				//sign the calender as populated
    				calenderElement.attr("isPopulated", "yes");

    			},
    			error: function (xhr) {
    				//alert("ajax-error during populating the calender");
    			}
    		})

    	}
    }
    
    //Loads the duration price data
    this.LoadDurationPriceData = function()
    {
            if (this.selectedDate == "")
            {
                $("#divBookingTableList").html("<div class='ma1000'><br/><b>" + this.msgErrObjectSoldOut + "</b><br/><br/><br/></div>").next().eq(0).hide();             
                return;
            }
                                                    
            var month = this.GetDatePartFromISODate(this.selectedDate, "month"); //this.selectedDate.substring(this.selectedDate.indexOf('-')+1,this.selectedDate.lastIndexOf('-'));
            month = parseInt(month);
            
            var year = parseInt(this.GetDatePartFromISODate(this.selectedDate, "year"));
            var day = parseInt(this.GetDatePartFromISODate(this.selectedDate, "day"));
            
            //create the params for the ajax call
            var params = { accommodationCode:this.accommodationCode, selectedDate: {Year:year, Month:month, Day:day} };
                        
            //perform the ajax-call                             
            $.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    url: this.dateDurationPricesServiceURL,
                    data: JSON.stringify(params),
                    success: this.OnLoadDurationPriceDataSuccess,
                    error: function(xhr) {
                            //alert("ajax-error during loading duration price data");
                    },
                    caller: this
                  })
    }
    
    //fires as call back after the duration price data is loaded by ajax
    this.OnLoadDurationPriceDataSuccess = function(data)
    {
        //this case is only executed once on the loading to preselect the checkIn date
        if (!this.caller.isDatePreSelected)
        {
            var month = this.caller.GetDatePartFromISODate(this.caller.selectedDate, "month");
            var year = this.caller.GetDatePartFromISODate(this.caller.selectedDate, "year");
            $("#divMonthSliderGateInner a[month=" + month + "][year=" + year + "]").click();
            this.caller.isDatePreSelected = true;
        }
        
        this.caller.aapPriceResult = data.d;
        this.caller.PopulateDurationDDL();
        this.caller.MarkStartDateOnCalender();
        this.caller.PopulateFirstDurationPriceRow();   
        //this.caller.PopulateDurationPriceList();     
        
        this.caller.HideAjaxLoader();

    }
    
    //shows the ajaxLoader for the calender
    this.ShowAjaxLoader = function()
    {
        $("#divAjaxLoader").css("display", "block");     
    }
    
    //hides the ajaxLoader for the calender
    this.HideAjaxLoader = function()
    {
        $("#divAjaxLoader").css("display", "none");    
    }
    
    //populates the duration ddl with the duration price data
    this.PopulateDurationDDL = function()
    {        
        if (this.aapPriceResult != null)
        {
            //populate the duration dropdownlist
            $("#ddlCalDuration").children().remove();
            for (var i=0; i < this.aapPriceResult.durPris.length; i++)
            {
                $("#ddlCalDuration").append("<option value=\"" + this.aapPriceResult.durPris[i].d + "\">" + this.aapPriceResult.durPris[i].dT + "</option>");
            }
        }
        
        //preselect the ddl
        this.PreSelectDurationDDL();
    }
    
    //preselect the duration ddl and returns the selected duration
    this.PreSelectDurationDDL = function() {
    	var isSelected = false;
    	var ddl = $("#ddlCalDuration")[0];

    	if (ddl) {
    		// 1. try to select the selected duration before
    		for (var i = 0; i < ddl.options.length; i++) {
    			if (parseInt(ddl.options[i].value) == this.storedDuration) {
    				ddl.options[i].setAttribute('selected', true); //use setAttribute-Method to select it, otherwise it crashes in IE6 !!!             
    				isSelected = true;
    				this.storedDuration = parseInt(ddl.options[ddl.selectedIndex].value);
    				//alert("1");
    				break;
    			}
    		}

    		//2. try to select the one week duration
    		if (!isSelected) {
    			for (var i = 0; i < ddl.options.length; i++) {
    				if (parseInt(ddl.options[i].value) == 7) {
    					ddl.options[i].setAttribute('selected', true);   //use setAttribute-Method to select it, otherwise it crashes in IE6 !!!                
    					isSelected = true;
    					this.storedDuration = parseInt(ddl.options[ddl.selectedIndex].value);
    					//alert("2");
    					break;
    				}
    			}
    		}

    		//3. for default select the first duration option
    		if (!isSelected) {

    			for (var i = 0; i < ddl.options.length; i++) {
    				if (ddl.options[i] != null) {
    					if (parseInt(ddl.options[i].value) > 0) {
    						ddl.options[i].setAttribute('selected', true);   //use setAttribute-Method to select it, otherwise it crashes in IE6 !!!                
    						isSelected = true;    					
    						this.storedDuration = parseInt(ddl.options[i].value);
    						//alert("3");
    						break;    						
    					}
    				}
    			}
    		}
    	}

    	//alert("stored duration=" + this.storedDuration);
    	return this.storedDuration;
    }
    
    //fires if the duration has changed
    this.OnDurationChange = function() {
        var ddl = $("#ddlCalDuration")[0];
        this.storedDuration = parseInt(ddl.options[ddl.selectedIndex].value);
        this.MarkStartDateOnCalender();
        this.PopulateFirstDurationPriceRow();
    }
    
    this.OnKeyUpDurationChange = function()
    {
        if ($.browser.mozilla)        
            this.OnDurationChange();
    }
    
    //populates the first duration price row
    this.PopulateFirstDurationPriceRow = function () {
    	var ddl = $("#ddlCalDuration");
    	var duration = this.storedDuration; //parseInt(ddl[0].options[ddl[0].selectedIndex].value);
    	var durPrisElement = null;

    	//find the right duration and price row
    	if (this.aapPriceResult != null && duration > 0) {
    		for (var i = 0; i < this.aapPriceResult.durPris.length; i++) {
    			if (parseInt(this.aapPriceResult.durPris[i].d) == duration) {
    				durPrisElement = this.aapPriceResult.durPris[i];
    				break;
    			}
    		}
    	}

    	//    	var priceText = ddl.parent().nextAll().eq(1).children().eq(0);
    	//    	var linkContainer = ddl.parent().nextAll().eq(2).children();

    	//    	// Remove the "on request info link" if it is present
    	//    	if (linkContainer.length > 1) {
    	//    		linkContainer.eq(0).remove();
    	//    		linkContainer = ddl.parent().nextAll().eq(2).children();
    	//    	}
    	//remove info icon of on request
    	//ddl.parent().nextAll().eq(3).children().remove();

    	if (durPrisElement == null) {
    		//set the period of travel
    		//ddl.parent().next().eq(0).html("").append("<nobr>N/A</nobr>");
    		$(this.selectorAccoDetailBookingDate).html("").append("<nobr>N/A</nobr>");
    		//set the price
    		//priceText.html("").append("N/A");
    		$(this.selectorAccoDetailBookingPrice).html("").append("N/A");
    		//hide the book button
    		//linkContainer.eq(0).attr("style", "visibility:hidden");
    		$(this.selectorAccoDetailBookingButton).attr("style", "visibility:hidden");

    		//show info box
    		$(this.selectorAccoDetailInfoBox).attr("style", "visibility:visible");
    	}
    	else {
    		var addOnRequestLink = false;

    		//hide info box
    		$(this.selectorAccoDetailInfoBox).attr("style", "visibility:hidden");

    		//show the booking button
    		//linkContainer.eq(0).attr("style", "visibility:visible");
    		$(this.selectorAccoDetailBookingButton).attr("style", "visibility:visible");
    		$(this.selectorAccoDetailBookingButton).html("").append(durPrisElement.bT);

    		//set the period of travel
    		//ddl.parent().next().eq(0).html("").append("<nobr>" + durPrisElement.dSE + "</nobr>");
    		$(this.selectorAccoDetailBookingDate).html("").append(durPrisElement.prvT);

    		//set the price                
    		if (durPrisElement.hSP) {
    			//priceText.html("").append(durPrisElement.c + "<span style='text-decoration:line-through;'>" + durPrisElement.p + "</span>&nbsp;<span style='color:red;'>" + durPrisElement.sP + "</span>");
    			$(this.selectorAccoDetailBookingPrice).html("").append("<span style='text-decoration:line-through;'>" + durPrisElement.c + " " + durPrisElement.p + "</span>&nbsp;<span class='font125' style='color:#B82626;'>" + durPrisElement.c + " " + durPrisElement.sP + "</span>");
    		}
    		else {
    			//priceText.html("").append(durPrisElement.c + " " + durPrisElement.p);
    			$(this.selectorAccoDetailBookingPrice).html("").append("<span class='font125'>" + durPrisElement.c + " " + durPrisElement.p + "</span>");
    		}

    		//set the booking link
    		var href = this.GetValidBookingURL(durPrisElement.sDt.Year + "-" + durPrisElement.sDt.Month + "-" + durPrisElement.sDt.Day, duration);
    		$(this.selectorAccoDetailBookingButton).attr("href", href);

    		if (durPrisElement.iB) {
    			//linkContainer.eq(0).attr("class", "fg-button ui-state-highlight fg-button-icon-left ui-corner-all");
    		}
    		else {
    			//linkContainer.eq(0).attr("class", "fg-button ui-state-highlight fg-button-icon-left ui-corner-all");
    			addOnRequestLink = true;
    		}

    		//linkcontainer.eq(0)
    		//	.attr("href", href)
    		//	.html("<span class='ui-icon ui-icon-circle-triangle-e'></span>" + durpriselement.bt);

    		if (addOnRequestLink) {
    			//linkContainer.eq(0).removeClass('ui-state-highlight').addClass('ui-state-default');
    			// do not add the info icon! SP3 has no icon anymore
    			//ddl.parent().nextAll().eq(3).append(this.onRequestInfoHTML);
    		} else {
    			//linkContainer.eq(0).removeClass('ui-state-default').addClass('ui-state-highlight');
    		}

    		var year = durPrisElement.sDt.Year;
    		var month = durPrisElement.sDt.Month;
    		var day = durPrisElement.sDt.Day;

    		//create the params for the ajax call
    		var params = { accommodationCode: this.accommodationCode, selectedDate: { Year: year, Month: month, Day: day }, selectedDuration: durPrisElement.d };

    		//perform the ajax-call                             
    		$.ajax({
    			type: "POST",
    			contentType: "application/json; charset=utf-8",
    			dataType: "json",
    			url: this.getExtraCostsURL,
    			data: JSON.stringify(params),
    			success: this.OnGetExtraCostsSuccess,
    			error: function (xhr) {
    				alert("ajax-error during loading duration price data" + xhr.toString());
    			},
    			caller: this
    		})
    	}
    }

    //fires as call back after the get extra costs text is loaded by ajax
    this.OnGetExtraCostsSuccess = function (data) {
    	var includedServices = new Array(); // Y2
    	var excludedServices = new Array(); // Y1

    	if (data.d["InPriceIncluded"] != undefined) {
    		includedServices = data.d["InPriceIncluded"];
    	}

    	if (data.d["ExtracostOnPlace"] != undefined) {
    		excludedServices = data.d["ExtracostOnPlace"];
    	}

    	var extraCostsTables = this.caller.CreateExtraCostsTable(this.caller.additionalServiceTypeTextList["InPriceIncluded"], includedServices);
    	extraCostsTables += this.caller.CreateExtraCostsTable(this.caller.additionalServiceTypeTextList["CostsOnInvoice"], excludedServices);
    	$(this.caller.selectorExtraCosts).html("").append(extraCostsTables);
    	//$(this.caller.selectorExtraCosts).html("").append(data.d);

    }

    this.CreateExtraCostsTable = function (tableTitle, additionalServiceList) {
    	var extraCostsTable = "<table class=\"list w100\"><tbody>";
    	extraCostsTable += "<tr>";
    	extraCostsTable += "  <td colspan=\"3\"><strong>" + tableTitle + "</strong></td>";
    	extraCostsTable += "</tr>";
    	for (var key in additionalServiceList) {
    		var additionalService = additionalServiceList[key];
    		extraCostsTable += "<tr>";
    		extraCostsTable += "<td><strong>" + additionalService.Description + "</strong><br>" + additionalService.PaymentInfo + "</td>";
    		extraCostsTable += "<td style=\"width: 10%;\" class=\"vaBo\">" + additionalService.CurrencyISOCode + "</td>";
    		extraCostsTable += "<td style=\"width: 10%;\" class=\"vaBo tright\">" + additionalService.Amount + "</td>";
    		extraCostsTable += "</tr>";
    	}

    	extraCostsTable += "</tbody></table>";
		return extraCostsTable;
    }

    //returns a valid url to the booking-process
    this.GetValidBookingURL = function(startDate, duration) 
    {
        return this.bookingBaseURL
            .replace("--0--", startDate)
            .replace("--1--", duration);
    }

    //get all calender elements
    this.GetCalenderElements = function()
    {
        return $("table[class='tableDuplexCalendar']");
    }

    //get all month-calender elements
    this.GetMonthCalenderElementes = function()
    {
        return $("#divMonthSliderGateInner").children("a");
    }

    //mark the month-calender element by index
    this.MarkMonthCalElement = function (index) {

    	$("#divMonthSliderGateInner").children().removeClass('ui-state-hover');
    	//$("#lnkMonthCal" + index).addClass('ui-state-hover noBorder');
    	//$("#lnkMonthCal" + (index + 1)).addClass('ui-state-hover noBorder');
    	for (var i = 0; i < this.nbrVisibleCalenderElements; i++) {
    		$("#lnkMonthCal" + (index + i)).addClass('ui-state-hover noBorder');
    	}
    }

    this.MarkStartDateOnCalender = function()
    {        
        var dayCellsCal1 = $("#tblCal" + this.currentCalIndex + " tbody tr td");
        var dayCellsCal2 = $("#tblCal" + (parseInt(this.currentCalIndex) + 1) + " tbody tr td");                      
        var startDay = this.GetDatePartFromISODate(this.selectedDate, "day");        
        var ddl = $("#ddlCalDuration")[0];
        var duration = 0;

        if (ddl != null && ddl.selectedIndex > -1)
            duration = parseInt(ddl.options[ddl.selectedIndex].value);

        var counter = 0;
        if (duration > 0)
        {
            //clear all selectedDays first
            var relevantTables
            $("table[id*='tblCal'] tbody tr td[class*='tdSelectedDates']").removeClass("tdSelectedDates");

            //select the day in the first visible calender
            for(var i=0; i < dayCellsCal1.length; i++)
            {                
                if (counter == duration)
                    break;

                if (dayCellsCal1.eq(i).attr("day"))
                {
                    if (parseInt(startDay) == parseInt(dayCellsCal1.eq(i).attr("day")) || counter > 0)
                    {                            
                        dayCellsCal1.eq(i).addClass("tdSelectedDates");                                                    
                        counter++;
                    }                    
                }
            }

            //select the possible days in the second visible calender
            if (counter != duration)
            {
                var startDayAlreadySelected = true;
                if (counter == 0)
                    startDayAlreadySelected = false;                   


                for(var i=0; i < dayCellsCal2.length; i++)
                {
                    //all days are selected on the calender 2
                    if (counter == duration)
                        break;

                    if (startDayAlreadySelected)   
                    {
                        if (dayCellsCal2.eq(i).attr("day"))
                        {
                            //selecte here the rest of the days in calender 2
                            //the startdate is on calender 1
                            dayCellsCal2.eq(i).addClass("tdSelectedDates");                                                                          
                            counter++;
                        }
                    }
                    else if (!isNaN(dayCellsCal2.eq(i).attr("day")) && parseInt(startDay) == parseInt(dayCellsCal2.eq(i).attr("day")))
                    {
                        //select here the startDay on the calender 2, when its not
                        //already selected on the calender 1
                        dayCellsCal2.eq(i).addClass("tdSelectedDates");    
                        startDayAlreadySelected = true; 

                        counter++;
                    }
                }
            }
        }
    }

    this.GetDatePartFromISODate = function(ISODate, part)
    {
        var part = part.toLowerCase();
        var returnValue = "";
        switch(part)
        {
            case "year":
                returnValue = ISODate.substring(0,4);             
                break;
            case "month":
                returnValue = ISODate.substring(5, ISODate.lastIndexOf("-"));
                                
                if (returnValue.substr(0,1) == "0")
                    returnValue = returnValue.substr(1,1);

                break;
            case "day":
                returnValue = ISODate.substring(ISODate.lastIndexOf("-")+1);
                
                if (returnValue.substr(0,1) == "0")
                    returnValue = returnValue.substr(1,1);

                break;
        }   
        return returnValue;
    }

    this.PopulateDurationPriceList = function() {
        //delete the full list first
//        $("#tableBookingTableList tbody tr:gt(0)").remove();
//        
//        for (var i = 0; i < this.aapPriceResult.durPris.length; i++) {
//            if (this.aapPriceResult.durPris[i].d == -1) {
//                // Trennstrich darf nicht ausgegeben werden
//                continue;
//            }

//            //create the row
//            durationPriceRow = "<tr>";
//            durationPriceRow += "<td style=\"white-space:nowrap;\">" + this.aapPriceResult.durPris[i].dT + "</td>";
//            durationPriceRow += "<td>" + this.aapPriceResult.durPris[i].dSE + "</td>";
//            if (this.aapPriceResult.durPris[i].hSP) {
//                durationPriceRow += "<td>" + this.aapPriceResult.durPris[i].c + "<span style='text-decoration:line-through;'>" + this.aapPriceResult.durPris[i].p + "</span>&nbsp;<span style='color:red;'>" + this.aapPriceResult.durPris[i].sP + "</span></td>";
//            }
//            else
//                durationPriceRow += "<td>" + this.aapPriceResult.durPris[i].c + " " + this.aapPriceResult.durPris[i].p + "</td>";

//            var href = this.GetValidBookingURL(this.aapPriceResult.durPris[i].sDt.Year + "-" + this.aapPriceResult.durPris[i].sDt.Month + "-" + this.aapPriceResult.durPris[i].sDt.Day, this.aapPriceResult.durPris[i].d);
//            if (this.aapPriceResult.durPris[i].iB) {
//            	durationPriceRow += '<td colspan="2"><a href="' + href + '" class="fg-button ui-state-highlight fg-button-icon-left ui-corner-all"><span class="ui-icon ui-icon-circle-triangle-e"></span>' + this.aapPriceResult.durPris[i].bT + '</a></td>';
//            }
//            else {
//            	durationPriceRow += "<td><a href=\"" + href + "\" class=\"fg-button ui-state-default fg-button-icon-left ui-corner-all\" style=\"white-space:nowrap;\"><span class=\"ui-icon ui-icon-circle-triangle-e\"></span>" + this.aapPriceResult.durPris[i].bT + "</a></td><td>" + this.onRequestInfoHTML + "</td>";
//            }
//            durationPriceRow += "</tr>";

//            //append the row to the table
//            $("#tableBookingTableList tbody").append(durationPriceRow);
//        }
    }

    this.LoadPeriodPriceListData = function() {

        if (this.isPeriodePriceListDataLoaded)
            return;

        //set the loading text           
        $("#divPeriodePriceList").children().remove();
        $("#divPeriodePriceList").append("<div style='text-align:center'>Loading...</div>");

        //create the params for the ajax call
        var month = this.GetDatePartFromISODate(this.selectedDate, "month");
        month = parseInt(month);
        var year = parseInt(this.GetDatePartFromISODate(this.selectedDate, "year"));
        var day = parseInt(this.GetDatePartFromISODate(this.selectedDate, "day"));

        var params = { accommodationCode: this.accommodationCode, selectedDate: { Year: year, Month: month, Day: day }, selectedDuration: this.storedDuration };

        //perform the ajax-call                                       
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            url: this.periodPriceListServiceURL,
            data: JSON.stringify(params),
            success: this.OnLoadPeriodPriceListDataSuccess,
            error: function(xhr) {
                //alert("ajax-error during populating the period price list");
            },
            caller: this
        })
    }

    this.OnLoadPeriodPriceListDataSuccess = function(data) {

        ////////////////////////////////////////////////////////////////////////////
        // Fill Pricelist
        //
        //remove the loading text
        //$("#divPeriodePriceList").children().remove();

        var periodPriceList = data.d;

		//since SP3 there is no use for this table anymore
//        var content = "";
//        content += "<div class=\"ui-widget ma10\">";
//        content += "<p><span class=\"ui-icon ui-icon-info left ma0100\"></span>" + periodPriceList.EXText + "</p>";
//        content += "</div>";
//        content += "<table id=\"tblPeriodePriceList\" class=\"list w100\">";
//        content += "<thead>";
//        content += "<tr>";
//        content += "<th class=\"ui-widget-header\">" + periodPriceList.PLH1 + "</th>";
//        content += "<th class=\"ui-widget-header\">" + periodPriceList.PLH2 + "</th>";
//        content += "<th class=\"ui-widget-header\">&nbsp;</th>";
//        content += "</tr>";
//        content += "</thead>";
//        content += "<tbody>";
//        content += "<tr>";
//        content += "<td class=\"ui-state-active\">&nbsp;</td>";
//        content += "<td class=\"ui-state-active\">" + periodPriceList.PLHS1 + "</td>";
//        content += "<td class=\"ui-state-active\">" + periodPriceList.PLHS2 + "</td>";
//        content += "</tr>";
//        for (var i = 0; i < periodPriceList.PriceList.length; i++) {
//            var price = (periodPriceList.PriceList[i].SP != "") ? "<span style='text-decoration: line-through;'>" + periodPriceList.PriceList[i].WP + "</span>&nbsp;<span style='color:red'>" + periodPriceList.PriceList[i].SP + "</span>" : periodPriceList.PriceList[i].WP;
//            var specialCondition = periodPriceList.PriceList[i].tTi;
//            if (specialCondition != "") {
//                specialCondition = "<a href='#' onclick=\"OpenDialog(this, '" + periodPriceList.PriceList[i].tTe + "', '" + periodPriceList.PriceList[i].tTi + "'); return false;\">" + specialCondition + "</a>";
//            }
//            content += "<tr>";
//            content += "<td class=\"ui-widget-content vaMi\">" + periodPriceList.PriceList[i].pT + "</td>";
//            content += "<td class=\"ui-widget-content vaMi\">" + price + "</td>";
//            content += "<td class=\"ui-widget-content vaMi\">" + periodPriceList.PriceList[i].sbText + "</td>";
//            content += "</tr>";
//        }
//        content += "</tbody>";
//        content += "</table>";
//        $("#divPeriodePriceList").append(content);


        ////////////////////////////////////////////////////////////////////////////
        // Fill Offerlist
        //

        //remove the loading text
        $("#divOfferList").children().remove();

        if (periodPriceList.OfferList.length > 0) {
            content = "";
            content += "<table id=\"tblOfferList\" class=\"list w100\">";
            content += "<thead>";
            content += "<tr>";
            content += "<th class=\"ui-widget-header\">" + periodPriceList.PLH1 + "</th>";
            content += "<th class=\"ui-widget-header\">" + periodPriceList.PLH2 + "</th>";
            content += "<th class=\"ui-widget-header\">" + periodPriceList.PLHS3 + "</th>";
            content += "</tr>";
            content += "</thead>";
            content += "<tbody>";
            for (var i = 0; i < periodPriceList.OfferList.length; i++) {
                var price = (periodPriceList.OfferList[i].SP != "") ? "<span style='text-decoration: line-through;'>" + periodPriceList.OfferList[i].WP + "</span>&nbsp;<span style='color:red'>" + periodPriceList.OfferList[i].SP + "</span>" : periodPriceList.OfferList[i].WP;
                var specialCondition = periodPriceList.OfferList[i].tTi;
//                if (specialCondition != "") {
//                    specialCondition = "<a href='#' onclick=\"OpenDialog(this, '" + periodPriceList.OfferList[i].tTe + "', '" + periodPriceList.OfferList[i].tTi + "'); return false;\">" + specialCondition + "</a>";
//                }
                content += "<tr>";
                content += "<td class=\"ui-widget-content vaMi\">" + periodPriceList.OfferList[i].pT + "</td>";
                content += "<td class=\"ui-widget-content vaMi\">" + price + "</td>";
                content += "<td class=\"ui-widget-content vaMi\">" + specialCondition + "</td>";
                content += "</tr>";
            }
            content += "</tbody>";
            content += "</table>";
            $("#divOfferList").append(content);
        }
        
        this.caller.isPeriodePriceListDataLoaded = true;
    }
   
    this.HidePeriodPriceList = function() 
    {
        //$("#divPeriodePriceListBlock").remove();
        $("#divOfferListBlock").remove();
    }
   
    this.HideAllCalenders = function()
    {
        $("#divMonthSlider").hide();
        $("#divDuplexCalendar").hide();
    }
   }
$(document).ready(function() {
   	$('.linkMonthSliderButtonLeft, .linkMonthSliderButtonRight, .linkDuplexCalendarButtonLeft, .linkDuplexCalendarButtonRight').hover(
		function() { $(this).addClass('ui-state-hover'); },
		function() { $(this).removeClass('ui-state-hover'); }
	);
});



