// ************** LICENCE ****************
/*
	Copyright (c) PORTANEO.

	This file is part of POSH (Portaneo Open Source Homepage) http://sourceforge.net/projects/posh/.

	POSH is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version

	POSH is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with Posh.  If not, see <http://www.gnu.org/licenses/>.
*/
// ***************************************
// Modules javascript functions
//
// !! be careful, this file must be saved under uft8 format, and display an e accentuated here : é à ù è
// ***************************************

/*
 *  file: modules.js
 *
 *  javascript functions used by Iframe widgets
 *
 *
 */
var windowLocationObject = {
	'search':window.location.search,
	'href':window.location.href,
	'protocol':window.location.protocol,
	'host':window.location.host
};

var indef;
var __lang=parent.__lang;
var __LOCALFOLDER=parent.__LOCALFOLDER;

// get widget ID based on URL
if (!__MODULE_ID__) {
    var querystring = windowLocationObject.search.substring(1);
	var l_items = querystring.split("&");
	for (var i = 0; i < l_items.length; i++) 
	{
		var l_arr = l_items[i].split("=");
		if (l_arr[0] == "p") {
			var __MODULE_ID__ = l_arr[1];
		}
	}
    if (__MODULE_ID__ == '') __MODULE_ID__ = indef;
}
// get widget ID in the parent page (only if in the same domain
if (__MODULE_ID__ == indef && parent.document) {
    var frms = window.parent.document.getElementsByTagName('iframe');
    for (var i = 0; i < frms.length; i++)
    {
        if (frms[i].contentWindow) {
            var l_parentElement = frms[i].contentWindow;
            var l_objectElement = window;
        }
        else {
            var l_parentElement = frms[i].contentDocument;
            var l_objectElement = document;
        }
        if (l_parentElement == l_objectElement) {
            var parts = (frms[i].id).split('_');
            var l_moduleId = parts[1];
            if (!isNaN(l_moduleId))
            {
                __MODULE_ID__ = l_moduleId;
            }
        }
    }
}



/*
    Function : __
    
            module translation

       Parameters:
       
                v_s - label to translate
 */
function __(v_s) {
	return parent.lg(v_s);
}


//open Netvibes widgets
callNetvibesWidget=function(url)
{
	/*
	License:
	  Copyright (c) 2005-2008 Netvibes (http://www.netvibes.org/).

	  This file is part of Netvibes Widget Platform.

	  Netvibes Widget Platform is free software: you can redistribute it and/or modify
	  it under the terms of the GNU Lesser General Public License as published by
	  the Free Software Foundation, either version 3 of the License, or
	  (at your option) any later version.

	  Netvibes Widget Platform is distributed in the hope that it will be useful,
	  but WITHOUT ANY WARRANTY; without even the implied warranty of
	  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	  GNU Lesser General Public License for more details.

	  You should have received a copy of the GNU Lesser General Public License
	  along with Netvibes Widget Platform.  If not, see <http://www.gnu.org/licenses/>.
	*/
	if (typeof UWA == 'undefined') UWA = {};

	UWA.iFrameMessaging = function(){}

	UWA.iFrameMessaging.prototype = {
	    _options : {},
	    
	    init: function(options){
	        var _this = this;
	        
	        if (typeof options!='object' || !options.eventHandler) {
	            return;
	        }
	        
	        this._options  = options;
	        
	        if (typeof document.postMessage === 'function' || typeof window.postMessage === 'function') {
	            window.addEventListener('message',  function(msg){
	                var origin = msg.origin;
	                if (origin){ // Common case
	                    origin = origin.split('//')[1];
	                } else { // Opera case
	                    origin = msg.domain;
	                }
	                _this.dispatch(msg.data, origin, 'postMessage');
	            }, false);
	        }
	    },
	    
	    dispatch: function(msg, msgOrigin, msgCommType){
	        var options = this._options;
	        msgOrigin = unescape(msgOrigin);
	        if (typeof options.trustedOrigin == 'undefined' || msgOrigin==options.trustedOrigin){
	            var msg = this.decodeJson(msg);
	            if (msg) {
	                msg.commType = msgCommType;
	                options.eventHandler(msg);
	            };
	        } else {
	             throw new Error('Origin ' + msgOrigin + ' is not trusted.');
	        }
	    },
	    
	    decodeJson: function(json){
	        var ret = false;
	        if ((/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(unescape(json).replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, ''))) {
	            ret = eval('(' + unescape(json) + ')');
	        }
	        return ret;
	    }
	}
	msgHandler = function(message) {
	  var id = message.id;
	  switch (message.action) {
	    case 'resizeHeight':
	      var frame = document.getElementById('frame_' + id);
	      if (frame) {
	        frame.setAttribute('height', message.value);
			_IG_AdjustIFrameHeight(message.value);
	      }
	      break;
        default:
	   //   console.log(message.action + ': not implemented - ' + message.name + ':' + message.value);
	      break;
	  }
	};
	UWA.MessageHandler = new UWA.iFrameMessaging;
	UWA.MessageHandler.init({
	    'eventHandler': msgHandler,
	    'trustedOrigin' : 'nvmodules.netvibes.com'
	});
    //document.write("http://nvmodules.netvibes.com/widget/frame/?uwaUrl='+_esc(url)+'&id=123456&ifproxyUrl='+_esc(__LOCALFOLDER+'tools/netvibesproxy.html')+'");
	document.write('<iframe id="frame_123456" scrolling="no" frameborder="0" height="300" width="100%" src="http://nvmodules.netvibes.com/widget/frame/?uwaUrl='+_esc(url)+'&id=123456&ifproxyUrl='+_esc(__LOCALFOLDER+'tools/netvibesproxy.html')+'"></iframe>');
}



//declare the gadget namespace
gadgets = {};

