/*
 * Copyright 2009 Palm, Inc. All rights reserved.
 */
/*global Mojo, Class, $L, AppAssistant, ConnectionWidget, UrlManager, MenuData, navigator */
/*jslint rhino:true, undef:true */

var HelpAssistant = Class.create({
  initialize: function() {
    Mojo.Log.info("Initializing HelpAssistant base class.");
    this.gotNetworkStatus = this.gotNetworkStatus.bind(this);
    this.base_activate = this.base_activate.bind(this);
    this.base_connectionAlert = this.base_connectionAlert.bind(this);
  },

  base_setup: function( ) {
    try {
      Mojo.Log.info("setting up HelpAssistant base class instance.");
      this.spinnerModel = {spinning: true};
      
      this.setupAppMenu();

      // Not all child classes have a WebView, but if they do then this base class will
      // use it.
      if (this.webViewHelper) {
        this.webViewHelper.setup();
      }
      this.controller.setupWidget('large-activity-spinner', {spinnerSize: Mojo.Widget.spinnerLarge}, this.spinnerModel);

      var targetWindow = this.controller.window;
      if (targetWindow.PalmSystem && targetWindow.PalmSystem.setWindowOrientation) {
          if ( this.turnOffRotation ) {
            targetWindow.PalmSystem.setWindowOrientation("up");
		  } else {
            targetWindow.PalmSystem.setWindowOrientation("free");
		  }
      }

      // Allow override of 'back' gesture in landscape mode.
      this.controller.useLandscapePageUpDown(true);

      Mojo.Log.info("Help assistant setup complete");
    }
    catch (e) {
      Mojo.Log.logException(e, 'HelpAssistant.setup');
    }
  },

  base_cleanup: function () {
    if (this.webViewHelper) {
      this.webViewHelper.cleanup();
      delete this.webViewHelper;
    }
  },

  base_ready: function( ) {
    if (this.webViewHelper) {
      this.webViewHelper.ready( );
    }
  },

  base_activate: function(event) {
    AppAssistant.Network.observe(this.gotNetworkStatus);
    if (this.webViewHelper) {
      this.webViewHelper.startListening();
      this.webViewHelper.tryToLoadInitialUrl();
	  this.webViewHelper.activate();
    }
  },

  base_deactivate: function(event) {
    if (this.webViewHelper) {
      this.webViewHelper.stopListening();
    }
  },

  setupAppMenu: function(disableHelpItems) {
    this.appMenuModel = {
      visible: true,
      items: [Mojo.Menu.editItem]
    };
    if (this.controller.sceneName !== "home" && !disableHelpItems) {
      this.appMenuModel.items.push({ label: $L('Search'), command:'home', checkEnabled: true});
      this.appMenuModel.items.push({ label: $L('Tips'), command:'topics', checkEnabled: true});
      this.appMenuModel.items.push({ label: $L('Clips'), command:'flicks', checkEnabled: true});
    }
	if (this.controller.sceneName !== "home" && AppAssistant.showCopyInfoMenu) {
		this.appMenuModel.items.push({ label: $L('Copy Page Info'), command:'pageInfo'});
	}
    this.controller.setupWidget(Mojo.Menu.appMenu, {omitDefaultItems:true}, this.appMenuModel);
  },

  setupSearchBox: function(initialTerms) {
    this.searchBoxModel = { value: initialTerms };

    var attributes = {
      hintText: $L('Search Help...'),
      focus: false,
      enterSubmits: true,
      multiline: false,
      textCase: Mojo.Widget.steModeLowerCase,
      focusMode: Mojo.Widget.focusInsertMode,
      requiresEnterKey: true,
      changeOnKeyPress: true
    };

    this.controller.setupWidget('search-terms', attributes, this.searchBoxModel);
  },

  setSearchBoxVisibility: function(visible) {
                            Mojo.Log.info("XXXXXXXX Setting search visibility: %s", visible);
    var elem = this.controller.get('search-header');
    if (visible) {
      elem.show();
    }
    else {
      elem.hide();
    }
  },

  /**
   * We use the full scene spinner for when the BrowserServer is down.
   */
  setSpin: function(spinning) {
    if (spinning) {
      this.controller.get('spinContainer').show();
      this.controller.showWidgetContainer('spinContainer');
    }
    else {
      this.controller.hideWidgetContainer('spinContainer');
      this.controller.get('spinContainer').hide();
    }
    this.spinnerModel.spinning = spinning;
    this.controller.modelChanged(this.spinnerModel);
  },

  // return true if the event is handled, false if it is not
  base_handleCommand: function(event) 
  {
    try {
      if (event.type == Mojo.Event.back) {
        if (this.webViewHelper && this.webViewHelper.canGoBack && !this.webViewHelper.isChatWindow) {
          this.controller.get('web-view-help').mojo.goBack();
          event.preventDefault();
          event.stopPropagation();
        }
        else {
          var scene = this.controller.stageController.activeScene();
          if (scene && scene.sceneName !== 'home' && scene.sceneName !== 'chat' ) {
            event.preventDefault();
            event.stopPropagation();
            this.controller.stageController.popScene();
          }
        }
      }
      else if (event.type == Mojo.Event.command) 
      {
        switch (event.command) {
          case "home":
            this.controller.stageController.popScenesTo();
            this.controller.stageController.pushScene('home');
            break;
          case "topics":
            this.controller.stageController.popScenesTo('home');
            this.controller.stageController.pushScene({name: "json",transition: Mojo.Transition.crossFade},
              UrlManager.getTipsMenuUrl() );
            break;
          case "flicks":
            this.controller.stageController.popScenesTo('home');
            this.controller.stageController.pushScene({name: "json",transition: Mojo.Transition.crossFade},
              UrlManager.getClipsMenuUrl() );
            break;
          case "pageInfo":
            this.copyPageInfo();
            break;
          case MenuData.NavigationMenu.Stop.command:
            this.controller.get('web-view-help').mojo.stopLoad();
            break;
          case MenuData.NavigationMenu.Reload.command:
            this.controller.get('web-view-help').mojo.reloadPage();
            break;
          case MenuData.NavigationMenu.Back.command:
            if (this.webViewHelper && this.webViewHelper.canGoBack) {
              this.controller.get('web-view-help').mojo.goBack();
            }
            else {
              // Go back to the home scene
              this.controller.stageController.popScene();
            }
            break;
          case MenuData.NavigationMenu.Forward.command:
            if (this.webViewHelper && this.webViewHelper.canGoForward) {
              this.controller.get('web-view-help').mojo.goForward();
            }
            break;
          default:
            // It wasn't handled
            return false;
        }
      }
      else if (event.type == Mojo.Event.commandEnable) 
      {
        if (event.command == this.topic) 
        {
          event.preventDefault();
        }
      }
    }
    catch (e) {
      Mojo.Log.logException(e);
    }
    return true;
  },

  copyPageInfo: function() {
	var pageInfo = "Url: " + ((this.webViewHelper && this.webViewHelper.currentUrl) || this.url || '<none>') +
		"\nProduct model: " + UrlManager.deviceModel +
		"\nUser agent: " + navigator.userAgent +
		"\nX-Palm-Carrier: " + UrlManager.carrier;
	this.copyFromBuffer(pageInfo);
  },

	copyFromBuffer: function(data) {
		// Sets up a Text Field widget, sets its value to the data we want to
		// copy, copies it to the clipboard, then removes the Text Field widget
		var parentDiv = this.controller.document.createElement('div');
		var div = this.controller.document.createElement('div');
		div.setAttribute('x-mojo-element', 'TextField');
		div.setAttribute('id', 'help-app-copy-buffer');
		parentDiv.appendChild(div);
		this.controller.document.body.appendChild(parentDiv);
		this.controller.setupWidget('help-app-copy-buffer', {focus: true, multiline: true}, {value: data});
		this.controller.instantiateChildWidgets(parentDiv);
		var textField = this.controller.get('help-app-copy-buffer');
		textField.mojo.setCursorPosition(0, data.length);
		this.controller.document.execCommand('Copy');
		this.controller.document.body.removeChild(parentDiv);
	},

  handleCommand: function(event) {
    this.base_handleCommand(event);
  },

  isResource: function(url) {
    var lc = url.toLowerCase();
    return lc.startsWith("http:") || lc.startsWith("https:") || lc.startsWith("ftp:");
  },

  isCommand: function(url) {
    return !this.isResource(url);
  },

  showLoadFailed: function( url ) {
    if (!url) {
        url = "";
	}

    this.controller.get('web-view-help').hide();
    var failedElem = this.controller.get('load-failed-message');
    failedElem.show();
    var failedModel = {message:$L("Failed to load the requested page."), url: url};
    failedElem.innerHTML = Mojo.View.render({template:"failed-message-template", object:failedModel});
  },

    gotNetworkStatus: function(response) 
    {
        Mojo.Log.info("help: @@@ Got network status: online=", response.isInternetConnectionAvailable);

        // On first launch we alway attempt to connect to the network if we are not online.
        var self = this;
        if (!AppAssistant.Network.online) 
        {
            ConnectionWidget.connect({
                type: 'data',
                onSuccess: function(response) 
                    {
                        // If the connection widget was previously cancelled and we
                        // are under its internal timeout limit then popup the network
                        // alert dialog.
                        if (response === "WiFi-UserCancelled") 
                        {
                            if (self.base_connectionAlert) {
                                self.base_connectionAlert();
							} else {
                                Mojo.Log.info("Connection alert not implemented");
							}
                        }
                    }
            }, self.controller.stageController);
        }
    },

    base_connectionAlert: function(params)
    {
        // Show a custom network alert dialog.
        this.controller.showAlertDialog({

            onChoose: function(value) 
            {
                if (value === 'help') 
                {
                    this.controller.stageController.pushScene('no-network');
                }
            },

            title: $L('No Internet Connection'),
            message: $L('Please enable networking before using the help application.'),
            choices: [{
                    label: $L('Help'),
                    value: 'help',
                    type: 'dismiss',
                    buttonClass: 'secondary'
                }, {
                    label: $L('OK'),
                    value: 'OK',
                    type: 'alert',
                    buttonClass: 'primary'
                }]
        });

    }


});

