﻿ rangeForm = "closed";
var rangeHeight
var filterHeight
var rangeHeight
var btnArray
var data
var maxCompare = 4;
var totalCompare = 0;
var cboArray
//var currentFormName = "fmFilter";

function pageInit(){
    // Hide the loading bar
    if($('loadBar')){
        $('loadBar').hide();
        $('loadBar').removeClassName('hidden');
    }

    showSort(); // Show the sort drop down
    
    // SUBMIT BUTTONS
    // ------------------------------
    if ($('searchBar')){
        btnArray = $('searchBar').getElementsByTagName("input");
        
        for (var i=0; i < btnArray.length; i++) {
            if (btnArray[i].type == "submit"){
                btnArray[i].onclick = function(){
                var currentForm = this.id
                    currentFormArray = currentForm.split("_")
                    currentFormName = currentFormArray[0]
					
					try{
						pageTracker._trackEvent('Help Me Choose', 'Search', currentFormName)
						pageTrackerExternal._trackEvent('Help Me Choose', 'Search', currentFormName)
					}catch(e){}
                    performSearch();
                    return(false);
                }
            }
        }
    }
    
    // 'Filter the range' and 'Range finder' links
    // ------------------------------
    // Opens and closes the 'filter range/filter' forms
    if ($('fmFilterLink')){
        
        // Work out which search type to show on page load
        if($('filterRange').value=="true"){
            $('fmFilterLink').className = "closedPanel"
            $('fmFinderLink').className = "openedPanel"
            filterAnim('filter');
            currentFormName = "fmFilter";
        }else{
            $('fmFinderLink').className = "closedPanel"
            $('fmFilterLink').className = "openedPanel"
            filterAnim('range');
            currentFormName = "fmFinder";
            
        }

        filterHeight = $('fmFilterLI').offsetHeight;
        rangeHeight = $('fmFinderLI').offsetHeight;
        
        $('fmFilterLink').onclick = function(){
            filterAnim('filter');
            return(false);
        }
        $('fmFinderLink').onclick = function(){
            filterAnim('range');
            return(false);
        }        
    }
    //performSearch();
    setCompareLinks();
}

function setCompareLinks(){
    // Add to Compare Checkboxes
    cboArray = $('searchResults').getElementsByTagName("input");
        for (var i=0; i < cboArray.length; i++) {
            if (cboArray[i].type == "checkbox"){       
                cboArray[i].onclick = function(){
                
                    addCompare(this.id,this.checked);
                }
            }
        }
    // Hide the compare button
    addCompare('','');

    externalLinks(); // Runs the function to watch the buyButton Links
    searchResultsSubmit();
}

function searchResultsSubmit() {
    $('searchResults').onsubmit = function () {
        eventTracking('Compare', 'Vacuums', 'Total: ' + totalCompare + '');
    }
}