gadgets.Container = function() {
    this.gadgets_ = {};
    this.parentUrl_ = 'http://' + document.location.host;
    this.country_ = 'ALL';
    this.language_ = 'ALL';
    this.view_ = 'default';
    this.nocache_ = 1;
    // signed max int
    this.maxheight_ = 0x7FFFFFFF;
}; 





































//Gadget Views class
gadgets.views={
    ViewType:'home',
    View:function (mode) {
        var views = gadgets.views.getSupportedViews(); 
        return views[mode];
    },
    /*
                Function: gadgets.views.getCurrentView
                
                    get current view
    
        */
    getCurrentView:function () {
        this.getName = gadgets.views.getName;
        this.l_tab = parent.$p.app.tabs.sel;
        this.l_id = parent.$p.app.widgets.uniqToId(__MODULE_ID__,this.l_tab);
        
        return gadgets.views;
    },
    /*
                Function: gadgets.views.getName
                
                    return currentview name
        */
    getName:function () {
        var l_tab=parent.$p.app.tabs.sel;
        var l_id=parent.$p.app.widgets.uniqToId(__MODULE_ID__,l_tab);
        gadgets.views.ViewType=parent.tab[l_tab].module[l_id].currentView;
        return parent.tab[l_tab].module[l_id].currentView;
    },
    getParams:function () {
    
    },
    /*
                Function: gadgets.views.getSupportedViews
                
                        return supported view and function linked
                        
                        
        */
    getSupportedViews: function (v_uniq,v_id) {
        var l_tab=parent.$p.app.tabs.sel;
		var uniq = __MODULE_ID__;
        var l_id=parent.$p.app.widgets.uniqToId(__MODULE_ID__,l_tab);
		var modid = l_id;		
		if(v_id != indef) {
			modid = v_id;
		}
		if(v_uniq != indef) {
			uniq = v_uniq;
		}
        var viewTab = {
            'canvas'  :  'parent.$p.app.widgets.maximize('+uniq+','+modid+')',
            'home'      : 'parent.$p.app.widgets.homeView('+modid+')'
        };
        return viewTab;
    },
    url:null,
    /*
            function: gadgets.views.changeUrl
            
                change url to open any url in a full scree view
                
                parameters:
                
                    url - url
                    
        */
    changeUrl:function (url) {
        gadgets.views.url = url;
    },
    /*
                function: gadgets.views.requestNavigateTo

                        function to open a canvas content in full screen view
                  
                  parameters :
                
                        fct  - function used to return to view (return of the gadgets.views.getSupportedViews() function)
                        opt_params - 
                        opt_ownerId - 
                        
                  Example : gadgets.views.requestNavigateTo(gadgets.views.getSupportedViews()['home']);
            */
    requestNavigateTo:function (fct,opt_params, opt_ownerId) {
        //modify url to add parameters (id of this widget, who become parent id, to return to old widget)
        var l_tab = parent.$p.app.tabs.sel;
        var l_id = parent.$p.app.widgets.uniqToId(__MODULE_ID__,l_tab);
        
        // if the view called is the current view, just refresh the widget
        if (fct == gadgets.views.getSupportedViews()[parent.tab[l_tab].module[l_id].currentView])
        {
            parent.tab[l_tab].module[l_id].url = gadgets.views.url;
            parent.tab[l_tab].module[l_id].format = 'U';
            parent.tab[l_tab].module[l_id].refresh();
        }
        else
        {
            //get object then send to windows
            if (gadgets.views.url) {
                parent.tab[l_tab].module[l_id].newUrl = gadgets.views.url;
                parent.tab[l_tab].module[l_id].newFormat = 'U';
                gadgets.views.url=null;
            }
            eval(fct);
        }
    },
    isOnlyVisibleGadget:function () {},
    getUrlTemplate:function () {},
    bind:function() {}
}






//Gadget Config function
gadgets.config = function() {
  var components = [];
  var configuration;
  return {
    'register':
    function(component, opt_validators, opt_callback) {
      var registered = components[component];
      if (!registered) {
        registered = [];
        components[component] = registered;
      }

      registered.push({
        validators: opt_validators || {},
        callback: opt_callback
      });
    },
    'get':
    function(opt_component) {
      if (opt_component) {
        return configuration[opt_component] || {};
      }
      return configuration;
    },
    'init': function(config, opt_noValidation) {
      configuration = config;
      for (var name in components) {
        if (components.hasOwnProperty(name)) {
          var componentList = components[name],
              conf = config[name];

          for (var i = 0, j = componentList.length; i < j; ++i) {
            var component = componentList[i];
            if (conf && !opt_noValidation) {
              var validators = component.validators;
              for (var v in validators) {
                if (validators.hasOwnProperty(v)) {
                  if (!validators[v](conf[v])) {
                    throw new Error('Invalid config value "' + conf[v] +
                        '" for parameter "' + v + '" in component "' +
                        name + '"');
                  }
                }
              }
            }

            if (component.callback) {
              component.callback(config);
            }
          }
        }
      }
    },
    'EnumValidator': function(list) {
      var listItems = [];
      if (arguments.length > 1) {
        for (var i = 0, arg; (arg = arguments[i]); ++i) {
          listItems.push(arg);
        }
      } else {
        listItems = list;
      }
      return function(data) {
        for (var i = 0, test; (test = listItems[i]); ++i) {
          if (data === listItems[i]) {
            return true;
          }
        }
      };
    },
    'RegExValidator': function(re) {
      return function(data) {
        return re.test(data);
      };
    },
    'ExistsValidator': function(data) {
      return typeof data !== "undefined";
    },
    'NonEmptyStringValidator': function(data) {
      return typeof data === "string" && data.length > 0;
    },
    'BooleanValidator': function(data) {
      return typeof data === "boolean";
    },
    'LikeValidator' : function(test) {
      return function(data) {
        for (var member in test) {
          if (test.hasOwnProperty(member)) {
            var t = test[member];
            if (!t(data[member])) {
              return false;
            }
          }
        }
        return true;
      };
    }
  };
}();






