

// [AA (a.avenwedde@mobizcorp.de)] Pls. refer to 'product-filters.js' for any additional calls also.
// Didn't moved the calls because may be referenced somewhere else at 
// those place.



//[AA] Encapsulated into function to be called _not_ onload automatically
// (Providing more better event flow).

jQuery(document).ready(function(){
   
   completeProductFilters(); 
    
});



function completeProductFilters() {
  
     
    var $ = jQuery;
    
    //tabify
     $('#product-filter-tabs').tabs();
    
	 // dynamic values:
	 var pmin = Math.floor($('#price-min').val());
	 var pmax = Math.ceil($('#price-max').val());
     
    // question: 0 is obviously the absolute minimum, but what is the absolute maximum? 600?
    //var sliderInitialValues = [$('#price-min').val(), $('#price-max').val()];
	 var sliderInitialValues = [pmin, pmax];
    
   
    
    // or static values (may be better):
    //pmin = 0;
	//pmax = 600;
    
    
    
    $("#slider-range").slider({
        animate: true,
        range: true,
        min: pmin,
        max: pmax,
        values: sliderInitialValues,
        slide: function(event, ui) {
            $('#slider-range .ui-slider-handle span').each(function(i){
                $(this).html('$'+ui.values[i]);
            });
        },
        stop: function(event, ui){
            var rangeValues = [];
            $('#slider-range .ui-slider-handle span').each(function(i){
                rangeValues[i] = this.innerHTML.substring(1); //substring starting at 1 to leave off the dollarsign
            });
            //var url = '?minPrice='+rangeValues[0]+'&maxPrice='+rangeValues[1]
            var url = $('#priceRefine').attr('rel');
            
            
            setPriceMin(rangeValues[0]);
            setPriceMax(rangeValues[1]);
            url = getRefineUrl();
            rf.filterResults(url);
        }
    });
    
    // we want to show the dollar amounts under the slider thumbs/handles, we'll do this via the appended spans:
    $('#slider-range .ui-slider-handle').each(function(i){
        $(this).append('<span>$'+sliderInitialValues[i]+'</span>');
    });
            
    // slider replaces need for labels and inputs. [kinda]
    $('#price-min,#price-max,label[for=price-min],label[for=price-max]').remove();
    
    $('#product-filters .school-list').jScrollPane({showArrows:true, scrollbarWidth: 21, scrollbarMargin: 0, arrowSize: 19});
    $('#product-filters .school-list li').click(function(){
        
        
        var relax = false;

        // [AA] Using id's instead of jQuery DOM traversing features is much more
        // flexible, because:

        // - doesn't loose references with dynamic updates,
        // - independency of xml / html stucture.
        
        var school = $(this).attr("id").split("-")[1];
        var schoolurl = $(this).attr("team");
        
        
        //remove previous selection if there is one
        if(selectedSchools.length>0){
        	addRefinementSchool(selectedSchools[0],true);
        	$('#product-filters .school-list li').removeClass('selected');
    	}
        
        //apply selected style
        $(this).addClass('selected');
        addRefinementSchool(schoolurl,relax);
        // get client-based refinement url:
        url = getRefineUrl();
        rf.filterResults(url);
        return false;
    });
    
    $('.product-filters-head a').click(function(){
        /**
         * reset the filters.
         */
         
         var pmin = Math.floor($('#pmin').val());
         var pmax = Math.ceil($('#pmax').val());
        // reset the size and color and school selections
        $('#product-filters label').removeClass('selected');
        $('#product-filters .school-list li').removeClass('selected');
        
        // reset the range slider
        $("#slider-range").slider('values',0, pmin);
        $("#slider-range").slider('values',1, pmax);
        //$("#slider-range").slider('values',pmin, pmax);
        var ui = {values:[pmin,pmax]};
        $('#slider-range .ui-slider-handle span').each(function(i){
            $(this).html('$'+ui.values[i]);
        });
        var url = $(this).attr('href');
        // Reset the js-based refinement model:
        resetFilters();
        rf.filterResults(url);
        
        return false;
    })
    
   

}


/* NOT USED WITHIN COLUMBIA YET */



/**********  NEW (crocs footwear,columbia sportswear..) *************/

