/*

  File: searchPane.js
  Author: Rob MacGregor
  Date: December 2009
  Description: This file defines and calls (or binds to event handlers) a set of 
  functions for adding interactive functionality to the megashopbot searchPane (the 
  interactive bit in the middle of the page). The file is statically
  linked to index3.php 
  
// Function 1: destroyCategory
// Removes all html from the searchCriteria and botList form. This function is called as part of the chain that is
// called when a user selects a new category

// Function 2: getCategory

// Takes one optional parameter, the value of a category  option. If passed, sets the category selectlist to that value
// of the param, otherwise sets it to the value of the global var default cat. Then loops through the searchCriteria JSON 
// data object (defined in searchPane3.php). When it finds the category (with in the data object) with an id that matches 
// the value of cat, the data held in that category child-object is then used to build the searchForm for the selelcted 
// category

 */ 

// ####################################################### Register global vars & constants##################################################//

// sets the default option (value) of the category select list

// if var deepLink (array of deeplink parameters) is defined (see body.php), use the value of the val property
// of the first element in the deepLink array (the first element being the category value). If deepLink var undefined
// then set defaultCategory to 1 

var defaultCategory= (typeof(deepLink)!= "undefined") ? deepLink[0].val :1;

// set the value of the currwently selected category. Initially this is set to the default category, but is updated 
// whenever the user changes category

var selectedCat=defaultCategory;


// ####################################################### Function Definitions##################################################//


// Function 1: destroyCategory
// Removes all html from the searchCriteria and botList form. This function is called as part of the chain that is
// called when a user selects a new category


var destroyCategory=function()
{

  $('searchCriteria').erase('html');
  
  $('botList').erase('html');  
 
};


// Function 2: getCategory

// Takes one optional parameter, the value of a category  option. If passed, sets the category selectlist to that value
// of the param, otherwise sets it to the value of the global var default cat. Then loops through the searchCriteria JSON 
// data object (defined in searchPane3.php). When it finds the category (with in the data object) with an id that matches 
// the value of cat, the data held in that category child-object is then used to build the searchForm for the selelcted 
// category