//Prefs constructor
gadgets.Prefs = function (uniq) {
    this.uniq = uniq || 0;
    this.seltab = parent.$p.app.tabs.sel;
	if (this.seltab < 0) this.seltab = 0;
    this.id = parent.$p.app.widgets.uniqToId(uniq);
    this.vars = parent.tab[this.seltab].module[this.id].vars;
    this.getString = gadgets.Prefs.getString;
    this.getInt = gadgets.Prefs.getInt;
    this.getBool = gadgets.Prefs.getBool;
    this.set = gadgets.Prefs.setPrefVal;
    this.open = gadgets.Prefs.openPref;
    this.addOption = gadgets.Prefs.addPrefOption;
    this.removeOption = gadgets.Prefs.removePrefOption;
    this.getMsg = gadgets.Prefs.getMsg;
    this.getArray = gadgets.Prefs.getArray;
    this.setArray = gadgets.Prefs.setArray;
    this.getCountry = gadgets.Prefs.getCountry;
    this.getLang = gadgets.Prefs.getLang;
};
gadgets.Prefs.getMsg = function (label) {
    if (label == 'default_hl') {
        return __lang;
    }
    return label;
};
/*

    Function: getString
            
            Get variable value from this widget URL 

     Parameters: 
     
        v_var - variable searched
			
	Returns:
                    
                value of the variable
 */
gadgets.Prefs.getString = function (v_var) {
    return parent.$p.string.getVar(this.vars,v_var,'string');
};
/*

    Function: getInt
            
    Get variable value from this widget URL as an int

     Parameters: 
     
        v_var - variable searched
			
	Returns:
                    
                value of the variable (int)
 */
gadgets.Prefs.getInt = function (v_var) {
    return parseInt(parent.$p.string.getVar(this.vars,v_var,'int'),10);
};
/*

    Function: getBool
            
    Get variable value from this widget URL as a boolean

     Parameters: 
     
        v_var - variable searched
			
	Returns:
                    
                value of the variable (boolean)
 */
gadgets.Prefs.getBool = function (v_var) {
    return (parent.$p.string.getVar(this.vars,v_var)==1?true:false);
};
/*

    Function: setPrefVal
            
    set the variable searched to the input value

     Parameters: 
     
        v_var - variable searched
        v_value - new value for the variable
 */
gadgets.Prefs.setPrefVal = function (v_var,v_value) {
    parent.tab[this.seltab].module[this.id].changeVar(v_var,v_value);
    parent.$p.app.widgets.param.getModuleParam(this.id);
};
/*

    Function: openPref
            
		opens the preferences menu.
	
	Returns:
				false;
 */
gadgets.Prefs.openPref = function (){
    parent.$p.app.widgets.param.show(this.uniq);
    return false;
};
/*

    Function: addPrefOption
            
    add value to a preferences option

     Parameters: 
     
		v_selectName - the option name
		v_value - value to add
		v_displayValue - for display the value
	   
 */
gadgets.Prefs.addPrefOption = function (v_selectName,v_value,v_displayValue) {
    var l_tab = parent.$p.app.tabs.sel;
    //	var l_id = parent.$p.app.widgets.uniqToId(__MODULE_ID__,l_tab);
    var l_select = parent.$('editboxinput_'+parent.tab[l_tab].id+'_'+__MODULE_ID__+'_'+v_selectName);
    l_select.options[l_select.options.length] = new Option(v_displayValue, v_value);
};
/*

    Function: removePrefOption
            
    remove a value from a preferences option

    Parameters: 
     
		v_selectName - the option name
		v_value - value to remove
		
	Returns:
		true if the value has been found
		false if the value has vot been found
	   
 */
gadgets.Prefs.removePrefOption = function (v_selectName,v_value) {
    var l_tab = parent.$p.app.tabs.sel;
    var l_select = parent.$('editboxinput_'+parent.tab[l_tab].id+'_'+__MODULE_ID__+'_'+v_selectName);
    for (var i = 0;i < l_select.options.length;i ++)
    {
        if (l_select.options[i].value == v_value)
        {
            l_select.options[i] = null;
            return true;
        }
    }
    return false;
}; 
/*

    Function: set
            
    remove a value from a preferences option

    Parameters: 
     
        String key - The pref to store 
        Object val - The values to store  
 */
gadgets.Prefs.set = function(key, value) { gadgets.Prefs.setPrefVal(key,value); };
/*

    Function: getArray
            
    remove a value from a preferences option

    Parameters: 
     
        String key - The preference to fetch 
        
     Returns:
            
          Array.<String> - The preference; if not set, an empty array 
 */
gadgets.Prefs.getArray = function(key) { };
/*

    Function: setArray
           
    Parameters: 
     
        String key - The pref to store 
        Array val - The values to store 
 */
gadgets.Prefs.setArray = function(key,val) { };
/*

    Function: getMsg
           
    Parameters: 
     
        String key - The message to fetch 

    Returns:
    
        String - The message
 */
gadgets.Prefs.getMsg = function(key) { };
/*

    Function: getCountry

    Returns:
    
        String - The country for this module instance 
 */    
gadgets.Prefs.getCountry = function() { return 'us'; };
/*

    Function: getLang

    Returns:
    
        String - The language for this module instance  
 */     
gadgets.Prefs.getLang = function() { return __lang; };
gadgets.Prefs.getModuleId = function() { };