/* New settings for to be more flexible with product refinements definitions. */

/** [AA] New, lean settings, using ajaxhref.js, to replace most parts above.
    and to be more flexible for future use.
    
    Advantages:
    No overhead with developer-confusing client-server roundtrips*, no additional server-logic for
    ajax-requesets required, no doubling of template code (.isml/.js).
    
    Drawbacks:
    With dynamic update of html code, all dynamically added object references
    (i.e. attached events) are lost. 
    
    Instead of re-appling events and to relay onto the dom-structure, assign unique ids to 
    the elements. This is even more versatile for general use.
    
    (*) are more encapsulated into libraries.
 */

// TODO: Encapsulate into own namespace, if needed.

// Define special callbacks for refinement-updates here:
	   // Supported params (hooks) onstart|onend
	   // to define more hooks, modify ajaxhref.js

	 // Globally used collapsed refinments store (workaround, should be supported by server itself).
	 // [AA] UPDATE 04/2009: Also done by server templates now.
	 
       var  activeSizeTab = "regular";

	   // The global AJAXHREF_EXCHANGE_HASH (ajaxhref.js) can be used to exchange objects.
	   function refine(param , isCachedRequest ) {
	     
	     var myurl = AJAXHREF_EXCHANGE_HASH['url'];
	     var append = "";
	     
	     // Append this GET request by the collapsed refinement groups:
	     
	     
	     if (myurl) {
		     
		     append = "&selectedSizeTab=" + activeSizeTab;
		     myurl = myurl + append;
		     // Pass-back this modified url of this callback:
		     AJAXHREF_EXCHANGE_HASH['url'] = myurl;
		 }
	     

	     //alert('refine callback called.');


	     var fadeSpeed = "normal";
	     
	     // With cached requests, too much fading produces overhead/delays, so shorten up:
	     if (isCachedRequest) {
	       if (isCachedRequest == "yes") {
	         
	         fadeSpeed = "fast";
	       }
	     }
	     
	     if (param == "onstart") {
	       // Give user a visual hint, that something is done behind the scenes:
	       document.body.style.cursor = "wait";
	       // NEW: Skip fadeOut with fast transitions (i.e. if cached).
	       if (fadeSpeed != "fast") {
	         jQuery("#results-col").fadeOut(fadeSpeed);
	       }
	     }
	     if (param == "onend") {
  			
  		   // at product-filters, re-apply some settings again:
  		   completeProductFilters('update');
	       
	       jQuery("#results-col").fadeIn(fadeSpeed);
	       // Switch back wait cursor:
	       document.body.style.cursor="default";
	       	
	     }
	   }
	   
	   
	   
	   /* Toggle a refinement group and store its state at cliens side.
	     for later use without to relay on jQuery.
	    */
	   /* elem:current dom element (object)*/
	   
	   function refineTab(elem) {
	     
	     
	     var id = elem.id;
         
         if (id == "filter-regular-link") {
           //alert("Set Regular");
           activeSizeTab = "regular";
           document.getElementById("product-filter-tabs-1").style.display="block";
           document.getElementById("product-filter-tabs-2").style.display="none";
         }
         else if (id=="filter-big-link") {
            //alert("Set big");
            activeSizeTab = "big";
            document.getElementById("product-filter-tabs-1").style.display="none";
            document.getElementById("product-filter-tabs-2").style.display="block";
         }
         return false;
         
	    

	   }
	   
	   var selectedColors = [];
	   var selectedSizes = [];
	   var selectedDimensions = [];	   
   	   var selectedSchools = [];
	   var selectedPriceMin = null;
	   var selectedPriceMax = null;

	   
	   var refineBaseUrl = null;
	   
	   // TODO (check): is this needed, don't think so
	   function refineUrlInit() {
		  
		    
		  refineBaseUrl = window.location.href;
		  
	   }
	   
	   /*
	   [AA]
	    For ajax requests, save the states of the selected refinement values
	    at client. Could/should be done more generally.
	    This part is implemented for the current requirements of columbia.
	    
	   */
	   
	   
	   function addRefinementColor(color,relax) {
	     
	     if (relax) {
	       var newAr = [];
	       for (var i=0;i<selectedColors.length;i++) {
	         if (selectedColors[i] != color) {
	           newAr[newAr.length] = selectedColors[i];
	         }
	       }
	       selectedColors = newAr;
	     }
	     else {
	       selectedColors[selectedColors.length] = color;
	     }
	     
	   }
	
		function addRefinementSize(size,relax) {
	     if (relax) {
	        var newAr = [];
	        for (var i=0;i<selectedSizes.length;i++) {
	         if (selectedSizes[i] != size) {
	           newAr[newAr.length] = selectedSizes[i];
	         }
	       }
	       selectedSizes = newAr;
	     }
	     else {
 		     selectedSizes[selectedSizes.length] = size;
 		 }
	     
	   }

		function addRefinementDimensions(size,relax) 
		{		
		     if (relax) {
		        var newAr = [];
		        for (var i=0;i<selectedDimensions.length;i++) {
		         if (selectedDimensions[i] != size) {
		           newAr[newAr.length] = selectedDimensions[i];
		         }
		       }
		        selectedDimensions = newAr;
		     }
		     else {
		    	 selectedDimensions[selectedDimensions.length] = size;
	 		 }	     
	   }		
		
	   // 'school' / ('team') refinement value:
	   function addRefinementSchool(school,relax) {
	     if (relax) {
	        var newAr = [];
	        for (var i=0;i<selectedSchools.length;i++) {
	         if (selectedSchools[i] != school) {
	           newAr[newAr.length] = selectedSchools[i];
	         }
	       }
	       selectedSchools = newAr;
	     }
	     else {
 		     selectedSchools[selectedSchools.length] = school;
 		 }
	     
	   }
	   
	   function setPriceMin(p) {
	      selectedPriceMin = p;
	   }
	   
	   function setPriceMax(p) {
	     selectedPriceMax = p;
	   }
	   
	   // Reset all (javascript-state-based) filter values:
	   function resetFilters() {
	      
	      setPriceMin(null);
	      setPriceMax(null);
	      selectedSizes = [];
	      selectedDimensions = [];
	      selectedColors = [];
	      selectedSchools = [];
	   }
	   
	   
	   // [AA] Columbia project based. 
	   // Assembles the refine URL for ajax-based updates of the category grid.
	   // This is a workaround to by-passing the default server based URLs for refinements.
	   // 'relax / refine'
	   
	   
	   
	   
	   function getRefineUrl() {
	     
	     // get the refinement base Url:
	     var url = refineBaseUrl;
	     
	     if(!url.match(/\?/)) url = url + '?';
	     
	     // append parameters manually here:
	     var append = "";
	     
	     // This is a workaround/pass-by the demandware refinement handling:
	     // This part has to be extended for future use of other refinements, if needed.
	     
	     var count = 1;
	     
	     if (selectedSizes.length > 0) 
	     {
	    	 append += (append==''?'':'&')+"prefn"+count+"=variationSize&prefv"+count+"=" + selectedSizes.join("|");
	    	 count++;
	     }
	     
	     if (selectedDimensions.length > 0) 
	     {
	    	 append += (append==''?'':'&')+"prefn"+count+"=variationDimension&prefv"+count+"=" + selectedDimensions.join("|");	    	 
	    	 count++;
		 }
	     
	     if (selectedColors.length > 0) 
	     {
	    	 append += (append==''?'':'&')+"prefn"+count+"=filterColor&prefv"+count+"=" + selectedColors.join("|");
	    	 count++;
	     }
	     
	     if (selectedSchools.length > 0) {
	       append += (append==''?'':'&')+"prefn"+count+"=team&prefv"+count+"=" + selectedSchools.join("|");
	     }
	     
	     if (selectedPriceMin) {
	        append += (append==''?'':'&')+"pmin="+Math.floor(selectedPriceMin);	        
	     }
	     
	     if (selectedPriceMax) {
	        //append += (append==''?'':'&')+"pmax="+selectedPriceMax;
	        append += (append==''?'':'&')+"pmax="+Math.ceil(selectedPriceMax);
	     }
	     
	     url = url + "&" + append;
	     
	     // To debug this url statically:
	     //window.open(url);
	     return url;
	     
	    
	   }
	   
	   // [AA] Set the initial search-url to keep flexibility:
	   refineUrlInit();