var getCategory=function(cat)
{


  if((typeof(cat)=="undefined"))
  {
  
    cat= window.defaultCategory;
  
   var opt = $('categories').getElements('option');
   
   $each(opt, function(o){
   
    if(o.get('value')==cat)
    {
      o.set('selected',"selected");
    }
   
   });
  }

 


      var container = $('searchCriteria');
      

      $each(searchCriteria,function(category)
      {

        
        if(category.id==cat)
        {
 
         
              $('categoryImage').getElement('img').set({'src': IMAGES+category.image,
                                                        'alt': category.Category
                                                        
                                                      });
        

 
        
          $each(category.searchFields, function(searchField)
          {
            var labelContainer = new Element('div',
                                    {
                                      'id':searchField.name+'LabContainer',
                                      'class':'labContainer'
                                    }).inject(container);     
            
            var label = new Element('label',
                                    {
                                      'for':searchField.name,
                                      'html':searchField.label
                                    }).inject(labelContainer); 
                                    
            var inputContainer = new Element('div',
                                    {
                                      'id':searchField.name+'InpContainer',
                                      'class':'inpContainer'
                                    }).inject(container);


          switch(searchField.type)
          {
            case "text":
            
                          var input = new Element('input',
                                        {
                                          'type':'text',
                                          'name':searchField.name,  
                                          'id':searchField.name                                      
                                        }).inject(inputContainer);
            break;
          
            case "select":
             
                        var optionElements = [];
                         
                        var select = new Element('select',
                                                  {
                                                    'id':searchField.name,
                                                    'name':searchField.name
                                                  }).inject(inputContainer); 
                                        
                        var opts = searchField.option;
                        
                        
              
                        $each(opts, function(opt)
                        {
                        
                          var optionElement = new Element('option',
                                                          {
                                                            'value':opt.value,
                                                            'html':opt.text
                                                          }).inject(select);
                        });
          break;
          }
         
          var clearDiv = new Element('div',
                                    {
                                      'class':'clearFloat'
                                    }).inject(container);                                   

        });
        
        var botList = $('botList');

      var innerContainerLeft = new Element('div', 
                                      {
                                        'id': 'innerContainerLeft',
                                        'class': 'innerContainerLeft'
                                                                              
                                      }).inject(botList);
            
      var innerContainerRight = new Element('div', 
                                      {
                                        'id': 'innerContainerRight',
                                        'class': 'innerContainerRight'
                                                                              
                                      }).inject(botList);
                                      
                                new Element('div',{
                                                    'styles':{
                                                      'clear':'both'
                                                    }
                                                  }).inject(botList);
  
        var topBotCount=0;
  
  
        var i=0;   

        $each(category.shopbots, function(shopbot){
      
        if(shopbot.top==1) 
        {
        topBotCount++;
        }
        var l = (category.shopbots.length%2==0)?category.shopbots.length/2:(category.shopbots.length+1)/2;
        

        var cont = ( i<l ) ? innerContainerLeft:innerContainerRight;

            var checkBotContainer = new Element('div',
                                                {
                                                  'class': 'checkBotContainer'
                                                
                                                }).inject(cont);
          
          // this global var is used as a reference to the element of the deepLink array that contains the shopbot deeplink.
          // it is used by results.js
          
          window.sbDLIndex=category.searchFields.length+1;
          
          var checked = "";

          if(typeof(deepLink)!="undefined" && typeof(deepLink[window.sbDLIndex])!="undefined") 
          {
              if(deepLink[window.sbDLIndex].val==shopbot.id)
              {
                checked = "checked";
              }
          }
          
          if(shopbot.top==1)
          {
            checked = "checked";
          }
          
            var checkBotElement = new Element('input',
                                              {
                                                'type':'checkbox',
                                                'id':shopbot.sbName,
                                                'name':shopbot.sbName,
                                                'value':shopbot.sbName,
                                                'checked': checked
                                               }).inject(checkBotContainer);
            
            var checkBotLabel = new Element('label',
                                              {
                                             //   'for': shopbot.sbName

                                               }).inject(checkBotContainer);
            
            var shopBotName = (shopbot.affil==1)?shopbot.sbName+"*":shopbot.sbName; 
            
            var botLabelLink="";
            
            if(shopbot.image)
            {
            botLabelLink = new Element('a',
                                              {
                                                'href': shopbot.url
                                               }).inject(checkBotLabel);
                                               
              var botLinkImage = new Element('img',{
                                                    'src': IMAGES+'logos/'+ shopbot.image,
                                                    'alt': shopbot.shopbot
                                                    }).inject(botLabelLink);
                                                    
              if(shopbot.affil==1)
              {
                                  new Element('span',
                                                    {
                                                      'html':' *'
                                                    }).inject(botLabelLink);
              
              }                
            
            }else{
            
                                                           
            botLabelLink = new Element('a',
                                              {
                                                'href': shopbot.url,
                                                'html': shopbot.shopbot
                                               }).inject(checkBotLabel);
            }
     i++;
          });
       $('topBotListText').set('html', "Tick shopbots to search<br />(our top "+topBotCount+" are auto-selected)")  ;        
        }
     

                      
    });
  
};

