/**
 * noun_type_php_function
 *
 * @author Peter Eliasson [warackta@gmail.com] http://verath.se/phpdoc/
 */

var noun_type_php_function = {
   _functions: [],
   _getPhpFunctions: function(){
      // Get all php functions
      $.get('http://php.net/quickref.php', function(data){
         var regexp = /<a.*?\/manual\/en\/function.*?>([\s\S.]*?)<\/a>/gim;
         var matches;
         while ((matches = regexp.exec(data)) != null){
            noun_type_php_function._functions.push(matches[1]);
         }
         
         noun_type_php_function._hasFunctions = 2;
      });
   },
   _hasFunctions: 0,
   _getfuncs: function(text){
      if( noun_type_php_function._hasFunctions !== 2 ) {
         if( noun_type_php_function._hasFunctions === 0 ) {
            noun_type_php_function._getPhpFunctions();
            noun_type_php_function._hasFunctions = 1;
         }
         return new Array(CmdUtils.makeSugg(text));
      }
      var functions = noun_type_php_function._functions;        
      var matches = new Array();
      for( var i=0; i < functions.length-1; i++ ){
         if (functions[i].substr(0, text.length) == text ){
            matches.push( CmdUtils.makeSugg(functions[i]) );
         }
      }
      if ( matches.length == 0 ){
         matches.push( CmdUtils.makeSugg(text) );
      }
      return matches;
   },
   label: "Function name",
   
   suggest: function( text, html, callback ) {
      return noun_type_php_function._getfuncs(text);
   }
   
};

/**
 * CreateCommand
 *
 * @author Peter Eliasson [warackta@gmail.com] http://verath.se/phpdoc/
 * @author Sebastian Barthenheier [tauven@gmail.com] http://taukon.de/ubiquity-php-function-doc.php
 * @author Sebastien Barbieri [contact@sbw.be] http://www.sbw.be/
 */


CmdUtils.CreateCommand({
        homepage:       "http://download.sbw.be/projects/ubiquity/php-search.html",
	icon: 		"http://www.php.net/favicon.ico",
        author:         {name: "Sebastien Barbieri", email: "contact@sbw.be", homepage: "http://www.sbw.be/"},
        license:        "GPL",
        description:    "Searching in the PHP Documentation, autocompletion while typing and an hit on the return key, will take you immediately to the official php documentation. This work is the concatenation of 2 other works: phpd and phpdoc from respectively:<br /><ul><li>Sebastian Barthenheier [tauven@gmail.com] http://taukon.de/ubiquity-php-function-doc.php</li><li>Peter Eliasson [warackta@gmail.com] http://verath.se/phpdoc/</li></ul><br/>",
        help:           "Enter php {function} to search for any documented php function",
        names:          ['php'],
        arguments:      {object: noun_type_php_function},
        preview:        function(pblock, {object: {text}}) {
                                if(!text){
                                	pblock.innerHTML = this.description;
				}else{
					pblock.innerHTML = _("Searching for <strong>${func_name}</strong> in the PHP documentation", {func_name: text});
					me = this;
					CmdUtils.previewGet(pblock, this._loc(text), function(phpDesc) {
						 if( phpDesc.search("<title>PHP: 404 Not Found</title>") === -1 ) {
						    pblock.innerHTML = _(me._template, {func_url: me._loc(text), func_name: text, summary: me._summary(phpDesc), useage: me._useage(phpDesc)} );
						 }
					});
				}
                        },
        execute:        function( {object: {text}}) {
                                // search for a tab containing http://[\.]+.php.net/ and do the serach in there or open a new url if no tabs found
                                tabs = Utils.tabs.search("^http:\/\/[^\.]+.php.net\/.*$",1);
                                url = "/manual-lookup.php" + Utils.paramsToString({pattern: text}) + "";
                                if(tabs.length > 0){
                                        currentURLSplitted = tabs[0].document['URL'].split('/');
                                        tabs[0]._browser.loadURI(currentURLSplitted[0]+"//"+currentURLSplitted[2]+url);
                                        tabs[0].focus();
                                }else{
                                        Utils.openUrlInBrowser("http://www.php.net"+url);
                                }
                        },
                        
	_template: "<strong><a href='${func_url}'>${func_name}</a></strong><br /><i>${summary}</i><br /><br />${useage}",

	_loc: function(func){
		return _("http://php.net/manual/en/function."+ func +".php").replace(/_/gim, '-');
	},

	_useage: function(page){
		var page    = page.replace(/<\/?span.*?>/gim, '');
		var regexp  = /methodsynopsis dc-description.*?>([\s\S.]*?)<\/div>/im;
		var matches = regexp.exec(page);
		if( matches != null ) {
			return "Useage:<br />" + matches[1].replace(/(\n)+/gim, ' ');
		} else {
			return '';
		}
	},

	_summary: function(page){
		var page    = page.replace(/<\/?span.*?>/gim, '');
		var regexp  = /<p.*?class="(sim)?para( rdfs-comment)?".*?>([\s\S.]*?)<\/p>/im;
		var matches = regexp.exec(page);
		if( matches != null ) {
			return matches[3].replace(/(\n)+/gim, '');
		} else {
			return '';
		}
	},

	_getText: function(html){
		return html.replace(/<br \/?>/gim, "\n").replace(/<.*?>/gim,'').replace(/( )+/gim, ' ').replace(/\n( )*/gim, "\n");
	}
});