//deprecated Prefs functions
function getMsg (label) { return gadgets.Prefs.getMsg(label); }
function getString(v_var){ return gadgets.Prefs.getString(v_var); }
function getInt(v_var){ return gadgets.Prefs.getInt(v_var); }
function getBool(v_var){ return gadgets.Prefs.getBool(v_var); }
function setPrefVal(v_var,v_value) { gadgets.Prefs.setPrefVal(v_var,v_value); }
function openPref() { return gadgets.Prefs.openPref(); }
function addPrefOption(v_selectName,v_value,v_displayValue) { gadgets.Prefs.addPrefOption(v_selectName,v_value,v_displayValue); }
function removePrefOption(v_selectName,v_value) { return gadgets.Prefs.removePrefOption(v_selectName,v_value); }
function _IG_Prefs(uniq) { return new gadgets.Prefs(uniq); }   







//gadget window class
gadgets.window = {
    /*

            Function: adjustHeight
                    
                    Resize frame
                    
                   This function should be called right after displaying HTML code
                  
             Parameters: 
             
                v_height -  default height (or additional height / computing)
                v_repeat -  repeat frame adjustment
                v_delay (int) -  delay to resize the frame (number of second)
          
         */
    adjustHeight:function(v_height,v_repeat,v_delay,v_tab) {
        var l_height = v_height;
        v_delay = (v_delay==indef) ? 1 : v_delay;

        // if module ID is not defined, no action
        if (__MODULE_ID__ == indef) return;
        var local_height;
        var l_additionalHeight = 5;

        // if additional height sent
        if (l_height != indef 
            && typeof(l_height) == 'string' 
            && l_height.substr(0,1) == '+') {
                l_additionalHeight = parseInt(v_height.substr(1),10);
                l_height = indef;
        }

        if (l_height) {
            local_height = l_height;
        }
        else {
            /**
                                            going through this condition is needed to allow resizing of widget
                                            so v_height can be defined, but in most of cases it must be undefined
                                **/
            if (document.all) {
                if (document.compatMode && document.compatMode != 'BackCompat') {
                    local_height = document.documentElement.scrollHeight + l_additionalHeight;
                }
                else {
                    local_height = document.body.scrollHeight + l_additionalHeight;
                }
            }
            else if (document.height) {
                local_height = document.height + 5 + l_additionalHeight;
            }
        }
        //resize widget frame
        if (!parent.$p) return;
        var l_tab = parent.$p.app.tabs.sel;
		// prevent from resizing in another tab if user switch from one tab to another
		if (v_tab != indef && v_tab != l_tab) return;
        
        //depending on the mode, resize widget or canvas view
        var l_id = parent.$p.app.widgets.uniqToId(__MODULE_ID__,l_tab);
		if (parseInt(local_height,10) >= 30)
			parent.tab[l_tab].module[l_id].setHeight(local_height);
        
        // fix issue with IE
        if (v_repeat == indef || v_repeat == true) {
            if (v_height == indef) {
                //must  indef to allow resizing of widget, no change here unless you know what you are doing and you can test with several widgets
                setTimeout("_IG_AdjustIFrameHeight(indef,false,indef," + l_tab + ")",1000*v_delay);
            }
            else {
                setTimeout("_IG_AdjustIFrameHeight('" + v_height + "',false,indef," + l_tab + ")",1000*v_delay);
            }
        }    
    },
    /*

            Function: getViewportDimensions

                   Detects the inner dimensions of a frame.
                  
             Returns:
             
                    Object - An object with width and height properties 
          
         */
    getViewportDimensions:function() {},
    /*
            Function: setTitle
                    
                    Sets the gadget title. 
                 
           Parameters:

                    String title - The preferred title 
         */
    setTitle:function(title) {
    	var l_tab=parent.$p.app.tabs.sel;
        var l_id=parent.$p.app.widgets.uniqToId(__MODULE_ID__,l_tab);
        parent.$p.app.widgets.changeName(l_id,title,l_tab);
    }
}

//deprecated functions (old versions compatibility)
function _IG_AdjustIFrameHeight(v_height,v_repeat,v_delay,v_tab) { gadgets.window.adjustHeight(v_height,v_repeat,v_delay,v_tab); }
function _IG_SetTitle(title) { gadgets.window.setTitle(title); }





var parameters = null;
var features = {};
var onLoadHandlers = [];

//Provides general-purpose utility functions. 
gadgets.util = {
  
    getUrlParameters:function (v_s) {
        return _args(v_s);
      /*
      if (parameters !== null) {
        return parameters;
      }
      parameters = {};
      var pairs = parseUrlParams();
      var unesc = window.decodeURIComponent ? decodeURIComponent : unescape;
      for (var i = 0, j = pairs.length; i < j; ++i) {
        var pos = pairs[i].indexOf('=');
        if (pos === -1) {
          continue;
        }
        var argName = pairs[i].substring(0, pos);
        var value = pairs[i].substring(pos + 1);
        value = value.replace(/\+/g, " ");
        parameters[argName] = unesc(value);
      }
      return parameters;
      */
    },
    makeClosure:function(scope, callback, var_args) {
      // arguments isn't a real array, so we copy it into one.
      var baseArgs = [];
      for (var i = 2, j = arguments.length; i < j; ++i) {
       baseArgs.push(arguments[i]);
      }
      return function() {
        // append new arguments.
        var tmpArgs = baseArgs.slice();
        for (var i = 0, j = arguments.length; i < j; ++i) {
          tmpArgs.push(arguments[i]);
        }
        return callback.apply(scope, tmpArgs);
      };
    },
    escape:function(str) {
       // return _esc(str); 
    },
    escapeString:function(str) {
        return _esc(str);
    },
    unescapeString:function(str) {
        return _unesc(str);
    },
    /*
                    function: _IG_RegisterOnloadHandler
                    
                    set onload handler
                    
                    Parameters:
                    
                        v_fct - function to handle
            */
    registerOnLoadHandler:function(v_fct) {
        window.onload=v_fct;
    },
    getFeatureParameters:function(feature) {},
    hasFeature:function(feature) {},
    sanitizeHtml:function(text){},
    makeEnum:function (values) {
      var obj = {};
      for (var i = 0, v; (v = values[i]); ++i) {
        obj[v] = v;
      }
      return obj;
    }   
}

