/**
* PoolPartyPage is a utility for building and maintaing a page.
* @module page
* @title PoolPartyPage utility
*/
/**
* The PoolPartyAutoComplete Class
* @class PoolPartyAutoComplete
* @constructor
* @param {Object} oConfig The Configuration for this PoolPartyAutoComplete.
*/
PoolPartyAutoComplete = function(oConfig){
 this.oConfigSchema = new Object();
 this.oConfigSchema["id"]="optional";
 this.oConfigSchema["useLucene"]="required";
 this.oConfigSchema["servletPath"]="optional";
 this.oConfig = oConfig; 
 this.build();
}
PoolPartyAutoComplete.prototype = {
 /**
 * ConfigurationError fires when there's an error in the Configuration for this PoolPartyPage
 * @event onConfigurationError
 * @type CustomEvent
 * @param type {type} The type.
 * @param args {Object} The arguments.
 * @param self {Object} self.
 */
 onConfigurationError: new YAHOO.util.CustomEvent('ConfigurationError'),
 /**
 * The Configuration of the PoolPartyPage
 * @property oConfig
 * @type Object
 */
 oConfig: null,
 /**
 * A Collection of Permanent AutoCompletes of the PoolPartyPage
 * @property oPermanentAutoCompletes
 * @type Object
 */
 oPermanentAutoCompletes: new Object(),
 /**
 * The Dynamic AutoComplete of the PoolPartyPage
 * @property oDynamicAutoComplete
 * @type {YAHOO.widget.AutoComplete}
 */
 oDynamicAutoComplete: null,
 /**
 * The DataSource of this PoolPartyAutoComplete
 * @property oDynamicAutoComplete
 * @type {YAHOO.util.XHRDataSource}
 */
 oDataSource:null,
 /**
 * The useLuceneFlag, wether to use Lucene or normal SPARQL Query
 * @property useLucene
 * @type {String} "true" || "false"
 */
 useLucene:"false",
 /**
 * The default servletPath used for the XHRDataSource
 * @property servletPath
 * @type {String}
 */
 servletPath:"../SesameIOAC",
 /**
 * Builds the PoolPartyAutoComplete from a ConfigurationObject.
 * @method build
 */
 build: function(){
  if("object" !== typeof this.oConfig || this.oConfig == null){
   this.onConfigurationError.fire();
  } else {
   for(key in this.oConfigSchema){
    if(typeof this.oConfigSchema[key] !== "function"){
     if(this.oConfigSchema[key]=="required"){
      if(this.oConfig[key]!==undefined){
       this[key] = this.oConfig[key];
      } else {
       this.onConfigurationError.fire();
       return;
      }
     } else {
      if(this.oConfig[key]!==undefined){ this[key] = this.oConfig[key];}
     }
    }
   }
   this.buildDataSource();
  }
 },
 /**
 * Builds the oDataSource of this PoolPartyAutoComplete
 * @method buildDataSource
 */
 buildDataSource: function(){
  this.oDataSource = new YAHOO.util.XHRDataSource(this.servletPath,{connMethodPost:true});
  this.oDataSource.responseType = YAHOO.util.XHRDataSource.TYPE_JSON;
  this.oDataSource.connXhrMode = "cancelStaleRequests";
  this.oDataSource.resultTypeList = true;
  this.oDataSource.responseSchema = {
    resultsList : "ResultList",
    fields : ["ID","Label", "Broader","BroaderLabel","ConceptScheme", "ConceptSchemeLabel", "type"]
  };
  /*
  * Check for session timeouts
  */ 
  this.oDataSource.subscribe("responseEvent",function(oArgs){            
    if(oArgs.response["getResponseHeader"]["login"]=="true"){
        window.document.location.href="index.jsp";
    }
  });
 },
 /**
 * Adds an AutoComplete from CommonSetup to the PermanentAutoCompletes of this PoolPartyAutoComplete
 * @method addPermanentDefaultAutoComplete
 * @param {String} AutoCompleteID. the id of the PermanentAutoComplete
 * @param {String} InputField. the id of the InputField
 * @param {String} ContainerDiv. the id of ContainerDiv
 */
 addPermanentDefaultAutoComplete: function(AutoCompleteID, InputField, ContainerDiv){
    if(this.oPermanentAutoCompletes[AutoCompleteID]!==undefined){
        try {
            this.oPermanentAutoCompletes[AutoCompleteID].destroy();
        } catch(e){ }
    }
    this.oPermanentAutoCompletes[AutoCompleteID] = this.createDefaultAutoComplete(InputField, ContainerDiv);
    
    this.oPermanentAutoCompletes[AutoCompleteID].dataRequestEvent.subscribe(function(oSelf, sQuery, oRequest){
      document.getElementById("permanentacloading").innerHTML = "<img src='images/permanentacloader.gif'/>";
    });
    this.oPermanentAutoCompletes[AutoCompleteID].dataReturnEvent.subscribe(function(oSelf, sQuery, oRequest){
      document.getElementById("permanentacloading").innerHTML = "";
    });    
 },
 /**
 * Adds a CustomAutoComplete to the PermanentAutoCompletes of this PoolPartyAutoComplete
 * @method addPermanentCustomAutoComplete
 * @param {String} AutoCompleteID. the id of the PermanentAutoComplete
 * @param {YAHOO.widget.AutoComplete} AutoComplete. the id of the InputField
 * @param {String} ContainerDiv. the id of ContainerDiv
 */
 addPermanentCustomAutoComplete: function(AutoCompleteID, AutoComplete){
    if(this.PermanentAutoCompletes[AutoCompleteID]!==undefined){
        this.PermanentAutoCompletes[AutoCompleteID].destroy();
    }
    this.PermanentAutoCompletes[AutoCompleteID] = AutoComplete;
 },
 /**
 * Returns the PermanentAutoComplete for the given AutoCompleteID
 * @method getPermanentAutoComplete
 * @param {String} AutoCompleteID. the id of the PermanentAutoComplete
 */
 getPermanentAutoComplete: function(AutoCompleteID){
    return this.oPermanentAutoCompletes[AutoCompleteID];
 },
 /**
 * Sets a DefaultAutoComplete as the DynamicAutoComplete of this PoolPartyAutoComplete
 * @method setDynamicDefaultAutoComplete 
 * @param {String} InputField. the id of the InputField
 * @param {String} ContainerDiv. the id of ContainerDiv
 */
 setDynamicDefaultAutoComplete: function (InputField, ContainerDiv){
    if(this.oDynamicAutoComplete!=null){
        try {
         this.oDynamicAutoComplete.destroy();
        } catch (e){}
    }
    this.oDynamicAutoComplete = this.createDefaultAutoComplete(InputField, ContainerDiv);    
 },
 /**
 * Sets the focus to the input field of the AutoComplete with the given id, if not found
 * to the DynamicAutoComplete
 * @method setFocusToInputfield
 * @param {String} AutoCompleteID. the id of the PermanentAutoComplete
 */
 setFocusToInputfield: function(AutoCompleteID){
    var ac;
    if (AutoCompleteID==null) {
        ac=this.DynamicAutoComplete;
    } else {
        ac=this.PermanentAutoCompletes[AutoCompleteID];
    }
    if (ac!=null) {
        ac.getInputEl().focus();
    }
 },
 /**
 * Creates a DefaultAutoComplete
 * @method createDefaultAutoComplete
 * @param {String} InputField. the id of the InputField
 * @param {String} ContainerDiv. the id of ContainerDiv
 */
 createDefaultAutoComplete: function(InputField, ContainerDiv){
        AutoComplete = new YAHOO.widget.AutoComplete(InputField,ContainerDiv, this.oDataSource, {maxResultsDisplayed:20,maxCacheEntries:0});
        AutoComplete.minQueryLength = 3;
        AutoComplete.useShadow = true;
        AutoComplete.suppressInputUpdate = true;
        var replacements = new Object();
            replacements.ö = "(Ö|ö)";
            replacements.ä = "(Ä|ä)";
            replacements.ü = "(Ü|ü)";            
        AutoComplete.generateRequest = function(sQuery) {
            var acLang;
                try {
                    acLang = PPP.ACLanguageMenuItem.cfg.getProperty("text");
                } catch(e){
                    acLang = PPP.getSessionAttribute("ProjectDefaultLanguage");
                }
            var Q;
            if(acLang=="de"){
                Q = (decodeURI(sQuery)).toLowerCase();
                for(umlaut in replacements){
                 if(typeof replacements[umlaut] !== "function"){
                 var regex = new RegExp( umlaut, "g" )
                      Q = Q.replace( regex, replacements[umlaut] );
                 }
                }
            } else {
                Q = decodeURI(sQuery);
            }

            return "lang="+acLang+"&query=" + (Q) +"&useLucene="+PPP.AC.useLucene;
        };
        AutoComplete.formatResult = function(oResultItem, sQuery, sResultMatch) {
            // Concept oResultItem[0];
            // Label oResultItem[1];
            // Broader oResultItem[2];
            // BroaderLabel oResultItem[3];
            // ConceptScheme oResultItem[4];
            // ConceptSchemeLabel oResultItem[5];
            //alert(oResultItem.toJSONString());
            var regex = new RegExp(sQuery.replace("^","").replace("$",""),'gi');
            var Label = "";
                for(var i = 0; i < oResultItem[1].length; i++){
                    if(i>0){ Label += ", "}
                    Label += oResultItem[1][i].replace(regex,function(thematch){ return "<span style='font-weight:bold;'>"+thematch+"</span>"});
                }
                try {
                if(oResultItem[3].length>0){
                    var BroaderLabelCounter = 0;
                    Label += " (";
                    for(var i = 0; i < oResultItem[3].length; i++){
                        if(BroaderLabelCounter < 3){
                            if(i>0){ Label += ", "; }
                            Label += oResultItem[3][i].replace(regex,function(thematch){ return "<span style='font-weight:bold;'>"+thematch+"</span>"});
                            BroaderLabelCounter++;
                        }
                    }
                    Label += ") ";
                }
                } catch(e){}
                try {
                if(oResultItem[4].length>0){
                    Label += " (";
                    if(oResultItem[5].length>0){
                        for(var i = 0; i < oResultItem[5].length; i++){
                            if(i>0){ Label+=", "}
                            Label += "<span style='font-style:italic'>"+oResultItem[5][i].replace(regex,function(thematch){ return "<span style='font-weight:bold;'>"+thematch+"</span>"}) + "</span>";
                        }
                    } else {
                            Label += "<span style='font-style:italic'>NOLABEL</span>";
                    }
                    Label += ") ";
                }
                } catch(e){}
                return Label;
        };        
        return AutoComplete;
 }
}