var getCompare =function(e){

  if(e)
  {
    e.stop();
  }

  var el = document.shopbotSearch.elements;
  var tag;
  var id;
  var type;
  var val;
  var qs=[];

  window.jsAnalyticsCategory="";

  window.jsAnalyticsSearchText="";

  
  var formValCriteria = false;

  var formValBots = false;

  for(i=0;i<el.length;i++)
  {

    x=qs.length;
  
    tag = el[i].get('tag');

    id = el[i].get('id');
      
    if(tag=='select')
    {

      if(el[i].getSelected().get('value')!=0)
      {

        formValCriteria = (id!='categories')?true:false;        
      
        qs[x]={
        
          "name" : el[i].get('name'),
          "value" :  el[i].getSelected().get('value')
        
        };
             
        if(el[i].get('id')=="categories")
        {
          window.jsAnalyticsCategory+= (window.jsAnalyticsCategory.length==0)? el[i].getSelected().get('text') : "::::" + el[i].getSelected().get('text') ;
        }
        else
        {
          window.jsAnalyticsSearchText+= (window.jsAnalyticsSearchText.length==0)? el[i].getSelected().get('text') : "::::" + el[i].getSelected().get('text')  ;
        }
    
      
      }
  
    }
    else if(tag=='input')
    {
    
      type = el[i].get('type');
    
      if(type=='text')
      {

        if(el[i].get('value')>""){
        
      
          formValCriteria = true;
  
          qs[x]={
            "name" : el[i].get('name'),
            "value" :  new mse_Url(el[i].get('value')).encode()
          
          };

        }
        
        if(el[i].getParents('div[id=searchCriteria]').get('id'))
        {
          window.jsAnalyticsSearchText += (window.jsAnalyticsSearchText==0)? el[i].get('value') : "::::" + el[i].get('value')  ;
        }

      }
      else if(type=='checkbox')
      {
        if(el[i].get('checked'))
        {
        
          formValBots= true;
        
            qs[x]={
              "name" : el[i].get('name'),
              "value" :  el[i].get('value')
            };
        

        
        }
      }  
    }
  
  }

  if(!formValCriteria)
  {
    
    alert("Enter something to search for");
    
    return false;
  
  }else if(!formValBots)
  {
  
    alert("Select a shopbot to search");
    
    return false;
  
  }else{
    var querystring = "";  
    
    for(i=0;i<qs.length;i++)
    {
      querystring += qs[i].name;
      querystring += "=";
      querystring += qs[i].value;
    
      if(i<(qs.length-1))
      {
        querystring += "&";        
      }
    
    }
  
  
  var req = new Request({
  
    method: 'get',
    
    url: APPROOT+'results',
    
        evalScripts: true,  
    
    onComplete: function(response){

     // Asset.javascript(JS+'mootools-core.js', {id: 'mootoolscore', type: 'text/javascript'});
      
     // Asset.javascript(JS+'mootools-more.js', {id: 'mootoolsmore', type: 'text/javascript'});

      $('results').innerHTML = response;

    },
    
    onSuccess: function(){
      
      Asset.javascript(JS+'results.js', {id: 'tabs', type: 'text/javascript'});    

    }


  
  }).send(querystring);
 
 }
  

  
};



var selectToggle=function()
{
  var curText = $('selectToggle').get('html');
 
  var bots = $('botList').getElements('input[type=checkbox]');
  
  if(curText=="Select All")
  {
  
    $each(bots, function(bot){
    
      bot.set('checked', 'checked');
    
    });

  $('selectToggle').set('html','Select None');

  }else{
  
    $each(bots, function(bot){
    
      bot.erase('checked');
    
    });

  $('selectToggle').set('html','Select All');
      
  }

}; 



  var dissolveCategory = function()
  {
    new Fx.Reveal($('dissolveBlock'),{duration:500, mode: 'vertical', display: 'block'}).dissolve();
  };
  
  var revealCategory = function()
  {
    new Fx.Reveal($('dissolveBlock')).reveal();
  };


var switchPane = function()
{

  changeChain = new Chain();  
   
  changeChain.chain(dissolveCategory);
  changeChain.chain(destroyCategory);

  
  changeChain.chain(function(){
      getCategory($('categories').options[$('categories').selectedIndex].value);
  });
  
  changeChain.chain(revealCategory);
   
  changeChain.callChain();
  changeChain.callChain.delay(800,changeChain);
  changeChain.callChain.delay(800,changeChain);
  changeChain.callChain.delay(800,changeChain);  
  
//  if($('categories').options[$('categories').selectedIndex].value.substring(0,3) != 888 ||
//     $('categories').options[$('categories').selectedIndex].value.substring(0,3) != 999)
//  {

    selectedCat=$('categories').options[$('categories').selectedIndex].value;
 //   }
}  ;

var getDeepLinkSearchCriteria = function(){

  if(typeof(deepLink)!= "undefined"){

    var isSearch=0;

    $each(deepLink, function(param){

      if((typeof(param)!="undefined") && ((param.key!="cat") && (param.key!="shopbot") ))
      {
      
        $(param.key).set('value',param.val);
      
        isSearch=1;
      
      }
    
    });
    
    if(isSearch==1)
    {
      getCompare();
    }
  }

};


window.addEvent('domready', function(){

  getCategory();
  
  getDeepLinkSearchCriteria();
  
  $('categories').addEvent('change', function(){
      //    alert(selectedCategory);

          if(this.options[this.selectedIndex].value.substring(0,3)==999 || this.options[this.selectedIndex].value.substring(0,3)==888)
          {
                      window.open(APPROOT+'redirect?cat='+this.getSelected().get('value'));
          
            $('categories').set('value',defaultCategory);
          
             window.switchPane();
          
          }else{
  
  
      switchPane();
      }
  });
  
  
  $('selectToggle').addEvent('click', selectToggle);

  $('shopbotSearch').addEvent('submit', getCompare);



});