// Shows the Compare button if applicable and displays the number of machines in the comparison
// If the total is greater than 4 it cancels the last one off and displays a message
function addCompare(cboID,cboChecked){

    var copyCompare = "Compare"
    var copyMachine = "machine"
    var copyMachinePl = "machines"
    
    // Set Copy Text
    if($('copy_Compare')){
        copyCompare = $('copy_Compare').value;
        copyMachine = $('copy_Machine').value;
        copyMachinePl = $('copy_MachinesPl').value;
    }


    totalCompare = 0
    //var machinePl = "";
    var buttonText = "";
    // get the total number of machines being compared
    for (var i=0; i < cboArray.length; i++) {
        if ($(cboArray[i]).checked){
            totalCompare = parseInt(totalCompare)+1;
        }
    }
    if (totalCompare > maxCompare) {
        try{alert($('maximumComparePre').value + maxCompare + $('maximumComparePost').value);}
        catch(err){alert("You can compare a maximum of "+maxCompare+" products.");}
        
        $(cboID).checked = false;
    }else{
        if(totalCompare>0){
                $('compareBtn').removeClassName("hidden");
            if (totalCompare>1){
                machineText = copyMachinePl
                //machinePl = "s"
                $('compareBtn').disabled = false;
                $('compareBtn').removeClassName("disabled");
            }else{
                machineText = copyMachine
            
                $('compareBtn').disabled = true;
                $('compareBtn').addClassName("disabled");
            }
            
            
            buttonText = copyCompare +" "+totalCompare+" "+machineText
            
            $('compareBtn').value = buttonText
        }else{
            if($('compareBtn')) {
                $('compareBtn').addClassName("hidden");
            }
        }
    
    
    //Show or hide the compare link beneath the checkbox
    //--------------------------------------------------
    
    // Update the text on all buttons
    var submitArray = $('searchResults').getElementsByTagName("input");
        for (var i=0; i < submitArray.length; i++) {
            if (submitArray[i].type == "submit"){ 
                submitArray[i].value = buttonText;
                
                if(totalCompare>0){
                    if (totalCompare>1){
                        submitArray[i].disabled = false;
                        $(submitArray[i]).removeClassName("disabled")
                    }else{
                        submitArray[i].disabled = true;
                        $(submitArray[i]).addClassName("disabled")
                    }
                }
            }
        }
        
        // Show or hide the relevant button
        if(cboID !=""){
            buttonID = cboID.split(":")
            
            if (cboChecked){
                $('compareLink:'+buttonID[1]).removeClassName("hidden")
            }else{
                $('compareLink:'+buttonID[1]).addClassName("hidden")
            }
        }
    
    }
   
}
function filterAnim(activeForm){

    // If the range form is closed - open it and close the filter form
    if (activeForm == "range"){
        $('filterRange').value="false"
        $('fmFinderLink').className = "closedPanel"
        $('fmFilterLink').className = "openedPanel"
  
        new Effect.Morph('fmFilterLI', {
          style: 'height:55px;', // CSS Properties
          duration: 0.3
        });
    
        new Effect.Morph('fmFinderLI', {
          style: 'height:'+rangeHeight+'px;', // CSS Properties
          duration: 0.3
        });
        
        //resetCheckboxes('fmFinder');
       
    }else{
    // Open the Filter form and close the Range form
        $('filterRange').value="true"
        $('fmFilterLink').className = "closedPanel"
        $('fmFinderLink').className = "openedPanel"
        
        new Effect.Morph('fmFilterLI', {
          style: 'height:'+filterHeight+'px;', // CSS Properties
          duration: 0.3
        });
   
        new Effect.Morph('fmFinderLI', {
          style: 'height:55px;', // CSS Properties
          duration: 0.3
        });
        //resetCheckboxes('fmFilter');
        
       
       
    }
}

// Resets all the checkboxes to unchecked
function resetCheckboxes(formID){
    //Get all the checkboxes from the form and set them to unchecked
    var cboList = $(formID).getElementsByTagName("input");

     for (var i=0; i < cboList.length; i++) {
            if (cboList[i].type == "checkbox"){ 
                cboList[i].checked = false;
            }
        }

}


function performSearch(){
   
    // Firstly, reset the checkboxes in the other form
    
    if(currentFormName == "fmFilter"){
        resetCheckboxes('fmFinder');
    }else{
        resetCheckboxes('fmFilter');
    }
    

    data = $(currentFormName).serialize(); // gets all forms data

    new Effect.Appear($('loadBar'), {duration:0.1, from:0.1, to:1}); // Show loading bar
    new Effect.Fade($('searchResults'), {duration:0.1, from:1, to:0.1, afterFinish: loadProducts});
    
}
function loadProducts(){
  dataArray = data.split("&")
  for (var i=0; i < dataArray.length; i++) {
    dataValArray = dataArray[i].split("=")
    
    if(dataValArray[0] != "selSort"){
		try{
			pageTracker._trackEvent('Help Me Choose', 'Filter', dataValArray[1]);
			pageTrackerExternal._trackEvent('Help Me Choose', 'Filter', dataValArray[1]);
		}catch(e){}
    }
  }
  
  
    var searchForm = new Ajax.Updater('searchResults','/ajax/hmc_result.asp',{parameters: data, onSuccess: function(){
        Effect.Appear('searchResults', { duration: 0.2 });
        Effect.Fade('loadBar', { duration: 0.2,afterFinish:showSort});
    }, onComplete: function(){basketSummaryInt(); initLiveChat();}});
}
// Shows the 'Sort By' drop down
function showSort(){
    

   if ($('sortBy')){
        $('sortBy').removeClassName('hidden');
        if ($('selSortSearch')){
        $('selSortDD').value = $('selSortSearch').value;        
        }
        
        $('selSortDD').onchange = function(){
       
            // set hidden search field
            $('selSortSearch').value =  $('selSortDD').value;
            $('selSortRange').value =  $('selSortDD').value;

            // Track GA
          
            eventTracking('Help Me Choose', 'Sort', $('selSortDD').value)
            
            performSearch();
        }
    }
    
    // Reset the compare links
    setCompareLinks();
}
//Event.observe(window,"load",function() { pageInit();});
document.observe("dom:loaded",function() { pageInit();});

