//### BEGIN CALENDAR ### //
(function(){
    var SuperClass = SW.widget.Calendar.AvailabilityCalendar.prototype,
        Calendar = SW.widget.Calendar.Calendar,
        CalUtils = SW.widget.Calendar.Utils,
        Url = SW.tools.Url,
        Html = SW.tools.Html,
        yuiDom = YAHOO.util.Dom,
        yuiEvent = YAHOO.util.Event,
        yuiLang = YAHOO.lang,
        customEvent = YAHOO.util.CustomEvent,
        Content = SW.widget.Calendar.Content;

    function MultiRateCalendar(settings){
        this.rateCollection = settings.rateCollection;
        // set initial search params
        settings.ratePref = this.rateCollection[0].ratePref;
        settings.ratePrefValue = this.rateCollection[0].ratePrefValue;
        settings.currencyCode = this.rateCollection[0].currencyCode;
        this.rateNotificationArray = [];
        SuperClass.constructor.call(this, settings);
    }
    YAHOO.lang.extend(MultiRateCalendar,SW.widget.Calendar.AvailabilityCalendar,{
        _TYPE:"MultiRateCalendar",
        _CONTAINER_CLASS:"multiRateCalendar",
        initialize:function(){
            SuperClass.initialize.call(this);

            if(this.settings.maxLOSExceeded){
                this.notificationArray[this.notificationArray.length] = this.content.get("ERROR_LOS_EXCEEDED");
            }
        },

        initEvents:function(){
            SuperClass.initEvents.call(this);
            this.beforeApplyAllEvent = new customEvent("beforeApplyAllEvent",null,false,customEvent.FLAT);
            this.applyAllEvent = new customEvent("applyAllEvent",null,false,customEvent.FLAT);
        },

        initHandlers:function(){
            SuperClass.initHandlers.call(this);
            this.submitEvent.subscribe(this._continue,this,true);
            this.applyAllEvent.subscribe(this.applyDatesToAllHotels,this,true);
        },
        toggleHandler:function(e){
            if(this.isShowing()){
                this.hide();
            }
            else{
            	this.show();
            }
            if(e){
                yuiEvent.preventDefault(e);
            }
        },

        _continue:function(){
            var url = this.fetchRateListAction() || this.settings._baseHref;
            var selectedStay = this.getStayObject();

            //set standard date params
            url = Url.setParameter(url,"arrivalDate",CalUtils.dateToSystemFormat(this.rangeStartDate));
            url = Url.setParameter(url,"departureDate",CalUtils.dateToSystemFormat(this.rangeEndDate));
            url = Url.setParameter(url,"lengthOfStay",CalUtils.getLengthOfStay(this.rangeStartDate,this.rangeEndDate));

            //set lpq rate params if not award booking
            if (!selectedStay.pts) {
                url = Url.setParameter(url,"lpqRatePlanName",selectedStay.rp);
                url = Url.setParameter(url,"lpqRate",selectedStay.rate);
            }
            document.location.href = url;
        },

        _applyDates:function(){
            if(this.beforeApplyAllEvent.fire()){
                this.applyAllEvent.fire();
            }
        },

        parseDataError:function(){
            this.render();
            this.parseError();
        },

        fetchRateListAction:function(){
            var ratePlanKey = this.getRatePlanKey();
            var matchKey;
            for(var i=0; i<this.rateCollection.length; i++){
                matchKey = this.rateCollection[i].ratePref + '_' + this.rateCollection[i].ratePrefValue;
                if(matchKey == ratePlanKey){
                    return this.rateCollection[i].rateListUrl;
                }
            }
        },

        createHeader:function(container) {
            // create close button

            this.renderCloseButton(container);

            this.heading = document.createElement("h3");
            this.heading.innerHTML = this.content.get('MULTIRATE_CALENDAR_HEADER') + ' ' + this.settings.titleText;
            container.appendChild(this.heading);

            this.createLegend(container);
       },

        createLegend:function(container){
            var legend = document.createElement("div");
            yuiDom.addClass(legend, "legendContainer");
            container.appendChild(legend);

            var ratePlanContainer = document.createElement("ul");
            var ratePlanKey = this.getRatePlanKey();
            var ratePlanElement, textNode, radioItem, radioLabel, matchKey;
            for(var i=0; i<this.rateCollection.length; i++){
                matchKey = this.rateCollection[i].ratePref + '_' + this.rateCollection[i].ratePrefValue;
                ratePlanElement = document.createElement("li");

                try{
                    radioItem = document.createElement('<input type="radio" name="' + this.settings.propertyId + '_plan' +'" />');
                }catch(err){
                    radioItem = document.createElement('input');
                    radioItem.setAttribute('type','radio');
                    radioItem.setAttribute("name", this.settings.propertyId + "_plan");
                }
                radioItem.setAttribute("id", matchKey);
                if(matchKey == ratePlanKey){
                    radioItem.setAttribute("defaultChecked", "true");
                    radioItem.setAttribute("checked", "checked");
                }
                yuiEvent.addListener(radioItem, "click", this.selectNewRate, {ratePref:this.rateCollection[i].ratePref, ratePrefValue:this.rateCollection[i].ratePrefValue}, this);
                ratePlanElement.appendChild(radioItem);

                radioLabel = document.createElement("label");
                radioLabel.setAttribute("for", matchKey);
                textNode = document.createTextNode(this.rateCollection[i].ratePrefLabel);
                radioLabel.appendChild(textNode);
                ratePlanElement.appendChild(radioLabel);

                ratePlanContainer.appendChild(ratePlanElement);
            }
            legend.appendChild(ratePlanContainer);
        },

        renderFooter:function(){
            var resetLink;
            if(this.rangeStartDate) {
                this._menuElements.rangeStartInstructions.innerHTML = this.getCheckInCopy();
                resetLink = document.createElement("a");
                resetLink.innerHTML = this.content.get("RANGE_START_RESET");
                resetLink.href = "#";
                yuiEvent.addListener(resetLink, "click", this.handleReset, this, true);
                this._menuElements.rangeStartInstructions.appendChild(resetLink);

                yuiDom.addClass(this._menuElements.rangeEndInstructions, "active");
                yuiDom.addClass(this._menuElements.rangeStartInstructions, "selected");
            } else {
                this._menuElements.rangeStartInstructions.innerHTML = this.content.get("RANGE_START_INSTRUCTIONS");
                yuiDom.addClass(this._menuElements.rangeStartInstructions, "active");
                yuiDom.removeClass(this._menuElements.rangeStartInstructions, "selected");
            }
            if(this.rangeEndDate) {
                this._menuElements.rangeEndInstructions.innerHTML = this.getCheckOutCopy();
                resetLink = document.createElement("a");
                resetLink.innerHTML = this.content.get("RANGE_END_RESET");
                resetLink.href = "#";
                yuiEvent.addListener(resetLink, "click", this.handleResetRangeEnd, this, true);
                this._menuElements.rangeEndInstructions.appendChild(resetLink);

                yuiDom.addClass(this._menuElements.rangeEndInstructions, "selected");
            } else{
                this._menuElements.rangeEndInstructions.innerHTML = this.content.get("RANGE_END_INSTRUCTIONS");
                yuiDom.removeClass(this._menuElements.rangeEndInstructions, "selected");
            }
            if(this.rangeStartDate && this.rangeEndDate) {
                this._menuElements.submitInstructions.innerHTML = this.getSummaryMessage();
                this._menuElements.continueButton.innerHTML = this.content.get("SUBMIT");
                this._menuElements.continueButtonContainer.appendChild(this._menuElements.continueButton);
                yuiDom.addClass(this._menuElements.submitInstructions, "active");   // apply active class to check out div
                this._menuElements.submitInstructions.appendChild(this._menuElements.continueButtonContainer);

                this._menuElements.optionalInstructionsContainer.innerHTML = "";
                this._applyDatesToAllLink = this.createApplyAllLink();
                this._menuElements.optionalInstructionsContainer.appendChild(this._applyDatesToAllLink);
            } else{
                yuiDom.removeClass(this._menuElements.submitInstructions, "active");   // apply active class to check out div
                if(this._menuElements.continueButtonContainer.parentNode == this._menuElements.submitInstructions) {
                    this._menuElements.submitInstructions.removeChild(this._menuElements.continueButtonContainer);
                }
                if(this._applyDatesToAllLink && this._applyDatesToAllLink.parentNode == this._menuElements.optionalInstructionsContainer) {
                    this._menuElements.optionalInstructionsContainer.removeChild(this._applyDatesToAllLink);
                }
                if(!this.rangeStartDate && !this.rangeEndDate) {
                    yuiDom.addClass(this._menuElements.rangeStartInstructions, "active");   // apply active class to check out div
                    yuiDom.removeClass(this._menuElements.rangeEndInstructions, "active");
                }
            }
        },

        getCheckInCopy:function(){
            return this.content.get("RANGE_START_PREFIX") + "<span>" + this.getLocaleFormattedDate(this.rangeStartDate) + "</span>";
        },

        getCheckOutCopy:function(){
            return this.content.get("RANGE_END_PREFIX") + "<span>" + this.getLocaleFormattedDate(this.rangeEndDate) + "</span>";
        },

        createApplyAllLink:function(){
            var applyAllLink = document.createElement("a");
            yuiDom.addClass(applyAllLink, "applyAllDates");
            applyAllLink.innerHTML = this.content.get("APPLY_DATES_TO_ALL");
            applyAllLink.href = "javascript:void(0);";
            yuiEvent.addListener(applyAllLink, "click", this._applyDates, this, true);
            return applyAllLink;
        },

        applyDatesToAllHotels:function(){
            var url = document.location.href;

            if (Url.getParameter(url, "arrivalDate") != null) {
                url = Url.setParameter(url,"arrivalDate",CalUtils.getLocalizedDate(this.rangeStartDate));
                url = Url.setParameter(url,"departureDate",CalUtils.getLocalizedDate(this.rangeEndDate));
            } else {
                url = Url.setParameter(url,"ciDate",CalUtils.getLocalizedDate(this.rangeStartDate));
                url = Url.setParameter(url,"coDate",CalUtils.getLocalizedDate(this.rangeEndDate));
            }

            document.location.href = url;
        },

        selectNewRate:function(e, data){
            this.reset();
            this.setRatePlanKey(data.ratePref, data.ratePrefValue);
            this.verifyRateMessages();
            this.getData();
        },

        verifyRateMessages:function(){
            this.rateNotificationArray = [];
            var ratePlanKey = this.getRatePlanKey();
            var matchKey;

            if(this.notification) {
                this.rateNotificationArray.push(this.notification);
            }
            for(var i=0; i<this.rateCollection.length; i++){
                matchKey = this.rateCollection[i].ratePref + '_' + this.rateCollection[i].ratePrefValue;
                if(matchKey == ratePlanKey){
                    if(this.rateCollection[i].isFreeNightAward && this.rateCollection[i].noFreeNightMessage){
                        this.rateNotificationArray.push(this.rateCollection[i].noFreeNightMessage);
                        break;
                    }
                }
            }
        },

        renderErrors:function(){
            //notifications are similar to errors except they persist and aren't cleared
            var output = []
            if(this.notificationArray.length > 0){
                for(var i=0; i<this.notificationArray.length; i++){
                    output.push('<li>' + this.notificationArray[i] +'</li>');
                }
            }
            if(this.rateNotificationArray.length > 0){
                for(var i=0; i<this.rateNotificationArray.length; i++){
                    output.push('<li>' + this.rateNotificationArray[i] +'</li>');
                }
            }
            if(this.errorArray.length > 0){
                for(var j=0; j<this.errorArray.length; j++){
                    output.push('<li>' + this.errorArray[j] +'</li>');
                }
            }
            if(output.length > 0){
                this._menuElements.errorContainer.innerHTML = output.join("\n");
                yuiDom.addClass(this._menuElements.errorContainer, "show");
            }else{
                yuiDom.removeClass(this._menuElements.errorContainer, "show");
                this._menuElements.errorContainer.innerHTML = "";
            }
            this.errorArray = [];
        },

        animateIn:function(){
            if(this.settings._mapLink && this.settings._mapLink.config){
                mapPanel.hide(this.settings._mapLink.config);
            }
            if(this.settings._animConfig.showOnCompleteFn != null){
                this.settings._animConfig.showOnCompleteFn.call(this);
            }
            SuperClass.animateIn.call(this);
        },
        animateOut:function(){
            if(this.settings._animConfig.hideOnCompleteFn != null){
                this.settings._animConfig.hideOnCompleteFn.call(this);
            }
            SuperClass.animateOut.call(this);
        }
    });

    SW.widget.Calendar.MultiRateCalendar = MultiRateCalendar;
})();
