/*
 * based on http://demos111.mootools.net/Ajax.Form
 * and other demos there
 */

var JoomSearchModule = new Class({
  options: {
      moduleid: 0,
      noresultstxt: 'No results'
  },

  initoptions: function(){
    if (this.jsupcatorimg != null)
    {
      this.jsupcatorimg.fireEvent('change');
    }
  },

  initialize: function(options){
    this.setOptions(options);
    $(document.body).adopt(new Element("div", {id: 'js_searchresults' + this.options.moduleid}));    

    // form
    this.jsform = $('js_searchform'+this.options.moduleid);

    //search input field of form
    this.jssearchinput = $('js_searchinput'+this.options.moduleid);

    //search results window
    this.jssearchresults = $('js_searchresults'+this.options.moduleid);

    //make the results window dragable
    this.resultsdragmove=new Drag.Move(this.jssearchresults);

    //save the background style of search input field to restore it later
    this.jssearchinputCSS = this.jssearchinput.getStyle('background');
    //for IE
    if (typeof this.jssearchinputCSS =='undefined')
    {
      this.jssearchinputCSS=null;
    }

    // user panel options, first check if exists
    //limit
    if($chk($('js_limit'+this.options.moduleid)))
    {
      this.jslimit = $('js_limit'+this.options.moduleid);
      this.jslimit.addEvent('blur', function(e)
      {
        //store modified cookie
        this.setcookie();
      }.bind(this));
    }
    else
    {
      this.jslimit = null;
    }

    // search mode
    if($chk($('js_catorimg'+this.options.moduleid)))
    {
      this.jsupcatorimg = $('js_catorimg'+this.options.moduleid);
    }
    else
    {
      this.jsupcatorimg = null;
    }

    // image description
    if($chk($('js_imgdescr'+this.options.moduleid)))
    {
      this.js_imgdescr=$('js_imgdescr'+this.options.moduleid);
      this.jsimgdescrSlide = new Fx.Slide('js_imgdescr'+this.options.moduleid);
      this.js_imgdescr.addEvent('change', function(e)
      {
        //store modified cookie
        this.setcookie();
      }.bind(this));
    }
    else
    {
      this.jsimgdescrSlide = null;
    }

    // comments
    if($chk($('js_comments'+this.options.moduleid)))
    {
      this.js_comments=$('js_comments'+this.options.moduleid);
      this.jscommentsSlide = new Fx.Slide('js_comments'+this.options.moduleid);
      this.js_comments.addEvent('change', function(e)
      {
        //store modified cookie
        this.setcookie(options.moduleid);
      }.bind(this));
    }
    else
    {
      this.jscommentsSlide = null;
    }

    // search authors
    if($chk($('js_authors'+this.options.moduleid)))
    {
      this.js_authors=$('js_authors'+this.options.moduleid);
      this.jsauthorsSlide = new Fx.Slide('js_authors'+this.options.moduleid);
      this.js_authors.addEvent('change', function(e)
      {
        //store modified cookie
        this.setcookie();
      }.bind(this));
    }
    else
    {
      this.jsauthorsSlide = null;
    }

    // search cat description
    if($chk($('js_catdescr'+this.options.moduleid)))
    {
      this.js_catdescr=$('js_catdescr'+this.options.moduleid);
      this.jscatdescrSlide = new Fx.Slide('js_catdescr'+this.options.moduleid);
      this.js_catdescr.addEvent('change', function(e)
      {
        //store modified cookie
        this.setcookie();
      }.bind(this));
    }
    else
    {
      this.jscatdescrSlide = null;
    }

    //initial position of results window
    this.jsformtop=document.body.parentNode.scrollTop+20;
    this.jsformleft=parseInt((document.body.offsetWidth/2)-(this.jssearchresults.offsetWidth/2),10);
    this.jsresultsfirstpos=true;

    // no results html
    // TODO individual tag instead of h3
    this.jsnoresultshtml = '<h3 id="js_noresults">'+this.options.noresultstxt+'</h3>';

    // initially hide the results windows
    this.jssearchresults.setStyles({
      'visibility' : 'hidden'
    });

    // *** Effects ***
    //fade in/out for results window
    this.resultsfx = new Fx.Styles(this.jssearchresults, {
      duration: 500,
      wait: false,
      transition: Fx.Transitions.Quad.easeOut
    });
    //scroll to top in result window
    this.resultsscroll = new Fx.Scroll(this.jssearchresults);
    // *** end Effects ***

    // *** Events ***
    //resize of browser window
    window.addEvent('resize',function(e)
    {
      if (this.jsresultsfirstpos)
      {
        this.jssearchresults.setStyles( {
          'left' : this.jsformleft+'px',
          'top' : this.jsformtop+'px'
        });
        this.jsresultsfirstpos=false;
      }
    }.bind(this));

    this.jssearchinput.addEvent('keydown',this.sendsearch.bind(this));

    //show/hide options in user panel dependent on search mode
    //only if activated
    if (this.jsupcatorimg != null)
    {
      this.jsupcatorimg.addEvent('change', function(e)
      {
        if (this.jsupcatorimg.value == 0)
        {
          // category search
          if (this.jsimgdescrSlide != null) this.jsimgdescrSlide.slideOut();
          if (this.jscommentsSlide != null) this.jscommentsSlide.slideOut();
          if (this.jsauthorsSlide != null) this.jsauthorsSlide.slideOut();
          if (this.jscatdescrSlide != null) this.jscatdescrSlide.slideIn();
        }
        else
        {
          // image search
          if (this.jsimgdescrSlide != null) this.jsimgdescrSlide.slideIn();
          if (this.jscommentsSlide != null) this.jscommentsSlide.slideIn();
          if (this.jsauthorsSlide != null) this.jsauthorsSlide.slideIn();
          if (this.jscatdescrSlide != null) this.jscatdescrSlide.slideOut();
        }
        //store all values in cookie
        this.setcookie();
      }.bind(this));

    }
    //clicking in browser window fades out the results window if visible
    //document for IE
    document.addEvent('click', function(e)
    {
      if (this.jssearchresults.getStyles('visibility').visibility != 'hidden')
      {
        this.resultsfx.start({
          'opacity': [1,0]
        });
        //scroll results to the top
        this.resultsscroll.toTop();
      }
    }.bind(this));

    //scroll at srollbars, avoid dragging
    this.jssearchresults.addEvent('scroll', function(e)
    {
      //avoid dragging when clicked on scrollbar
      this.resultsdragmove.stop();
    }.bind(this));

    //click on results window doesn't fades it out except when clicking on links
    this.jssearchresults.addEvent('click', function(e)
    {
      //get the target element, different in IE
      var targettag=(e.target) ? $(e.target,'tag').nodeName : e.srcElement.nodeName;
      if (this.jssearchresults.getStyles('visibility').visibility != 'hidden' &&
          (targettag=='A' || targettag=='IMG'))
      {
        this.resultsfx.start({
          'opacity': [1,0]
        });
        //scroll results to the top
        this.resultsscroll.toTop();
      }
      else
      {
        new Event(e).stop();
      }
    }.bind(this));
    //submitting the form
    this.jsform.addEvent('submit',this.sendsearch.bind(this));
  },
  sendsearch: function(e){
    //key pressed not enter, return
    if (e.type=='keydown' && $chk(e.keyCode) && e.keyCode!=13)
    {
      return;
    }

    //prevent the submit event
    new Event(e).stop();

    //prevents a search with empty input
    if(this.jssearchinput.value.length == 0) return;

    // activate the spinner.gif of input field
    // save the image setting from css
    this.jssearchinput.setStyles({
        'background-image' : 'url(modules/mod_joomsearch/assets/spinner.gif)',
        'background-repeat' : 'no-repeat',
        'background-position' : 'right'
    });

    // send takes care of encoding and returns the Ajax instance.
    this.jsform.send({
      update : this.jssearchresults,
      onComplete : function()
      {
        //initial position of results window
        if (this.jsresultsfirstpos==true)
        {
          this.jssearchresults.setStyles( {
            'left' : this.jsformleft+'px',
            'top' : this.jsformtop+'px'
          });
          this.jsresultsfirstpos=false;
        }
        // get results from the delivered html
        var resultsfound=false;
        this.jssearchresults.getChildren().each(function(div)
        {
          if (div.getProperty('class').indexOf("contentpaneopen") >=0 
              || div.id.indexOf("page") >=0
              || div.getProperty('class').indexOf("column") >=0)
          {
            // check beez or ja purity 2 template
            if (div.id.indexOf("page") >= 0 || div.getProperty('class').indexOf("column") >=0)
            {
              var result = div.getElement('.results');
              if (result != null)
              {
                this.jssearchresults.innerHTML = result.innerHTML;
                resultsfound=true;
              }
            }
            else
            {
              // check for fieldset, otherwise no results
              if (this.jssearchresults.getElement('fieldset') != null)
              {
                this.jssearchresults.innerHTML = div.innerHTML;
                resultsfound=true;
              }
            }
          }
        }.bind(this));
        //no results found
        if (resultsfound == false)
        {
          this.jssearchresults.innerHTML = this.jsnoresultshtml;
        }
        //deactivate the spinner.gif of input field
        //restore formerly settings of CSS background, if setted
        if (this.jssearchinputCSS != null)
        {
          this.jssearchinput.setStyle('background', this.jssearchinputCSS);
        }
        else
        {
          //otherwise remove the styles
          this.jssearchinput.setStyles({
            'background-image' : 'none',
            'background-repeat' : '',
            'background-position' : ''
          });
        }
        //fade in the results window
        this.resultsfx.start({
          'opacity': [0,1]
        });
      }.bind(this)
    });
  },
  setcookie : function() {
    var cookiestring='';
    var cookiename='joomsearch'+this.options.moduleid;;
    //limit
    if(this.jslimit != null)
    {
      limitval=this.jslimit.value;
      //var type = typeof(limitval);
      tmp = parseInt(limitval * 1, 10);
      cookiestring=tmp+'-';
    }
    else
    {
      cookiestring='0-';
    }

    if(this.jsupcatorimg != null)
    {
      cookiestring=cookiestring+this.jsupcatorimg.selectedIndex+'-';
    }
    else
    {
      cookiestring=cookiestring+'0-';
    }

    // image description, check if option no (0) activated
    if(this.js_imgdescr != null)
    {
      if($('js_imgdescrno'+this.options.moduleid).checked)
      {
        cookiestring=cookiestring+'0-';
      }
      else
      {
        cookiestring=cookiestring+'1-';
      }
    }
    else
    {
      cookiestring=cookiestring+'0-';
    }

    // comments
    if(this.js_comments != null)
    {
      if($('js_commentsno'+this.options.moduleid).checked)
      {
        cookiestring=cookiestring+'0-';
      }
      else
      {
        cookiestring=cookiestring+'1-';
      }
    }
    else
    {
      cookiestring=cookiestring+'0-';
    }

    // search authors
    if(this.js_authors != null)
    {
      if($('js_authorsno'+this.options.moduleid).checked)
      {
        cookiestring=cookiestring+'0-';
      }
      else
      {
        cookiestring=cookiestring+'1-';
      }
    }
    else
    {
      cookiestring=cookiestring+'0-';
    }

    // search cat description
    if(this.js_catdescr != null)
    {
      if($('js_catdescrno'+this.options.moduleid).checked)
      {
        cookiestring=cookiestring+'0';
      }
      else
      {
        cookiestring=cookiestring+'1';
      }
    }
    else
    {
      cookiestring=cookiestring+'0';
    }
    document.cookie=cookiename+'= '+cookiestring;
  }
});
JoomSearchModule.implement(new Options);