//deprecated functions (old versions compatibility)
function _IG_RegisterOnloadHandler(v_fct) { gadgets.util.registerOnLoadHandler(v_fct); }


/* Not implemented, check out the documentation here: http://wiki.opensocial.org/index.php?title=Gadgets.Tab_%28v0.8%29 */
gadgets.Tab = {
    getName:function() {},
    getNameContainer:function() {},
    getContentContainer:function() {},
    getCallback:function() {},
    getIndex:function() {}    
}

//TabSet constructor
gadgets.TabSet = function (v_id,v_selTab) {
	this.moduleId=v_id;
	this.selTab=v_selTab;
	this.ulObj=null;
	this.addTab=gadgets.TabSet.addTab;
	this.addDynamicTab=gadgets.TabSet.addDynamicTab;
	this.setSelectedTab=gadgets.TabSet.setSelectedTab;
	this.moveTab=gadgets.TabSet.moveTab;
    this.alignTabs=gadgets.TabSet.alignTabs;
	this.getHeaderContainer=gadgets.TabSet.getTabsHeaderContainer;
    this.getSelectedTab=gadgets.TabSet.getSelectedTab;
};
/*

    Function: addTab
            
		add a tab

    Parameters:
	 
		v_name - name of the new tab
		v_divId - id of the div 
		v_fct - function associated to the tab selection

 */
gadgets.TabSet.addTab = function (v_name,v_divId,v_fct) { 

    if (!v_fct) {
        v_fct = nofunction;
    }
	if (v_divId==indef) v_divId="contentdiv";

	//define default tab if not already defined
	if (this.selTab==indef) this.selTab=v_name;
	//create tabs div if not already existing

	if (this.tabsContainer==null) {
		this.tabsContainer=document.createElement("div");
		this.tabsContainer.id="tabsdiv";
		// insert the tabContainer above the tabs content
		if (_gel(v_divId) == null) {
			document.body.appendChild(this.tabsContainer);
		}
		else {
			document.body.insertBefore(this.tabsContainer,_gel(v_divId));
		}
	}
    
	//create content div if not already existing
	if (_gel(v_divId) == null) {
		var l_obj=document.createElement("div");
		l_obj.id=v_divId;
		document.body.appendChild(l_obj);
	}
	else {
		var l_obj=_gel(v_divId);
	}
   
	//create ul obj if not already existing
	if (this.ulObj==null) {
		this.ulObj=document.createElement("ul");
		this.ulObj.className="tablist";
		this.tabsContainer.appendChild(this.ulObj);
        var l_separator = document.createElement('div');
		l_separator.style.clear = 'both';
		l_separator.style.height = '0px';
		this.tabsContainer.appendChild(l_separator);
	}
	//add the new tab
	var l_liObj=document.createElement("li");
	l_liObj.className=(this.selTab==v_name)?"tabsel":"tab";
	l_liObj.id=v_name+'_tab';
	
	l_aObj = document.createElement("a");
    l_aObj.appendChild(document.createTextNode(v_name));
    l_aObj.href = "javascript:void(null);";
    l_aObj.title = v_name;
	l_aObj.main = this;
	l_aObj.selDiv = v_divId;
	l_aObj.fct = v_fct;
    l_aObj.onmouseup = function(){changeSelectedTab(this.title,this.main);this.fct(this.selDiv);};
	l_liObj.appendChild(l_aObj);
	this.ulObj.appendChild(l_liObj);
	
	if (this.selTab == v_name) {
		changeSelectedTab(v_name,l_aObj.main);
		v_fct(v_divId);
	}
	
	return l_obj;
};
/*

    Function: addDynamicTab
            
		add a dynamic tab

    Parameters:
	 
		v_name - name of the new tab
		v_fct - function associated to the tab selection

 */
gadgets.TabSet.addDynamicTab = function (v_name,v_fct) {    
    gadgets.TabSet.addTab(v_name,v_name,v_fct);
};
/*

    Function: setSelectedTab
            
		set a default selected tab

    Parameters:
	 
		v_index - name of the default tab
		
 */
gadgets.TabSet.setSelectedTab = function (v_index) {    
	//define selected tab
    for (var i=0;i<this.ulObj.childNodes.length;i++)
	{
		var l_node=this.ulObj.childNodes[i];
        var tabDiv = this.ulObj.childNodes[i].childNodes[0].selDiv;
		l_node.className=(i==v_index?"tabsel":"tab");
        if ( _gel(tabDiv) ) {
            // hide the divs linked to other tabs
            _gel(tabDiv).style.display = (i == v_index) ?  'block' : 'none';
        }
	}    
};
/*

    Function: changeSelectedTab
            
		set a default selected tab		
 */
gadgets.TabSet.changeSelectedTab = function (v_name,v_obj) { 
    v_obj.selTab=v_name;
	for (var i=0;i<v_obj.ulObj.childNodes.length;i++)
	{
		var l_node=v_obj.ulObj.childNodes[i];
		if (l_node.id==v_name+'_tab') v_obj.setSelectedTab(i);
	}
};
gadgets.TabSet.getSelectedTab = function () { 
    return this.selTab;
};

gadgets.TabSet.getTabsHeaderContainer = function () { 
    return this.tabsContainer; 
};

gadgets.TabSet.alignTabs = function (align, opt_offset) {
    var align = align || "center";
    var opt_offset = opt_offset || "3px";
    var container = this.getHeaderContainer();
    container.align = align;
    if (align == 'left') {
        container.style.marginLeft = opt_offset;
    }
    if (align == 'right') {
        container.style.marginRight = opt_offset;
    }
};



