/*
 * Copyright 2009 Palm, Inc. All rights reserved.
 */
/*global Mojo, Class, $L, HelpAssistant, UrlManager, WebViewHelper */
/*jslint rhino:true, undef:true */

var SearchAssistant = Class.create(HelpAssistant, {
  initialize: function($super, searchTerms, url) {
    $super();
    this.initialURL = url;
    this.searchTerms = searchTerms;
    this.topic = "home";

    var params =
    {
        "url": url,
        "assistant": this
    };

    this.webViewHelper = new WebViewHelper(params);
  },
  setup:function() {
    this.base_setup( );

    this.setupSearchBox(this.searchTerms);

    this.searchHandler = this.search.bind(this);
    this._onTitleUrlChange = this._onTitleUrlChange.bind(this);
    this.searchTermsChangedHandler = this.onSearchTermsChanged.bind(this);
  },

  activate: function(event) {
    this.controller.listen('search-button', Mojo.Event.tap, this.searchHandler);
    this.controller.listen('search-terms', Mojo.Event.propertyChanged, this.searchTermsChangedHandler);
    this.controller.listen('web-view-help', Mojo.Event.webViewTitleUrlChanged, this._onTitleUrlChange);
    this.base_activate();

  },
  deactivate: function(event) {
    this.controller.stopListening('search-button', Mojo.Event.tap, this.searchHandler);
    this.controller.stopListening('search-terms', Mojo.Event.propertyChanged, this.searchTermsChangedHandler);
    this.controller.stopListening('web-view-help', Mojo.Event.webViewTitleUrlChanged, this._onTitleUrlChange);
    this.base_deactivate();
  },
  ready: function() {
    this.base_ready();
  },
  cleanup: function(event) {
    this.base_cleanup();
  },
  search : function(event) {
    var terms = this.controller.get('search-terms').mojo.getValue();
    var wb = this.controller.get('web-view-help');
    wb.mojo.openURL(UrlManager.buildSearchQuery(terms));
  },
  _onTitleUrlChange: function(event) {
    this.setSearchBoxVisibility(event.url.startsWith(UrlManager.searchUrl));
  },
  onSearchTermsChanged : function(event) {
    if (event.originalEvent.type == 'keyup' && event.originalEvent.keyCode == Mojo.Char.enter) {
      this.search(event);
    }
    else if (event.value === '') {
      this.controller.get('search-button').style.visibility = 'hidden';
    }
    else {
      this.controller.get('search-button').style.visibility = 'visible';
    }
  }
});
