// this is 

if ((typeof Prototype == 'undefined') ||
    (typeof Element == 'undefined') ||
    (typeof Element.Methods == 'undefined') ||
    parseFloat(Prototype.Version.split(".")[0] + "." +
               Prototype.Version.split(".")[1]) < 1.6) {
    throw("Review Selector requires the Prototype JavaScript framework >= 1.6.0")
}

function openPopUp(winURL, winName, scrollBar, resizable, winWidth, winHeight) {
    var winOptions = 'menubar=no,toolbar=no,location=no,directories=no,status=no,scrollbars=' + scrollBar + ',resizable=' + resizable + ',width=' + winWidth + ',height=' + winHeight;
    window.open(winURL, winName, winOptions);
}
/*requires prototype */
var reviewSelector = Class.create();
    reviewSelector.prototype = {
    getValue:"",
    makeFieldSelected:true,
    yrFieldSelected:false,
    defualtTxtMsg:"",
    defualtInnerstercialMsg:"",
    linkSelectFlag:false,
    formSubmitErrFlag:false,

    isVideo:false,
    isWriteReview:false,
    reviewsBtn:null,

     initialize:function(){
         $('make-selector').observe('change',this.selectController.bind(this));
         $('model-selector').observe('change',this.selectController.bind(this));
         $('year-selector').observe('change',this.buttonController.bind(this));
         this.reviewsBtn =document.getElementsByClassName('inactive')[0];
         this.reviewsBtn.observe('click',this.getCarModelLink.bind(this));
         $('model-selector').disable();
         $('year-selector').disable();
         $('make-selector').selectedIndex=0;

         this.defualtTxtMsg = $('make-selector').options[0].text;
         this.defualtInnerstercialMsg =$F('loading-inner-value');
         this.isVideo = $F('review-selector-selection').indexOf('video') != -1;
         this.isWriteReview = $F('review-selector-selection').indexOf('write') != -1;
         // This is the one that's pre-loaded, so make it the one that's selected.
         $('review-selector-selection').value = 'consumerreview';
         $('consumerReviewRadio').checked="checked";
         $('consumerReviewRadioLabel').style.fontWeight = 'bold';
         $('expertReviewRadioLabel').style.fontWeight = '';
         $('writeReviewRadioLabel').style.fontWeight = '';
         $('videoReviewRadioLabel').style.fontWeight = '';
     },
     reset:function(){
         
        
         $('model-selector').disable();
         $('year-selector').disable();
         $('make-selector').selectedIndex=0;

         this.isVideo = $F('review-selector-selection').indexOf('video') != -1;
         this.isWriteReview = $F('review-selector-selection').indexOf('write') != -1;
         //this.initialize();
         this.getValue="mak";
         this.makeReset = true;

         this.turnOnLoadingInnerstercial($('make-selector'));
         this.resetSelect($('make-selector'));
         this.doRequest();

         //this.turnOffLoadingInnerstercial($('make-selector'));
         this.resetSelect($('model-selector'));
         this.resetSelect( $('year-selector'));
     
     },

   selectController:function(evt){
     var ele = evt.target; // evt.findElement(evt,'select'); this would work in IE 7

             if(this.formSubmitErrFlag)this.resetErrorMsg();

         this.getValue =  $('list-return-value').value=(ele.id.startsWith('make'))?'mod':'yr';
          this.makeFieldSelected = (this.getValue.startsWith('mod'));
          this.linkSelectFlag =false;
       //populate make
          if((this.makeFieldSelected)&&(ele.selectedIndex>0)){
           this.turnOnLoadingInnerstercial($('model-selector'));
           this.resetSelect($('year-selector'));
           this.doRequest();

          }


       //populate yr
     else if(ele.selectedIndex>0){
           this.turnOnLoadingInnerstercial($('year-selector'));
           $('year-selector').enable();
            this.doRequest();

     }

       if((ele.selectedIndex==0)&&(!this.makeFieldSelected))
           this.resetSelect($('year-selector'));

       if((ele.selectedIndex==0)&&(this.makeFieldSelected))
       {   this.resetSelect($('model-selector'));
           this.resetSelect( $('year-selector'));

       }
     this.buttonController();

   },

   getCarModelLink:function(){
       if(this.selectReady())
       {
        this.getValue = $('list-return-value').value='link';
        this.linkSelectFlag=true;
        this.doRequest();
       } else {
           this.showRedError();
           this.formSubmitErrFlag=true;
       }
   },

    showRedError:function(){
        if ($('make-selector').selectedIndex == 0){
            $('make-selector-label').style.color='red';
        } else {
            $('make-selector-label').style.color='black';
        }
        if ($('model-selector').selectedIndex == 0){
            $('model-selector-label').style.color='red';
        } else {
            $('model-selector-label').style.color='black';
        }
        if ($('year-selector').selectedIndex == 0){
            $('year-selector-label').style.color='red';
        }  else {
            $('year-selector-label').style.color='black';
        }
        document.getElementById('review-form-error-msg').style.display='block';

   },


   resetErrorMsg:function(){
     this.formSubmitErrFlag=false;

     $('make-selector-label').style.color='black';
     $('model-selector-label').style.color='black';
     $('year-selector-label').style.color='black';
     $('review-form-error-msg').hide();
   },
        
   turnOnLoadingInnerstercial:function(ele){
      ele.options[0].text= this.defualtInnerstercialMsg;
   },

    turnOffLoadingInnerstercial:function(ele){
      ele.options[0].text= this.defualtTxtMsg;
   },


   doRequest:function(){
       var url = '/ac-servlets/reviewContentSearch?'+$('review-selector-form').serialize();
           var ajax = new Ajax.Request(url, {onSuccess: this.updateController.bindAsEventListener(this),
           onFailure:this.showError.bindAsEventListener(this)}, { method:'get', evalJSON:true, sanitizeJSON:true });
 },


   updateController:function(resp){
     var arr = new Array();

       if(this.linkSelectFlag) {
           /* for some of the links, it displays a popup window, and
           the background/parent window is advanced to research. */
           if (this.isWriteReview){
                openPopUp(resp.responseJSON.actionLink[0].action,'Review','yes','yes','750','650');
           }

            if((this.isVideo)||(this.isWriteReview)) {
                document.location = resp.responseJSON.actionLink[1].action + '&rdpage=HPTABRVW';
            } else {
                document.location = resp.responseJSON.actionLink[0].action + '&rdpage=HPTABRVW';
            }
           
       } else{
           if(this.makeReset){
               resp.responseJSON.makeList.each(function(make){arr.push(make.make);})
               this.populateSelect('make-selector', arr.sort());
               this.makeReset = false;
           } else if(this.makeFieldSelected){
               resp.responseJSON.modelList.each(function(model){arr.push(model.model);})
               this.populateSelect('model-selector',arr.sort());
           } else{
               resp.responseJSON.modelYearList.each(function(modelYear){arr.push(modelYear.modelYear);})
               this.populateSelect('year-selector',arr.sort());
           }
       }//end linkSelectflg else

        this.buttonController();
   },


   resetSelect:function(ele){
       ele.disable();
       ele.selectedIndex =0;
   },

  populateSelect:function(ele,list){
      if($(ele).tagName.startsWith("SELECT")){
        $(ele).enable();
        this.turnOffLoadingInnerstercial($(ele));
      /* clear all the elements, except the 1st*/
       $(ele).childElements().each(function(ele){if(ele.index!=0)ele.remove();})
       //add elements
      list.each(function(e){
          var opt = document.createElement('option');             
              opt.text=opt.value=e;
           $(ele).options.add(opt);
        });
      }
  },

  buttonController:function(){
     if(this.formSubmitErrFlag)this.resetErrorMsg();
     if(this.selectReady())
     this.showButton();
      else
     this.hideButton();
  },


 selectReady:function(){
   return ($('make-selector').selectedIndex>0&&$('model-selector').selectedIndex>0&&$('year-selector').selectedIndex>0);
 },

  hideButton:function(){
      this.reviewsBtn.removeClassName("active");
      this.reviewsBtn.addClassName("inactive");
  },
  showButton:function(){
     this.reviewsBtn.removeClassName("inactive");
     this.reviewsBtn.addClassName("active");
  },

  showError:function(){$('review-select-ajax-error').setStyle({display:'block'});}

} /* end of reviewSelector prototype*/

var revSelector;

function changeReviewType(el){
    $('review-selector-selection').value = $(el).value;
    $('make-selector').selectedIndex = 0;
    $('list-return-value').value = 'mak';
    revSelector.reset();
    styleToggle(el);
}
function styleToggle(b){
   var blength= b.form.length;
   for (var i = 0; i< blength; i++)
     {     
         if (b.form[i].name == b.name)
         {
          if(b.form[i].parentNode!=null){
             b.form[i].parentNode.style.fontWeight = b.form[i].checked? 'bold' : '';
           }
        }
    }
 }

//Call moved into init function within homepage-b-script.js
//Event.observe(window, 'load', function(){revSelector = new reviewSelector();});