gadgets.TabSet.displayTabs = function (display) {};
gadgets.TabSet.getTabs = function () {};
gadgets.TabSet.removeTab = function (tabIndex) {};
gadgets.TabSet.swapTabs = function (tabIndex1, tabIndex2) {};


//deprecated functions (old versions compatibility)
function _IG_Tabs(v_id,v_selTab) { return new gadgets.TabSet(v_id,v_selTab); }   
function addTab(v_name,v_divId,v_fct) { return gadgets.TabSet.addTab(v_name,v_divId,v_fct); } 
function addDynamicTab(v_name,v_fct) { return gadgets.TabSet.addTab(v_name,v_name,v_fct); } 
function setSelectedTab(v_index) { gadgets.TabSet.setSelectedTab(v_index); }
function changeSelectedTab(v_name,v_obj) { gadgets.TabSet.changeSelectedTab(v_name,v_obj); }   
function moveTab() {}   
function alignTabs(align, opt_offset) { gadgets.TabSet.alignTabs(align, opt_offset); }   
function getTabsHeaderContainer() { return gadgets.TabSet.getTabsHeaderContainer(); }
      
//gadgets.skins class
gadgets.skins = function() {};
gadgets.skins.getProperty = function(propertyKey) {};








//gadgets.flash class
gadgets.flash = {

    embedCachedFlash:function(swfUrl,swfContainer,swf_version,opt_params) {},
    /*

            Function: embedFlash
                    
                create a new flash object

            Parameters:
             
                swf_url - url of the flash object
                swf_container - container object
                opt_params - the flash object parameters

         */
    embedFlash:function(swfUrl,swfContainer,swf_version,opt_params) {
    //Not working: requires SWFObject class
        /*
        var so = new SWFObject(swf_url, "flash", "100%", "100%", "6");
        for(opt_param in opt_params)
        {
            so.addParam(opt_param,opt_params[opt_param]);
        }
        so.write(swf_container);
        */
    },
    /*
                    Function: getMajorVersion
                
                    ??????????????????????
            */    
    getMajorVersion:function() {}
    
}

//deprecated functions (old versions compatibility)
function _IG_GetFlashMajorVersion() { return gadgets.flash.getMajorVersion(); }
function _IG_EmbedFlash(swfUrl,swfContainer,opt_params) { gadgets.flash.embedFlash(swfUrl,swfContainer,opt_params.swf_version,opt_params); };
function _IG_EmbedCachedFlash(swfUrl,swfContainer,opt_params) { return gadgets.flash.embedCachedFlash(swfUrl,swfContainer,opt_params.swf_version,opt_params); };








//gadgets.pubsub class (rpc calls)
gadgets.pubsub = {

    publish:function(channelName, message) {},
    subscribe:function(channelName, callback) {},
    unsubscribe:function(channelName) {}
    
}








//gadgets.MiniMessage class
gadgets.MiniMessage = function(opt_moduleId, opt_container) {};
gadgets.MiniMessage.createDismissibleMessage = function(message, opt_callback) {};
gadgets.MiniMessage.createStaticMessage = function(html) {
    var d = document.createElement("div");
    d.innerHTML = html;
    return d;
};
gadgets.MiniMessage.createTimerMessage = function(message, seconds, opt_callback) {};
gadgets.MiniMessage.dismissMessage = function(message) {};

