/*
 * This class is used to initialiaze and send ajax request to the search filter action
 * @author Garima Parakh
 * 
 */

// ************************************************************************************************
/**
create the wth.cruise.dynamicfilter object which encloses all functions related to dynamic search
**/
wth.cruise.dynamicfilter= function () {
return  {	
	/** Called when the page loads the first time. It initializes the form with the pre-selected values 
	    and then calls the submitAjaxForm function 
	**/
  onPageLoad: function(){	
   		/**
          set events on the waiting and loading divs
          **/                    
		$('#searchfilter_waiting')
		.hide();  // hide it initially
		
		$("select[dynamicfilter='true']")
			.ajaxStart(function() {
			$(this).prop('disabled',true);
			})
		   .ajaxStop(function() {
		    $(this).prop('disabled',false);
			});
		
		$('#searchfilter_count_top').hide();		
		$('#searchfilter_count_bottom')	.hide() ;
	    $('#searchfilter_update').hide();     
		
		//get the query string
		var fullURL = parent.document.URL;
		if(fullURL.indexOf('?')==-1){
			var qStr=null;
		}else{		
			var qStr = fullURL.substring(fullURL.indexOf('?')+1, fullURL.length);
		}
  
        //only used for IE7
        var prevVal = null;
  	 	/**
		bind the onchange event with the process function to all selects that have dynamicfilter as true
		**/
        //store the previous value , only used for IE7
        	if ( $.browser.msie ) {
			if($.browser.version =='7.0'){
    	
				$("select[dynamicfilter='true']").focus(function(event){
					prevVal = $(this).val();
				});
			}
        	}
			$("select[dynamicfilter='true']").change(function(event){
	
			if ( $.browser.msie ) {
			if($.browser.version =='7.0'){
    		
	    		if(this.options[this.selectedIndex].disabled) {	 
	    			 $(this).val(prevVal);
			    }
		    
		  	}}
		 
			wth.cruise.dynamicfilter.getJSONContent(event.currentTarget, null,this);
			  
			}
		);
		wth.cruise.dynamicfilter.getJSONContent(null,qStr);
		
	
   	},	
// ************************************************************************************************
 /**
   	make the ajax server call 
 **/
 getJSONContent: function(changedTarget, formData, changedElement){
		 
   /**
   If the formData is not already initialized from the initialize function (form submit from previous page)
   then, it means that it is an onchange event, so we need to get the form data using the serialize.
   This is only needed onchange and not on init of the page
   
   Pass the changedDdl as part of the formdata as well
   This is used to change behaviour of the drop downs based on the 
   element changed the last time ie.e changedTarget.id
   This is only needed onchange and not on init of the page
   **/
    	
   	var changedTargetId ;        
  	if(!formData){
   		if(changedTarget) {
   			changedTargetId = changedTarget.id  ;
   	
   		}
		
   		formData = $('#AdvancedForm').serialize()+"&changedDdl="+changedTargetId;

    } 
  
		    
/**
Now make the actual server call
**/    
     $.ajax({
         url: "/ajaxjson/filterdynamic.do",
         contentType: "application/json; charset=utf-8",
         dataType: "json",
         data: formData,
         success: function(result){
         wth.cruise.dynamicfilter.processresult(result);
         },
         error: function(request, textStatus){
         wth.cruise.dynamicfilter.processerror(request, textStatus);
         }
        })
},   
// ************************************************************************************************
/**
   	make the ajax server call 
 **/
 getDynamicHtmlContent: function(changedTarget, formData){
		 
   /**
   If the formData is not already initialized from the initialize function (form submit from previous page)
   then, it means that it is an onchange event, so we need to get the form data using the serialize.
   This is only needed onchange and not on init of the page
   
   Pass the changedDdl as part of the formdata as well
   This is used to change behaviour of the drop downs based on the 
   element changed the last time ie.e changedTarget.id
   This is only needed onchange and not on init of the page
   **/
   			 
   	var changedTargetId ;        
  	if(!formData){
   		if(changedTarget)  	changedTargetId = changedTarget.id  ; 
   		formData = $('#AdvancedForm').serialize()+"&changedDdl="+changedTargetId;
    } 
		    
/**
Now make the actual server call
**/    
     $.ajax({
         url: "/ajaxhtml/filterdynamic.do",
         contentType: "application/html; charset=utf-8",
         dataType: "html",		               
         data: formData,
         success: function(result){
         $("#ajaxfilter").html(result);
     
         },
         error: function(request, textStatus){
    		handleErrorPage();
         }
        })
}, 
handleErrorPage: function(){
	
},
// ************************************************************************************************
/**
   	make the ajax server call 
 **/
 getStaticHtmlContent: function(changedTarget, formData){
		 
   /**
   If the formData is not already initialized from the initialize function (form submit from previous page)
   then, it means that it is an onchange event, so we need to get the form data using the serialize.
   This is only needed onchange and not on init of the page
   
   Pass the changedDdl as part of the formdata as well
   This is used to change behaviour of the drop downs based on the 
   element changed the last time ie.e changedTarget.id
   This is only needed onchange and not on init of the page
   **/
   			 
   	var changedTargetId ;        
  	if(!formData){
   		if(changedTarget)  	changedTargetId = changedTarget.id  ; 
   		formData = $('#AdvancedForm').serialize()+"&changedDdl="+changedTargetId;
    } 
		   
/**
Now make the actual server call
**/    
     $.ajax({
         url: "/ajaxhtml/filterstatic.do",
         contentType: "application/html; charset=utf-8",
         dataType: "html",		               
         data: formData,
         success: function(result){          	
         $("#ajaxfilter").html(result);   
         },
         error: function(request, textStatus){
 	   		handleErrorPage();
         }
        })
}, 
// ************************************************************************************************
   /**
   act on the resulting json data coming back. We need to disable the drop downs based on the result
   **/
  processresult:function(result){			                                             
                  try{
                  	wth.cruise.dynamicfilter.bindSelectHtml(result.cruiselines,"#c");   
                  	wth.cruise.dynamicfilter.bindSelectHtml(result.vessels,"#v");                  
                  	wth.cruise.dynamicfilter.bindSelectHtml(result.locations,"#places");
                   	wth.cruise.dynamicfilter.bindSelectHtml(result.lengths,"#days");
                  	wth.cruise.dynamicfilter.bindSelectHtml(result.ports,"#port");
                  	wth.cruise.dynamicfilter.bindSelectHtml(result.months,"#DepartureMonth");
                  	if($("#DepartureMonth").val()!='ALL'){
                  	wth.cruise.dynamicfilter.bindSelectHtml(result.daysofmonth,"#DepartureDay");
                  	}
                  	
                  	if($("#DepartureDay").val()!='ALL'){                  	
                  		wth.cruise.dynamicfilter.bindSelectHtml(result.flexibledays,"#FlexibleDays");
                  		$("#FlexSpace1").show();
                  		$("#FlexSpace2").show();
                  		$("#FlexLabel").show();
                  		$("#FlexSelect").show();
                  	}else{                  
                  		$("#FlexSpace1").hide();
                  		$("#FlexSpace2").hide();
                  		$("#FlexLabel").hide();
                  		$("#FlexSelect").hide();
                  	}
					/**
					 * on page load, the changedDdl will be null, we hide the count and prepopulate departure days
					 */
                    if(!result.changedDdl || result.changedDdl=='null'|| result.changedDdl=='undefined' ){    
                  
                    	$("#searchfilter_count_top").hide();
                    	$("#searchfilter_count_bottom").hide();
                    	$("#searchfilter_update").hide(); 
                    	 prepopuplateDepartureDaysDropdown();
                    }else{
                    	$("#searchfilter_count").html(result.count);  
                    	if(result.count==0){
                   
                    		CallTracker('SearchResults/DynamicRefine', 'ZeroResults', searchCriteria);
                    	}
                    	if(result.count==1){
                    
                    		$("#searchfilter_count_text").html("Cruise Matches<br />Your Selections");
                    	}else{
                   
                    		$("#searchfilter_count_text").html("Cruises Match<br />Your Selections");
                    	}
                      	$("#searchfilter_count_top").show();
                      	$("#searchfilter_count_bottom").html($("#searchfilter_count_top").html());  
                      	$("#searchfilter_count_bottom").show();  
                      	$("#searchfilter_update").show();     
                      	var searchImageSrc = $("input[name='Search']").attr("src");        
                      	var newSearchImageSrc = searchImageSrc.replace("Off","");
                      	$("input[name='Search']").attr("src",newSearchImageSrc);
                    }
                    wth.cruise.dynamicfilter.disableOptionsForIE7();
                  }catch(error){
	               		$("select[dynamicfilter='true']").attr('disabled',false);
                  }
     
  },
disableOptionsForIE7: function(){
	/**
	 * disable options for IE 7
	 */
if ( $.browser.msie ) {
	if($.browser.version =='7.0'){
		$('option[disabled]').css({'color': '#cccccc'});
	}}              
},
  // ************************************************************************************************
/**
for each value in the select box with name ddlname, create the option string using the bindOptionValue function
**/
bindSelectHtml: function (jsonList, ddlname){  		         
         var ddllistArr = [];                              
	    $.each(jsonList, function(index,val) {            	 
						ddllistArr[index]= wth.cruise.dynamicfilter.bindOptionValue(this);		
					}
		);	
		/**
		use join to create the whole list and then use innerhtml to add it to the actual select box
		**/			
		$(ddlname).html(ddllistArr.join(""));	
}, 
/**
creates the option string based on the json element
**/
bindOptionValue: function(jsonElem){
	 	var optionStr='';
		optionStr= optionStr+'<option value="';
		optionStr= optionStr+jsonElem['key']+'"';
		if(jsonElem['disabled'] && jsonElem['selected']){
			optionStr= optionStr+' selected='+jsonElem['selected'];
		}
		else {
			if(jsonElem['disabled']){
				optionStr= optionStr+' disabled='+jsonElem['disabled'];
			}			
			if(jsonElem['selected']){
				optionStr= optionStr+' selected='+jsonElem['selected'];
			}		
		}
		optionStr= optionStr+'>' +  jsonElem['value'] + '</option>';	
		return optionStr;
   },
  
   // ************************************************************************************************
  	
/**
 TODO: we need to work on the error handling                  
should we redirect the original page to an error page, if no drop-downs appear
**/
 processerror: function(request, textStatus) {
                  	if(request.status=='404'){                  	
                  	}       
                  	$("select[dynamicfilter='true']").attr('disabled',false);
                   //alert(request.responseText);
                   // alert(request.statusText);                 
  },
  //************************************************************************************************
/**
 * Depending on the ABVariation = static/dynamic value, it will load static vs dynamic page
 */
  runABTest: function (ABVariation){
//get the query string
		var fullURL = parent.document.URL;
		var qStr = fullURL.substring(fullURL.indexOf('?')+1, fullURL.length); 
		//based on the AB test cookie or parameter, get static or dynamic content		
	if(ABVariation=='dynamic'){         
       		wth.cruise.dynamicfilter.getDynamicHtmlContent(null,qStr);
        }else{       
        	wth.cruise.dynamicfilter.getStaticHtmlContent(null,qStr);
        }
		
			//wth.cruise.dynamicfilter.getDynamicHtmlContent(null,qStr);
         
},

runABTest2: function (ABVariation){
//get the query string
		
		//based on the AB test cookie or parameter, get static or dynamic content		
	if(ABVariation=="dynamic"){         
       		writeABSidebarDynamic();
        }else{       
        	writeABSidebarStatic();
        }
		
			//wth.cruise.dynamicfilter.getDynamicHtmlContent(null,qStr);
         
},
  // ************************************************************************************************

   	/**
   	reset all drop downs
   	**/
 reset: function (){
  	$("select[dynamicfilter='true']").val("ALL");
  	wth.cruise.dynamicfilter.process();
 	}
}
}(); 
 
 


