(function(){
    var yuiDom = YAHOO.util.Dom;
    var yuiEvent = YAHOO.util.Event;
    var interestSelector= (function(){
        var self= {
            autoUpdate:false,
            selectorRequestUrl:'',
            propertyRequestUrl:'',
            primaryInterest:'',
            secondaryInterest:'',
            regionInterest:'',
            brandInterest:'',
            filteredResult:null,
            primaryList:[],
            secondaryList:[],
            regionList:[],
            brandList:[],
            actionLink:null,
            relativeUrl:null,
            selectorUpdate:false,
            loader:null,
            loadPanel:null,
            init:function(params){
                self.relativeUrl=params.relativeUrl;
                self.selectorRequestUrl=params.selectorRequestUrl;
                self.propertyRequestUrl=params.propertyRequestUrl;
                self.selectorRequestUrl+='&localeCode='+params.localeCode;
                self.propertyRequestUrl+='&localeCode='+params.localeCode;
                self.loader = yuiDom.get('propertyTilesLoader');
                if (params.selectorUpdate) self.selectorUpdate = params.selectorUpdate;

                var setPosition = location.href.indexOf("#&set");
                if(setPosition>0){
                    self.parseParams(setPosition);
                }else{
                    if (self.selectorUpdate){
                        yuiDom.get('narrowResults').style.display="none";
                        yuiDom.get('noResults').style.display="block";
                        yuiDom.get('resultsMessaging').style.display="block";
                        self.updateTileControl("");
                        SW.local.propertyTile.updateCount(0);
                    }
                }

                var primaryInterest= yuiDom.get('primaryInterest');
                self.selectorSetup(primaryInterest,self.primaryList,"primary",self.primaryInterest);

                var secondaryInterest= yuiDom.get('secondaryInterest');
                self.selectorSetup(secondaryInterest,self.secondaryList,"secondary",self.secondaryInterest);

                var regionInterest= yuiDom.get('regionInterest');
                self.selectorSetup(regionInterest,self.regionList,"region",self.regionInterest);

                var brandsInterest= yuiDom.get('brandsInterest');
                self.selectorSetup(brandsInterest,self.brandList,"brand",self.brandInterest);

                self.actionLink = yuiDom.get("findPerfectResortLink");
                yuiEvent.addListener(self.actionLink,"click",self.submitInterests);

                yuiDom.getElementsByClassName("viewLink","a").forEach(function(link){
                	yuiEvent.addListener(link,"click",self.changeView);
                });
                yuiDom.getElementsByClassName("resetLink","a","primaryHeader").forEach(function(resetLink){
                	yuiEvent.addListener(resetLink,"click",self.resetInterest);
                });
            },
            parseParams:function(setPosition){
                var urlParams = location.href.substring(setPosition);
                var query = urlParams.split("=");
                if(query.length>1){
                    var interestQuery = query[1].split("|");
                     for (var i=0; i<interestQuery.length; i++) {
                         var interestParam = interestQuery[i].split("::");
                         switch(interestParam[0]){
                             case "Category":
                                var categoryParam=interestParam[1].split(",");
                                self.primaryInterest = unescape(categoryParam[0]);
                                if(categoryParam[1]) self.secondaryInterest = unescape(categoryParam[1]);
                                break;
                             case "WebRegion":
                                self.regionInterest=unescape(interestParam[1]);
                                break;
                             case "BrandCode":
                                 self.brandInterest=unescape(interestParam[1]);
                                break;
                         }
                     }
                }
                self.makeRequest();
                if (self.regionInterest !="" || self.brandInterest !=""){
                    yuiDom.addClass('optionalSelectors','selected')
                }
            },
            selectorSetup:function(root,itemsList,type,selectedInterest){
                interestTrigger=yuiDom.getElementsByClassName("dhtmlSelectTrigger","div",root)[0];
                yuiDom.getElementsByClassName("option","li",root).forEach(function(interest){
                     var config={
                        container:interest,
                        value:interest.getAttribute("data"),
                         type:type,
                         trigger:interestTrigger,
                         link:interest.getElementsByTagName("a")[0],
                        select:root
                    }
                    itemsList.push(config);
                    yuiEvent.addListener(interest,"click",self.selectInterest,config);
                    if (selectedInterest!='' && selectedInterest==config.value){
                        interestTrigger.innerHTML = config.link.innerHTML;
                    }
                });
            },
            resetOptions:function(root,itemsList,type,selectedInterest){
                var ajaxUrl = self.selectorRequestUrl+'&set=';
                ajaxUrl = encodeURI(ajaxUrl);
                // Making an Ajax call to populate all the options....
                yuiConnect.asyncRequest("GET",ajaxUrl,{success: self.resetSelectorsResponse, argument:{type:type,itemsList:itemsList}});
                  
            },
            selectInterest:function(e,config){
                yuiEvent.preventDefault(e);
                
                /**
                 *  The below code is for hide the reset container...
                 */
                // Showing the container...
                yuiDom.removeClass('tilesControl',"invisible reset");
                yuiDom.removeClass('propertyTiles',"reset");
                
                // Hiding Reset Message...
                yuiDom.removeClass('resetMessaging',"show");
                
                if (!yuiDom.hasClass(config.container,"active")){
                    return;
                }
                switch(config.type){
                    case "primary":
                        self.primaryInterest = config.value;
                        if (config.value!=''){
                            yuiDom.addClass(self.primaryList[0].container,"active");
                        }else{
                            yuiDom.addClass(self.primaryList[0].container,"active");
                        }
                        break;
                    case "secondary":
                        self.secondaryInterest = config.value;
                        if (config.value!=''){
                            yuiDom.addClass(self.secondaryList[0].container,"active");
                        }else{
                            yuiDom.removeClass(self.secondaryList[0].container,"active");
                        }
                        break;
                    case "region":
                        self.regionInterest = config.value;
                        if (config.value!=''){
                            yuiDom.addClass(self.regionList[0].container,"active");
                            yuiDom.addClass('optionalSelectors','selected')
                        }else{
                            yuiDom.removeClass(self.regionList[0].container,"active");
                            yuiDom.removeClass('optionalSelectors','selected')
                        }
                        break;
                    case "brand":
                        self.brandInterest = config.value;
                        if (config.value!='') {
                            yuiDom.addClass('optionalSelectors','selected')
                            yuiDom.addClass(self.brandList[0].container,"active");
                        }else{
                            yuiDom.removeClass(self.brandList[0].container,"active");
                            yuiDom.removeClass('optionalSelectors','selected')
                        }
                        break;
                }
                config.trigger.innerHTML = config.link.innerHTML;
                yuiDom.removeClass(config.select,"show");
                self.makeRequest(config);
            },
            showLoading:function(){
                if(self.loadPanel == null){
                    yuiDom.setStyle(self.loader,"display","block");
                    var panelContainer = document.createElement("div");
                    panelContainer.id="resultsLoadingPanel";
                    panelContainer.appendChild(self.loader);
                    var loadPanel = new YAHOO.widget.Panel(panelContainer,{
                        draggable:false,
                        close:false,
                        visible:false,
                        modal:true,
                        constraintoviewport:true,
                        fixedcenter: true,
                        zIndex:1030
                    });
                    self.loadPanel = loadPanel;
                    self.loadPanel.showMaskEvent.unsubscribe();
                    self.loadPanel.hideMaskEvent.unsubscribe();
                    self.loadPanel.render(document.body);
                }
                self.loadPanel.show();
            },
            hideLoading:function(){
                self.loadPanel.hide();
            },
            getActiveSelectors:function(type,selectors){
                var ajaxUrl = self.selectorRequestUrl+'&set=';

                 switch(type){
                    case "primary":
                        if(self.regionInterest!='') ajaxUrl+='|WebRegion::'+self.regionInterest;
                        if(self.brandInterest!='') ajaxUrl+='|BrandCode::'+self.brandInterest;
                        if(self.secondaryInterest!='') ajaxUrl+='|Category::'+self.secondaryInterest;
                        break;
                    case "secondary":
                        if(self.regionInterest!='') ajaxUrl+='|WebRegion::'+self.regionInterest;
                        if(self.brandInterest!='') ajaxUrl+='|BrandCode::'+self.brandInterest;
                        if(self.primaryInterest!='') ajaxUrl+='|Category::'+self.primaryInterest;
                        break;
                    case "region":
                        if(self.brandInterest!='') ajaxUrl+='|BrandCode::'+self.brandInterest;
                        if(self.primaryInterest!='') ajaxUrl+='|Category::'+self.primaryInterest;
                        if(self.primaryInterest!='' && self.secondaryInterest!='') ajaxUrl+=','+self.secondaryInterest;
                        break;
                    case "brand":
                        if(self.regionInterest!='') ajaxUrl+='|WebRegion::'+self.regionInterest;
                        if(self.primaryInterest!='') ajaxUrl+='|Category::'+self.primaryInterest;
                        if(self.primaryInterest!='' && self.secondaryInterest!='') ajaxUrl+=','+self.secondaryInterest;
                        break;
                }
                ajaxUrl = encodeURI(ajaxUrl);
                yuiConnect.asyncRequest("GET",ajaxUrl,{success: self.activeSelectorsResponse, argument:{type:type}});
            },
            activeSelectorsResponse:function(xhr){
                self.filteredResult = eval("("+xhr.responseText+")");
                var requestType = xhr.argument.type;
                var availableFilters = self.filteredResult.data.availableFilters;

                if (availableFilters){
                    if (requestType == "primary"){
                        self.updateOptions(self.primaryList,availableFilters.Category,(self.primaryInterest!='' ? true : false));
                    }
                    if (requestType == "secondary"){
                        self.updateOptions(self.secondaryList,availableFilters.Category,(self.secondaryInterest!='' ? true : false));
                    }
                    if (requestType == "region"){
                        self.updateOptions(self.regionList,availableFilters.WebRegion,(self.regionInterest!='' ? true : false));
                    }
                    if (requestType == "brand"){
                        self.updateOptions(self.brandList,availableFilters.BrandCode,(self.brandInterest!='' ? true : false));
                    }
                }
            },
            resetSelectorsResponse:function(xhr){
                self.filteredResult = eval("("+xhr.responseText+")");
                var requestType = xhr.argument.type;
                var requestItems = xhr.argument.itemsList;
                var availableFilters = self.filteredResult.data.availableFilters;
                
                //updateOptions method is called to update the options list and to activate them....
                if (availableFilters){
                	if (requestType == "primary"){
                        self.updateOptions(requestItems,availableFilters.Category,true);
                    }
                    if (requestType == "secondary"){
                        self.updateOptions(requestItems,availableFilters.Category,true);
                    }
                    if (requestType == "region"){
                        self.updateOptions(requestItems,availableFilters.WebRegion,true);
                    }
                    if (requestType == "brand"){
                        self.updateOptions(requestItems,availableFilters.BrandCode,true);
                    }
                }
                
                //Making the first option inactive...
                yuiDom.removeClass(requestItems[0].container,"active");
                
                requestItems[0].trigger.innerHTML = requestItems[0].link.innerHTML;
                //Disabling the second drop down... 
                if(requestType == "secondary") {
                	yuiDom.addClass("secondaryInterest","disabled");
                	self.secondaryInterest="";
                }
            },
            makeRequest:function(config){
                var requestType = (config ? config.type : "init");
                if (self.selectorUpdate){
                    var ajaxUrl = self.propertyRequestUrl+'&set=';
                }else{
                    var ajaxUrl = self.selectorRequestUrl+'&set=';
                }
                ajaxUrl += self.getUrlFilterParam();
                ajaxUrl = encodeURI(ajaxUrl);

                if (self.loader){
                    self.showLoading();
                }
                if(self.selectorUpdate){
                    document.location.hash="&set="+self.getUrlFilterParam();
                }
                if (yuiDom.get('propertyTiles')){
                    SW.local.propertyTile.updateCount(0);
                    SW.local.propertyTile.resetProperties();
                }
                yuiConnect.asyncRequest("GET",ajaxUrl,{success: self.response, argument:{type:requestType}});
            },
            getUrlFilterParam:function(){
                var urlFilterParam="";
                if(self.regionInterest!='') urlFilterParam+='|WebRegion::'+self.regionInterest;
                if(self.brandInterest!='') urlFilterParam+='|BrandCode::'+self.brandInterest;
                if(self.primaryInterest!='') urlFilterParam+='|Category::'+self.primaryInterest;
                if(self.primaryInterest!='' && self.secondaryInterest!='') urlFilterParam+=','+self.secondaryInterest;
                return urlFilterParam;
            },
            response:function(xhr){
                self.filteredResult = eval("("+xhr.responseText+")");
                var requestType = xhr.argument.type;
                var availableFilters = self.filteredResult.data.availableFilters;
                if(self.primaryInterest!=""){
                    yuiDom.removeClass("secondaryInterest","disabled")
                    if (self.actionLink) yuiDom.removeClass(self.actionLink.parentNode,"disabled");
                }else{
                    if (self.actionLink){
                        yuiDom.addClass(self.actionLink.parentNode,"disabled");
                    }
                    yuiDom.addClass("secondaryInterest","disabled");
                    self.secondaryInterest="";
                    self.secondaryList[0].trigger.innerHTML = self.secondaryList[0].link.innerHTML;
                }
                if (availableFilters){
                    if(availableFilters.Category && self.primaryInterest == ""){
                        self.updateOptions(self.primaryList,availableFilters.Category,(self.primaryInterest!='' ? true : false));
                    }else if(requestType !="primary"){
                        self.getActiveSelectors("primary");
                    }
                    if(availableFilters.Category && self.secondaryInterest==""){
                        self.updateOptions(self.secondaryList,availableFilters.Category,(self.secondaryInterest!='' ? true : false));
                    }else if(requestType !="secondary"){
                        self.getActiveSelectors("secondary");
                    }
                    if(availableFilters.WebRegion && self.regionInterest==""){
                        self.updateOptions(self.regionList,availableFilters.WebRegion,(self.regionInterest!='' ? true : false));
                    }else if(requestType !="region"){
                        self.getActiveSelectors("region");
                    }
                    if(availableFilters.BrandCode && self.brandInterest==""){
                        self.updateOptions(self.brandList,availableFilters.BrandCode,(self.brandInterest!='' ? true : false));
                    }else if(requestType !="brand"){
                         self.getActiveSelectors("brand");
                    }
                }
                if(self.filteredResult.data.count>99){
                    yuiDom.get('noResults').style.display="none";
                    yuiDom.get('narrowResults').style.display="block";
                    yuiDom.get('resultsMessaging').style.display="block";
                    self.updateTileControl("");
                }else if(self.filteredResult.data.properties && self.filteredResult.data.count>0){
                    yuiDom.get('resultsMessaging').style.display="none";
                    SW.local.propertyTile.renderFilteredProperties(self.filteredResult.data.properties,self.filteredResult.data.arrivalDate,self.filteredResult.data.departureDate);
                    self.updateTileControl(self.filteredResult.data.propPreFilter);
                }else if(self.filteredResult.data.count == '0'){
                    SW.local.propertyTile.updateCount(self.filteredResult.data.count);
                    yuiDom.get('narrowResults').style.display="none";
                    yuiDom.get('noResults').style.display="block";
                    yuiDom.get('resultsMessaging').style.display="block";
                    self.updateTileControl("");
                }
                if(self.filteredResult.data.properties) {
                    self.trackSelections();
                }
                if(requestType=="init"){
                    if(self.brandInterest!=''){
                        self.defaultOptional(self.brandList,true);
                    }
                    if(self.regionInterest!=''){
                        self.defaultOptional(self.regionList,true);
                    }
                }
                if (self.loader){
                    self.hideLoading();
                }
            },
            updateTileControl:function(filters){
                 if(filters!=''){
                    yuiDom.removeClass('tilesControl',"invisible");
                 }else{
                     yuiDom.addClass('tilesControl',"invisible");
                 }
                if(filters!=''){
                     yuiDom.getElementsByClassName("searchLink","a","tilesControl").forEach(function(link){
                        link.href = SW.tools.Url.setParameter(link.href,"propPreFilter",filters);
                     });
                }
            },
            updateOptions:function(itemList,filterList,showDefaultOption){
                itemList.forEach(function(item){
                    if(filterList[item.value] == undefined){
                        yuiDom.removeClass(item.container,"active")
                    }else{
                        if (!yuiDom.hasClass(item.container,"active")){
                            yuiDom.addClass(item.container,"active")
                        }
                    }
                });

                if (showDefaultOption && !yuiDom.hasClass(itemList[0].container,"active")){
                    yuiDom.addClass(itemList[0].container,"active")
                }
            },
            defaultOptional:function(itemList,showDefaultOption){
                itemList.forEach(function(item){
                    yuiDom.removeClass(item.container,"active")
                });

                if (showDefaultOption && !yuiDom.hasClass(itemList[0].container,"active")){
                    yuiDom.addClass(itemList[0].container,"active")
                }
            },
            submitInterests:function(e){
                yuiEvent.preventDefault(e);
                if(yuiDom.hasClass(self.actionLink.parentNode,"disabled")){
                    return;
                }
//                self.trackSelections(e);     // omniture
                var actionLink = self.actionLink.href;
                actionLink+="#&set="+self.getUrlFilterParam();
                location.href=actionLink;
            },
            changeView:function(e){
                yuiEvent.preventDefault(e);
                var actionLink = this.href;
                actionLink+="#&set="+self.getUrlFilterParam();
                location.href=actionLink;
            },
            resetInterest: function(e){
            	yuiEvent.preventDefault(e);
            	var actionLink = this.href;
            	actionLink+="#&set=";
                location.href=actionLink;
                
                // resetSetup Method is called for activating the options...
                var primaryInterest= yuiDom.get('primaryInterest');
                self.resetOptions(primaryInterest,self.primaryList,"primary",self.primaryInterest);

                var secondaryInterest= yuiDom.get('secondaryInterest');
                self.resetOptions(secondaryInterest,self.secondaryList,"secondary",self.secondaryInterest);

                var regionInterest= yuiDom.get('regionInterest');
                self.resetOptions(regionInterest,self.regionList,"region",self.regionInterest);

                var brandsInterest= yuiDom.get('brandsInterest');
                self.resetOptions(brandsInterest,self.brandList,"brand",self.brandInterest);
                
                // Hiding the container...
                yuiDom.addClass('tilesControl',"invisible reset");
                yuiDom.addClass('propertyTiles',"reset");
                
                // Showing Reset Message...
                yuiDom.addClass('resetMessaging',"show");
            },
            trackSelections:function(){
                // omniture tracking
                if (typeof s != 'undefined' && self.propertyRequestUrl.lastIndexOf("resortsPropertyFilter.do") >= 0) {
                    var prefix = "Resorts";

                    if (location.href.lastIndexOf("explore/find.html") >= 0) {
                        prefix = "ResortsExplore";
                    }

                    var str = prefix;

                    if (self.primaryInterest) {
                        str += "," + self.primaryInterest;
                    }
                    if (self.secondaryInterest) {
                        str += "," + self.secondaryInterest;
                    }
                    if (self.regionInterest) {
                        str += "," + self.regionInterest;
                    }
                    if (self.brandInterest) {
                        str += "," + self.brandInterest;
                    }

                    s.linkTrackVars = "prop51,eVar51";
                    s.prop51 = s.eVar51 = str;
                    s.t();
                }
            }
        }
        return self;
    })();

    YAHOO.namespace("SW.local.interestSelector");
    SW.local.interestSelector = interestSelector;
})();