//deprecated functions (old versions compatibility)
function _IG_MiniMessage() { return new gadgets.MiniMessage(); }








   
/*
//gadgets.json class
gadgets.json = {

    stringify:function(v)  {},
    parse:function(text) {}

}   
*/
  gadgets.json = function () {

  /**
   * Formats integers to 2 digits.
   * @param {Number} n
   */
  function f(n) {
    return n < 10 ? '0' + n : n;
  }

  Date.prototype.toJSON = function () {
    return [this.getUTCFullYear(), '-',
           f(this.getUTCMonth() + 1), '-',
           f(this.getUTCDate()), 'T',
           f(this.getUTCHours()), ':',
           f(this.getUTCMinutes()), ':',
           f(this.getUTCSeconds()), 'Z'].join("");
  };

  // table of character substitutions
  var m = {
    '\b': '\\b',
    '\t': '\\t',
    '\n': '\\n',
    '\f': '\\f',
    '\r': '\\r',
    '"' : '\\"',
    '\\': '\\\\'
  };

  /**
   * Converts a json object into a string.
   */
  function stringify(value) {
    var a,          // The array holding the partial texts.
        i,          // The loop counter.
        k,          // The member key.
        l,          // Length.
        r = /["\\\x00-\x1f\x7f-\x9f]/g,
        v;          // The member value.

    switch (typeof value) {
    case 'string':
    // If the string contains no control characters, no quote characters, and no
    // backslash characters, then we can safely slap some quotes around it.
    // Otherwise we must also replace the offending characters with safe ones.
      return r.test(value) ?
          '"' + value.replace(r, function (a) {
            var c = m[a];
            if (c) {
              return c;
            }
            c = a.charCodeAt();
            return '\\u00' + Math.floor(c / 16).toString(16) +
                (c % 16).toString(16);
            }) + '"'
          : '"' + value + '"';
    case 'number':
    // JSON numbers must be finite. Encode non-finite numbers as null.
      return isFinite(value) ? String(value) : 'null';
    case 'boolean':
    case 'null':
      return String(value);
    case 'object':
    // Due to a specification blunder in ECMAScript,
    // typeof null is 'object', so watch out for that case.
      if (!value) {
        return 'null';
      }
      // toJSON check removed; re-implement when it doesn't break other libs.
      a = [];
      if (typeof value.length === 'number' &&
          !(value.propertyIsEnumerable('length'))) {
        // The object is an array. Stringify every element. Use null as a
        // placeholder for non-JSON values.
        l = value.length;
        for (i = 0; i < l; i += 1) {
          a.push(stringify(value[i]) || 'null');
        }
        // Join all of the elements together and wrap them in brackets.
        return '[' + a.join(',') + ']';
      }
      // Otherwise, iterate through all of the keys in the object.
      for (k in value) if (value.hasOwnProperty(k)) {
        if (typeof k === 'string') {
          v = stringify(value[k]);
          if (v) {
            a.push(stringify(k) + ':' + v);
          }
        }
      }
      // Join all of the member texts together and wrap them in braces.
      return '{' + a.join(',') + '}';
    }
  }

  return {
    stringify: stringify,
    parse: function (text) {
      if (/^[\],:{}\s]*$/.test(text.replace(/\\["\\\/b-u]/g, '@').
          replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
          replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
        return eval('(' + text + ')');
      }
      return false;
    }
  };
}(); 
   
   
   
   
   
   
   
   
   
//gadgets.rpc class
gadgets.rpc = {
    call:function(targetId, serviceName, callback, var_args) {},
    register:function(serviceName, handler) {},
    registerDefault:function(handler) {},
    unregister:function(serviceName) {},
    unregisterDefault:function() {}
}



gadgets.io = function() {};
gadgets.io.makeNonProxiedRequest = function(relativeUrl, callback, opt_params, opt_contentType) {
      var params = opt_params || {};
      parent.getXml(relativeUrl,callback,"json",opt_params,"POST"); 
};
gadgets.io.makeRequest = function(url, callback, opt_params) {
        _IG_FetchXmlContent(url,callback,opt_params);
};
gadgets.io.encodeValues = function(fields) {
    return $p.gadgets.util.escapeString(fields);
};
gadgets.io.getProxyUrl = function(url, opt_params) {};
gadgets.io.RequestParameters = gadgets.util.makeEnum(
                                                        [
                                                          "METHOD",
                                                          "CONTENT_TYPE",
                                                          "POST_DATA",
                                                          "HEADERS",
                                                          "AUTHORIZATION",
                                                          "NUM_ENTRIES",
                                                          "GET_SUMMARIES",
                                                          "GET_FULL_HEADERS",
                                                          "REFRESH_INTERVAL",
                                                          "OAUTH_SERVICE_NAME",
                                                          "OAUTH_USE_TOKEN",
                                                          "OAUTH_TOKEN_NAME",
                                                          "OAUTH_REQUEST_TOKEN",
                                                          "OAUTH_REQUEST_TOKEN_SECRET",
                                                          "OAUTH_RECEIVED_CALLBACK"
                                                        ]
                                                   );

gadgets.io.MethodType = gadgets.util.makeEnum( 
                                                [
                                                  "GET", 
                                                  "POST", 
                                                  "PUT", 
                                                  "DELETE", 
                                                  "HEAD"
                                                ]
                                             );

gadgets.io.ContentType = gadgets.util.makeEnum(
                                                [
                                                    "TEXT", 
                                                    "DOM", 
                                                    "JSON", 
                                                    "FEED"
                                                ]
                                              );

gadgets.io.AuthorizationType = gadgets.util.makeEnum(
                                                        [
                                                            "NONE", "SIGNED", "OAUTH"
                                                        ]
                                                    );

                                                    
function parseUrlParams() {
    // Get settings from url, 'hash' takes precedence over 'search' component
    // don't use document.location.hash due to browser differences.
    var query;
    var l = document.location.href;
    var queryIdx = l.indexOf("?");
    var hashIdx = l.indexOf("#");
    if (hashIdx === -1) {
      query = l.substr(queryIdx + 1);
    } else {
      // essentially replaces "#" with "&"
      query = [l.substr(queryIdx + 1, hashIdx - queryIdx - 1), "&",
               l.substr(hashIdx + 1)].join("");
    }
    return query.split("&");
}








function nofunction( selDiv ) {}

/*

    Function: _bringToFront
            
		bring widjet to front

    Parameters:
	 
		v_uniq -the uniq id of the widget
		
 */
function _bringToFront(v_uniq) {
	var l_tab=parent.$p.app.tabs.sel;
	var l_mod=parent.$p.app.widgets.uniqToId(uniq,l_tab);
	parent.tab[l_tab].module[l_mod].bringToFront();
}

function _gel(v_id){return document.getElementById?(document.getElementById(v_id)?document.getElementById(v_id):null):document.all[v_id];}
function _gelstn(v_t){return document.getElementsByTagName?document.getElementsByTagName(v_t):new Array();}

function _esc(v_s){return parent._esc(v_s);}
function _unesc(v_s){return parent._unesc(v_s);}
function _uc(v_s){return parent._uc(v_s);}
function _lc(v_s){return parent._lc(v_s);}
function _min(v1,v2){return parent._min(v1,v2);}
function _max(v1,v2){return parent._max(v1,v2);}
function _hesc(v_s){return parent._hesc(v_s);}
function _args(v_s){return parent._args(v_s);}
function _trim(v_s){return parent._trim(v_s);}



/*

    Function: navPrint
            
		replace the content of an element

    Parameters:
	 
		v_id - id of the element
		v_s (string)- new content 
		
 */
function navPrint(v_id,v_s) {
	var l_obj=_gel(v_id);
	if (l_obj) l_obj.innerHTML=v_s;
}
/*

    Function: navClass
            
		Change CSS Class of an object

    Parameters:
	 
		v_id - id of the element
		v_class - new class
		
 */
function navClass(v_id,v_class) {
	var l_obj=_gel(v_id);
	if (l_obj) l_obj.className=v_class;
}
/*

    Function: navWait
            
		Display waiting icon in the defined object

    Parameters:
	 
		v_id - id of the element
		
 */
function navWait(v_id) {
	navPrint(v_id,'<img src="../images/ico_waiting.gif" />');
}
/*

    Function: navShow
            
		Show/Hide object

    Parameters:
	 
		v_id - id of the element
		v_disp - display or neot the element
		
 */
function navShow(v_id,v_disp) {
	var l_obj=_gel(v_id);
	if (l_obj) l_obj.style.display=v_disp;
}
/*

    Function: navIsShown
            
		say if the object is visible or not

    Parameters:
	 
		v_id - id of the element
			
	Returns:
		
		true if the object is visible
		false if it's not visible
		
 */
function navIsShown(v_id) {
	var l_obj=_gel(v_id);
	if (l_obj)
	{
		return (l_obj.style.display=='block'?true:false);
	}
	else
	{
		return false;
	}
	l_obj.style.display=v_disp;
}
/*

    Function: _toggle
            
		Show an object if it's hide, hide it if it's visible

    Parameters:
	 
		v_el - the element
		
 */
function _toggle(v_el)
{
	if (v_el.style.display=='block') {
		v_el.style.display='none';
	}
	else {
		v_el.style.display='block';
	}
}







/*

    Function: _IG_Callback
            
		Callback function

    Parameters:
	 
		v_fct - the callback function
		v1,v2,v3,v4,v5 - arguments
		
 */
function _IG_Callback(v_fct,v1,v2,v3,v4,v5) {
	var args=arguments;
	return function()
	{
		var l_vars=[];
		for(var i=0;i<arguments.length;i++)
		{
			l_vars[l_vars.length]=arguments[i];
		}
		for(var i=1;i<args.length;i++)
		{
			l_vars[l_vars.length]=args[i];
		}
		v_fct.apply(null,l_vars);
	}
}
 /*

    Function: _IG_GetImage
            
		get the url of an image

    Parameters:
	 
		v_url the image url
			
	Returns
	
		the url of the image
 */
function _IG_GetImage(v_url) {
	return v_url;
}
/*

    Function: _IG_FetchContent
            
		Get XML results (text)

    Parameters:
	 
		v_url (string) - url of the XML page containing data to retrieve
		v_fct(function) - callback function that will treat the results. responseXML and fct_vars are the arguments sent to this function.

 */
function _IG_FetchContent(v_url, v_fct) {
	parent.getXml(v_url,v_fct,"","html","","GET");
}
/*

    Function: _IG_FetchXmlContent
            
		Get XML results (xml)

    Parameters:
	 
		v_url (string) - url of the XML page containing data to retrieve
		v_fct(function) - callback function that will treat the results. responseXML and fct_vars are the arguments sent to this function.
		v_vars(string) - variables sent to the xml page
		v_type (string) - "post"=send v_vars as post variables, "get" ...

 */
function _IG_FetchXmlContent(v_url, v_fct,v_var,v_type) {
	if (v_var==indef) v_var="";
	if (v_type==indef) v_type="GET";
	parent.getXml(v_url,v_fct,"","xml",v_var,v_type);
}
/*

    Function: _IG_FetchFeedAsJSON
            
		Get XML results (xml) from an RSS feed

    Parameters:
	 
		v_url (string) - url of the XML page containing data to retrieve
		v_fct(function) - the function to execute on this page
		v_enties - number of articles to display
		v_summaries - for sumaries display

 */
function _IG_FetchFeedAsJSON(v_url,v_fct,v_entries,v_summaries) {
	if (v_entries==indef) v_entries=5;
	if (v_summaries==indef) v_summaries=false;
	parent.getXml(v_url,getRssFromXml,new Array(v_fct,v_entries,v_summaries),"xml","","GET");
}
/*

    Function: _IG_FetchFeedAsJSON
            
		????????????

    Parameters:
	 
		document - ?????
		mousemove - ???????
		id - ?????
 */
function _IG_AddDOMEventHandler(document, mousemove, id) { }
/*

    Function: getRssFromXml
            
		launch a function with the xml results in inputs

    Parameters:
	 
		response - xml get
		vars - (v_fct - v_enties - v_summaries)

 */
function getRssFromXml(response,vars) {
	var feed={};
	feed.Title=parent.getXMLval(response,"title","str",false,"no title");
	feed.Link=parent.getXMLval(response,"link","str",false,"");
	feed.Author=parent.getXMLval(response,"author","str",false,"");
	feed.Description=parent.getXMLval(response,"description","str",false,"");
	feed.Entry=[];
	var i=0;
	while (response.getElementsByTagName("item")[i] && i<vars[1])
	{
		var result=response.getElementsByTagName("item")[i];
		feed.Entry[i]={};
		feed.Entry[i].Title=parent.getXMLval(result,"title","str",false,"no title");
		feed.Entry[i].Link=parent.getXMLval(result,"link","str",false,"");
		feed.Entry[i].Summary=(parent.getXMLval(result,"description","str",false,"")).substr(0,200);
		feed.Entry[i].Date=parent.getXMLval(result,"pubdate","str",false,"");
		i++;
	}
	vars[0](feed);
}
/*

    Function: _IG_GetCachedUrl
            
		get the url of the cache

    Parameters:
	 
		v_url the cache url
			
	Returns
	
		the url of the cache
 */
function _IG_GetCachedUrl(v_url) {
	return v_url;
}

function _IG_RegisterMaximizeHandler () {}
function _IG_Analytics(v1,v2){}
function reportPageview() {}
function _IG_GA() {}


if (typeof($p) != 'object') $p={};
if (typeof($p.app) != 'object') $p.app={};
if (typeof($p.app.widgets) != 'object') $p.app.widgets={};
$p.modules={
    tooltip:function(v_msg) {
        return "<a href='#' onclick='return false' onmouseover=\"parent.mouseBox('hello'),event)\" onmouseout=\"parent.mouseBox('')\">"+$p.img("ico_help_s.gif",12,12,"","imgmid")+"</a>";
    }

}