appdb.components = {};
appdb.Component = appdb.DefineClass("appdb.Component",function(o){
    this._mediator = null;
    this.ErrorHandler = new appdb.views.ErrorHandler();
    this.subscribe = null;
    this.publish = null;
    this.unsubscribe = null;
    this.unsubscribeAll = null;
    this.clearObserver = null;
    this.views = {};
    this._model = null;
    this._title = "";
    this._dom = null;
    this.ext = (o)?(o.ext || {}):{};
    this.getComponentType = function(){
        return this._type_.getName();
    };
    this.getComponentName = function(){
        var n = this.getComponentType();
        n = n.split(".");
        return n[n.length-1];
    };
    this.getComponentTitle = function(){
        return this._componentTitle;
    };
    this.setComponentTitle = function(v){
        this._componentTitle = v;
        return this;
    };
    this.clearEvents = function(){
        var i, v = this.views;
        for(i in v){
            if(v[i].unsubscribeAll){
                v[i].unsubscribeAll(this);
            }
        }
        if(this._model){
            this._model.unsubscribeAll(this);
        }
        return this;
    };
    this.getModel = function(){
        return this._model || null;
    };
    this.setModel = function(v){
        this._model = v;
        return this;
    };
    this.reload = function(o){
        this._model.get(o);
    };
    this.destroy = function(){
        var i, v = this.views;
        for(i in v){
            if(v[i].destroy){
                v[i].destroy();
            }
        }
        if(this._model){
            this._model.destroy();
        }
        this._mediator.clearAll();
        if(this._dom){
            $(this._dom).empty();
        }
        return this;
    };
    this.setState = function(v){};
    this.getState = function(){return null;};
	this.displayType = (function(parent){
		var dt = 'inline';
		return function(v){
			if(typeof v === "string"){
				dt = v;
				return parent;
			}
			return dt;
		};
	})(this);
    this.setViewsParent = function(p){
        p = p || this;
       for(var i in this.views){
           this.views[i].parent = p;
       }
    };
    var _constructor = function(){
            this._mediator = new appdb.utils.ObserverMediator(this);
            this.subscribe = this._mediator.subscribe;
            this.publish = this._mediator.publish;
            this.unsubscribe = this._mediator.unsubscribe;
            this.unsubscribeAll = this._mediator.unsubscribeAll;
            this.clearObserver = this._mediator.clearAll;
            this._componentTitle = this.getComponentName();
        };
    _constructor.call(this);
});
appdb.components.People = appdb.ExtendClass(appdb.Component,"appdb.components.People",function(o){
    o = o || {};
    this.ext = o.ext || {};
	this.isLoaded = true;
    this._baseQuery = this.ext.baseQuery || null;
    this._getFullQuery = function(v){
        var res;
        if(typeof v === "string"){
            if( this._baseQuery){
                res = '' + v;
                res = v + " " + this._baseQuery.flt;
                return res;
            }else{
                return v;
            }
        }
        return {};
    };
    this._getUserQuery = function(v){
        var res,bqi,bq,f;
        if(v && this._baseQuery && this._baseQuery.flt){
            res = $.extend({},v);
            f = res.flt;
            bq = ''+this._baseQuery.flt;
            bqi = f.indexOf(bq)
            if(bqi>=0){
                f = f.substring(0,bqi);
                if(f[f.length-1]===" "){
                    f = f.substring(0,f.length-1);
                }
            }
            res.flt = f;
            return res;
        }
        return v;
    };
    this.render = function(d,p,t){
        var start = (new Date()).getTime(), v = this.views, _dom = this.dom, qvalue=this._model.getQuery();
        var len = ((d)?(typeof d.length==="number")?d.length:len:0);
        var ofs = (p)?(typeof p.pageoffset==="number")?p.pageoffset:ofs:0;
        $(_dom).empty();
        v.peopleList.render(d);
        if(typeof len === "undefined"){
            if(ofs===0){
                v.pagerview.reset();
            }else{
                v.pagerview.render(p);
            }
            v.ordering.reset();
            v.viewbuttons.reset();
        }else if(len===0){
            v.pagerview.reset();
            v.ordering.reset();
            v.viewbuttons.reset();
        }else{
            v.pagerview.render(p);
            v.ordering.render(qvalue);
            v.viewbuttons.render();
        }
        v.filtering.setWatermark(this.ext.filterDisplay);
        v.filtering.setValue(this.ext.userQuery);
        v.filtering.render();
        v.atom.render(qvalue.flt);
        v._export.setValue(qvalue.flt);
        v._export.render();
        v.resulttimer.render(p.count,t);
		v.permalink.render({query:this.ext.baseQuery || qvalue,ext:this.ext});
		var end = (new Date()).getTime();
        if ( appdb.config.appenv != 'production' ) {
            v.resulttimer.appendRender(end-start);
        }
    };
    this.load = function(o){
        this.clearEvents();
        var v = this.views;
		this.isLoaded = true;
        this.ext = o.ext || {};
		if(this.ext.mainTitle){
            this.setComponentTitle(this.ext.mainTitle);
        }
        var _base ;
        v.filtering.setWatermark(this.ext.filterDisplay);
        if(this.ext.baseQuery && this.ext.baseQuery.flt){
            _base = $.extend({},this.ext.baseQuery);
            if(_base.flt[0]!=="+"){
                _base.flt = "+" + _base.flt;
            }
            this._baseQuery = $.extend({},_base);
            if(o.query && o.query.flt){
                o.query =  $.extend({},_base);
                if(this.ext.userQuery){
                    o.query.flt = this.ext.userQuery.flt + " " + o.query.flt;
                }
            }
        }else{
            this._baseQuery = null;
            this.ext.userQuery = o.query;
        }
		var query = o.query || {};
		if(this.views.ordering && this.views.ordering.getSelected()!==null){
		 if(typeof query.orderby === "undefined" && typeof query.orderbyOp === "undefined"){
		  this.views.ordering.resetSelected();
		 }
		 this.views.ordering.setSelected(query.orderby,query.orderbyOp);
		}
        this._model = new appdb.model.People(query);
        this._model.subscribe({event:"beforeselect",callback:function(){
                this.views.loading.show();
            },caller:this});
        this._model.subscribe({event:"error",callback:function(err){
                this.views.loading.hide();
                this.ErrorHandler.handle({status:"Data transfer error",description:"An error occured during application list data transfer",source : err});
            },caller:this});
        v.pager = this._model.getPager().subscribe({event:'pageload',callback:function(d){
			this.render(d.data,d.pager,d.elapsed);
			this.views.loading.hide();
            $(this._dom).show();
			if(this.isLoaded == false){
			 appdb.Navigator.internalCall(appdb.Navigator.Registry["People"],{query:this._model.getQuery(),ext:this.ext});
			}else{
			 appdb.Navigator.setTitle(appdb.Navigator.Registry["People"],[this._model.getQuery(),this.ext]);
			}
		   this.isLoaded = false;
           this.publish({event:'loaded',value:{}});
        },caller : this});
		v.pager.current(); 
        v.pagerview.subscribe({event:"next",callback : function(){
            this.views.pager.next();
        }, caller : this});
        v.pagerview.subscribe({event:"previous",callback : function(){
            this.views.pager.previous();
        }, caller : this});
        v.pagerview.subscribe({event:"current",callback : function(v){
            this.views.pager.current(v);
        }, caller : this});
        v.ordering.subscribe({event:"order",callback:function(v){
            this._model.get(v);
        },caller : this});
        v.filtering.subscribe({event:"filter",callback:function(v){
            this.ext.userQuery = {flt:v.flt};
            v.flt = this._getFullQuery(v.flt);
            if(v.flt !== this._model.getQuery().flt){
                this.views._export.setValue(v.flt);
                this.views._export.render();
                this._model.get(v);
            }
        },caller: this});
        v.peopleList.subscribe({event:"itemclick",callback:function(data){
            var p ,s = this.views.pager.getCurrentPagingState();
            if(s.pagenumber>0){
                p = {pagelength:s.length,pageoffset: s.offset};
            }
            appdb.views.Main.showPerson({id:data.id},{mainTitle : data.firstname + " " + data.lastname,append:true,previousPager:p}); //else showPplDetails("people/details?id="+d.id);
        },caller:this});
    };
    this._init = function(){
        var v = {};
        if(this.ext.mainTitle){
            this.setComponentTitle(this.ext.mainTitle);
        }
        v.peopleList = new appdb.views.PeopleList({container : "ul#pplmainlist"});
        v.pagerview = new appdb.views.PagerPane({container : "ppl_paging"});
        v.filtering = new appdb.views.Filter({
            container : "ppl_filter",
            rich : true,
            watermark : this.ext.filterDisplay
        });
        if(this.ext.userQuery){
            v.filtering.setValue(this.ext.userQuery);
        }
        v.ordering = new appdb.views.Ordering({
            container : "ppl_orderby",
            selected : "firstname",
            items : [
                {name : "First Name" , value : "firstname"},
                {name : "Last Name" , value : "lastname"},
                {name : "ID" , value : "id"},
                {name : "Date" , value : "dateinclusion"},
                {name : "Unsorted" , value : "unsorted"}
            ]
        });
        v.resulttimer = new appdb.views.ResultTimer({container : $("#ppl_result_timer")});
        v.loading = new appdb.views.DelayedDisplay($("#ppl_loading"));
        v.viewbuttons = new appdb.views.ListViewMode({container : $("#ppl_viewbuttons"),list : "ul#pplmainlist"});
        v._export = new appdb.views.Export({container : $("#pplexportdiv"), target:'people'});
        v.permalink = new appdb.views.Permalink({container : $("#ppl_permalink"), datatype:"people"});
        v.atom = new appdb.views.NewsFeed({container : $("#ppl_atomfeed"),type:"ppl"});
		this.views = v;
        this.setViewsParent(this);
    };
    this._init();
});

appdb.components.Applications = appdb.ExtendClass(appdb.Component,"appdb.components.Applications",function(o){
    o = o || {};
    this._apptype = null;
	this.isLoaded = false;
    this.ext = o.ext || {};
    this._baseQuery = this.ext.baseQuery || null;
    this._getFullQuery = function(v){
        var res;
        if(typeof v === "string"){
            if( this._baseQuery){
                res = '' + v;
                res = v + " " + this._baseQuery.flt;
                return res;
            }else{
                return v;
            }
        }
        return {};
    };
    this._getUserQuery = function(v){
        var res,bqi,bq,f;
        if(v && this._baseQuery && this._baseQuery.flt){
            res = $.extend({},v);
            f = res.flt;
            bq = ''+this._baseQuery.flt;
            bqi = f.indexOf(bq)
            if(bqi>=0){
                f = f.substring(0,bqi);
                if(f[f.length-1]===" "){
                    f = f.substring(0,f.length-1);
                }
            }
            res.flt = f;
            return res;
        }
        return v;
    };
    this._componentTitle = "Applications";
    this.render = function(d,p,t){
        var start = (new Date()).getTime(), v = this.views, qvalue = this._model.getQuery();
        var len = (d)?(typeof d.length==="number")?d.length:len:0;
        var ofs = (p)?(typeof p.pageoffset==="number")?p.pageoffset:ofs:0;
        $(this._dom).empty();
        v.appsList.render(d);
        if(typeof len === "undefined"){
            if(ofs===0){
                v.pagerview.reset();
            }else{
                v.pagerview.render(p);
            }
            v.ordering.reset();
            v.viewbuttons.render();
        } else if(len===0){
            v.pagerview.reset();
            v.ordering.reset();
            v.viewbuttons.reset();
        }else{
            v.pagerview.render(p);
            v.ordering.render(qvalue);
            v.viewbuttons.render();
        }
        v.filtering.setWatermark(this.ext.filterDisplay);
        v.filtering.setValue(this.ext.userQuery);
        v.filtering.render();
        if(this._apptype===null){
            v._export.setValue(qvalue.flt);
            v._export.render();
            v.atom.render({flt : (qvalue.flt || ""), title : this.getComponentTitle() + " news feed"});
            $(".listtoolbox").show();
        }else{
            v._export.destroy();
            v.atom.destroy();
			v.mail.destroy();
            $(".listtoolbox").hide();
        }
        v.resulttimer.render(p.count,t);
        v.permalink.render({query:this.ext.baseQuery || qvalue,ext:this.ext});
        var end = (new Date()).getTime();
        if ( appdb.config.appenv != 'production' )   v.resulttimer.appendRender(end-start);
    };
    this.load = function(d){
		this.clearEvents();
        d = d || {};
		this.isLoaded = true;
		this.navigationType = "";
        this.ext = d.ext || {};
        var v = this.views;
        var _base ;
         if(this.ext.mainTitle){
            this.setComponentTitle(this.ext.mainTitle);
        }
        if(this.ext.baseQuery && this.ext.baseQuery.flt){
            _base = $.extend({},this.ext.baseQuery);
            if(_base.flt[0]!=="+"){
                _base.flt = "+" + _base.flt;
            }
            this._baseQuery = $.extend({},_base);
            if(d.query && d.query.flt){
                d.query =  $.extend({},_base);
                if(this.ext.userQuery){
                    d.query.flt = this.ext.userQuery.flt + " " + d.query.flt;
                }
            }
        }else{
            this._baseQuery = null;
            this.ext.userQuery = d.query
        }
        this._apptype = "o.query.applicationtype";
        var query = d.query || {};
		if(this.views.ordering && this.views.ordering.getSelected()!==null){
		 if(typeof query.orderby === "undefined" && typeof query.orderbyOp === "undefined"){
		  this.views.ordering.resetSelected();
		 }
		 this.views.ordering.setSelected(query.orderby,query.orderbyOp);
		}
        switch(query.applicationtype){
			case "related":
				this._model = new appdb.model.RelatedApplications(query,this.ext);
                v.filtering.setWatermark(d.query.applicationtype);
				this.navigationType = "RelatedApps";
				break;
            case "moderated":
				this.navigationType = (this.navigationType=="")?"Moderated":this.navigationType;
            case "deleted":
                this._model = new appdb.model.Applications(query);
                v.filtering.setWatermark(d.query.applicationtype);
				this.navigationType = (this.navigationType=="")?"Deleted":this.navigationType;
                break;
            case "bookmarked":
				this.navigationType = (this.navigationType=="")?"Deleted":this.navigationType;
            case "editable":
				this.navigationType = (this.navigationType=="")?"Editable":this.navigationType;
            case "associated":
				this.navigationType = (this.navigationType=="")?"Associated":this.navigationType;
            case "owned":
                this._model = new appdb.model.PeopleApplications(query);
                v.filtering.setWatermark(d.query.applicationtype);
				this.navigationType = (this.navigationType=="")?"Owned":this.navigationType;
                break;
            default:
                this._model = new appdb.model.Applications(query);
                v.filtering.setWatermark(this.ext.filterDisplay);
                this._apptype = null;
				this.navigationType = "Applications";
                delete d.query.applicationtype;
                break;
        }
        this._model.subscribe({event:"beforeselect",callback:function(){
                this.views.loading.show();
            },caller:this});
        this._model.subscribe({event:"error",callback:function(err){
                this.views.loading.hide();
                this.ErrorHandler.handle({status:"Data transfer error",description:"An error occured during application list data transfer",source : err});
            },caller:this});
        v.pager = this._model.getPager().subscribe({event:'pageload',callback:function(d){
            this.render(d.data,d.pager,d.elapsed);
            this.views.loading.hide();
            $(this._dom).show();
            if(typeof query.applicationtype === "undefined"){
                    this.views.mail.load({flt: (query.flt || ""), title : this.getComponentTitle() + " news"});
                }
				 if(this.isLoaded == false){
				  appdb.Navigator.internalCall(appdb.Navigator.Registry[this.navigationType],{query:this._model.getQuery(),ext:this.ext});
				 }else{
				  appdb.Navigator.setTitle(appdb.Navigator.Registry[this.navigationType],[this._model.getQuery(),this.ext]);
				 }
				this.isLoaded = false;
            this.publish({event:'loaded',value:{}});
        },caller : this});
		v.pager.current(); 
        v.pagerview.subscribe({event:"next",callback : function(){
             this.views.pager.next();
        }, caller : this});
        v.pagerview.subscribe({event:"previous",callback : function(){
             this.views.pager.previous();
        }, caller : this});
        v.pagerview.subscribe({event:"current",callback : function(v){
            this.views.pager.current(v);
        }, caller : this});
        v.ordering.subscribe({event:"order",callback:function(v){
            this._model.get(v);
        },caller : this});
        v.filtering.subscribe({event:"filter",callback:function(v){
            this.ext.userQuery = {flt:v.flt};
            v.flt = this._getFullQuery(v.flt);
            if(v.flt !== this._model.getQuery().flt){
                if(this._apptype===null){
                    this.views._export.setValue(v.flt);
                    this.views._export.render();
                }
                this._model.get(v);
            }
        },caller : this});
        v.appsList.subscribe({event:"itemclick",callback: function(data){
            var p ,s = this.views.pager.getCurrentPagingState();
            if(s.pagenumber>0){
                p = {previousPager: {pagelength:s.length,pageoffset: s.offset}};
            }
            appdb.views.Main.showApplication(data,p);
        },caller:this});
    };
    this._init = function(){
        var v = {};
        v.appsList = new appdb.views.AppsList({container : "ul#appmainlist"});
        v.pagerview = new appdb.views.PagerPane({container:"apps_paging"});
         v.filtering = new appdb.views.Filter({
            container : "apps_filter",
            rich : true,
            watermark : this.ext.filterDisplay
        });
        if(this.ext.userQuery){
            v.filtering.setValue(this.ext.userQuery);
        }
        v.ordering = new appdb.views.Ordering({
            container : "apps_orderby",
            selected : "name",
            items : [
                {name : "Name" , value : "name"},
                {name : "Date" , value : "dateadded"},
                {name : "ID" , value : "id"},
                {name : "Rating", value : "rating", operation : "NULLS LAST"},
                //{name : "Popularity", value : "app_popularity(applications.id)"},
                {name : "Most visited", value: "hitcount"},
                {name : "Unsorted" , value : "unsorted"}
            ]
        });
        v.resulttimer = new appdb.views.ResultTimer({container:$("#apps_result_time")});
        v.loading = new appdb.views.DelayedDisplay($("#apps_loading"));
        v.viewbuttons = new appdb.views.ListViewMode({container: $("#apps_viewbuttons"),list : "ul#appmainlist"});
        v._export = new appdb.views.Export({container : $("#exportdiv"),target:'apps'});
        v.permalink = new appdb.views.Permalink({container:$("#apps_permalink"),datatype:"apps"});
        v.atom = new appdb.views.NewsFeed({container : $("#apps_atomfeed"),feed:{type:"app",title:"Applications news feed",flt:""},customizable:true});
		v.mail = new appdb.components.MailSubscription({container : $("#apps_mailfeed")});
        this.views = v;
        this.setViewsParent(this);
    };
    this._init();
});

appdb.components.VOs = appdb.ExtendClass(appdb.Component,"appdb.components.VOs",function(o){
    o = o || {};
    this.ext = o.ext || {};
	this.isLoaded = false;
    this._baseQuery = this.ext.baseQuery || null;
    this._getFullQuery = function(v){
        var res;
        if(typeof v === "string"){
            if( this._baseQuery){
                res = '' + v;
                res = v + " " + this._baseQuery.domain;
                return res;
            }else{
                return v;
            }
        }
        v = $.extend($.extend({},this._baseQuery),v);
        return v;
    };
    this._getUserQuery = function(v){
        var res,bqi,bq,f;
        if(v && this._baseQuery && this._baseQuery.domain){
            res = $.extend({},v);
            f = res.flt;
            bq = ''+this._baseQuery.domain;
            bqi = f.indexOf(bq)
            if(bqi>=0){
                f = f.substring(0,bqi);
                if(f[f.length-1]===" "){
                    f = f.substring(0,f.length-1);
                }
            }
            res.domain = f;
            return res;
        }
        return v;
    };
    this._componentTitle = "Virtual Organizations";
    this.render = function(d,p,t){
        var start = (new Date()).getTime(), v = this.views, _dom = this.doms, qvalue=this._model.getQuery();
        var len = ((d)?(typeof d.length==="number")?d.length:len:0);
        var ofs = (p)?(typeof p.pageoffset==="number")?p.pageoffset:ofs:0;
        $(_dom).empty();
        v.vosList.render(d);
        if(typeof len === "undefined"){
            if(ofs===0){
                v.pagerview.reset();
                v.viewbuttons.reset();
            }else{
                v.pagerview.render(p);
                v.viewbuttons.render();
            }
        }else if(len===0){
            v.pagerview.reset();
            v.viewbuttons.reset();
        }else{
            v.pagerview.render(p);
            v.viewbuttons.render();
        }
        v.filtering.setWatermark(this.ext.filterDisplay);
        v.filtering.setValue(this.ext.userQuery);
        v.filtering.render();
        v.resulttimer.render(p.count,t);
		v.permalink.render({query:this.ext.baseQuery || qvalue,ext:this.ext});
		var end = (new Date()).getTime();
        if ( appdb.config.appenv != 'production' ) {
            v.resulttimer.appendRender(end-start);
        }
    };
    this.load = function(o){
        var v = this.views;
        this.clearEvents();
		this.isLoaded = true;
        this.ext = o.ext || {};
        if(this.ext.mainTitle){
            this.setComponentTitle(this.ext.mainTitle);
        }
        var _base ;
        v.filtering.setWatermark(this.ext.filterDisplay);
        if(this.ext.baseQuery){
            _base = $.extend({},this.ext.baseQuery);
            this._baseQuery = $.extend({},_base);
            if(o.query){
                o.query =  $.extend({},_base);
                if(this.ext.userQuery){
                    if(this.ext.userQuery.name ){
                        o.query.domain = this.ext.userQuery.domain || o.query.domain;
                    }
                    if(this.ext.userQuery.name){
                        o.query.name = this.ext.userQuery.name || o.query.name;
                    }
                }
            }
        }else{
            this._baseQuery = null;
            this.ext.userQuery = o.query;
        }
        this._model = new appdb.model.VOs(o.query);
        this._model.subscribe({event:"beforeselect",callback:function(){
                this.views.loading.show();
            },caller:this});
        this._model.subscribe({event:"error",callback:function(err){
                this.views.loading.hide();
                this.ErrorHandler.handle({status:"Data transfer error",description:"An error occured during application list data transfer",source : err});
            },caller:this});
        v.pager = this._model.getPager().subscribe({event:'pageload',callback:function(d){
            this.render(d.data,d.pager,d.elapsed);
            this.views.loading.hide();
            $(this._dom).show();
			if(this.isLoaded == false){
			 appdb.Navigator.internalCall(appdb.Navigator.Registry["VOs"],{query:this._model.getQuery(),ext:this.ext});
			}else{
			 appdb.Navigator.setTitle(appdb.Navigator.Registry["VOs"],[this._model.getQuery(),this.ext]);
			}
		   this.isLoaded = false;
           this.publish({event:'loaded',value:{}});
        },caller : this});
        v.pager.current();
        v.pagerview.subscribe({event:"next",callback : function(){
            this.views.pager.next();
        }, caller : this});
        v.pagerview.subscribe({event:"previous",callback : function(){
            this.views.pager.previous();
        }, caller : this});
        v.pagerview.subscribe({event:"current",callback : function(v){
            this.views.pager.current(v);
        }, caller : this});
        v.filtering.subscribe({event:"filter",callback:function(v){
            this.ext.userQuery = {name:v.name || ""};
            v = this._getFullQuery(v);
			if(v.name !== this._model.getQuery().name){
				this._model.get(v);
			}
        },caller: this});
        v.vosList.subscribe({event:"itemclick",callback:function(data){
            var p ,s = this.views.pager.getCurrentPagingState();
            if(s.pagenumber>0){
                p = {previousPager:{pagelength:s.length,pageoffset: s.offset}};
            }
            appdb.views.Main.showVO(data.name,p);
        },caller : this});
	   this.isLoaded = true;
    };
    this._init = function(){
        var v = {};
        v.vosList = new appdb.views.VOsList({container : "ul#vosmainlist"});
        v.pagerview = new appdb.views.PagerPane({container:"vos_paging"});
        v.filtering = new appdb.views.Filter({
            container : "vos_filter",
            rich : false,
            field : "name",
            watermark : this.ext.filterDisplay,
			displayClear : true
        });
        v.viewbuttons = new appdb.views.ListViewMode({container : $("#vos_viewbuttons"),list : "ul#vosmainlist"});
        v.resulttimer = new appdb.views.ResultTimer({container : $("#vos_result_timer")});
        v.loading = new appdb.views.DelayedDisplay($("#vos_loading"));
		v.permalink = new appdb.views.Permalink({container:$("#vos_permalink"),datatype:"vos"})
        this.views = v;
        this.setViewsParent(this);
    };
    this._init();
});
appdb.components.RelatedContacts = appdb.ExtendClass(appdb.Component,"appdb.components.RelatedContacts",function(o){
    o = o || {};
    this.ext = o.ext || {};
    this._baseQuery = this.ext.baseQuery || null;
    this._getFullQuery = function(v){
        var res;
        if(typeof v === "string"){
            if( this._baseQuery){
                res = '' + v;
                res = v + " " + this._baseQuery.flt;
                return res;
            }else{
                return v;
            }
        }
        return {};
    };
    this._getUserQuery = function(v){
        var res,bqi,bq,f;
        if(v && this._baseQuery && this._baseQuery.flt){
            res = $.extend({},v);
            f = res.flt;
            bq = ''+this._baseQuery.flt;
            bqi = f.indexOf(bq)
            if(bqi>=0){
                f = f.substring(0,bqi);
                if(f[f.length-1]===" "){
                    f = f.substring(0,f.length-1);
                }
            }
            res.flt = f;
            return res;
        }
        return v;
    };
    this.render = function(d,p,t){
        var start = (new Date()).getTime(), v = this.views, _dom = this.dom, qvalue=this._model.getQuery();
        var len = ((d)?(typeof d.length==="number")?d.length:len:0);
        var ofs = (p)?(typeof p.pageoffset==="number")?p.pageoffset:ofs:0;
		
		v.pagerview.reset();
		v.filtering.reset();
		d.permissions = {action : {id: 16}};
		v.peopleList.render(d);
		v.peopleList.EditMode(true);
        if(typeof len === "undefined"){
            if(ofs===0){
                v.pagerview.reset();
            }else if(p){
                v.pagerview.render(p);
            }
        }else if(len===0){
            v.pagerview.reset();
        }else if(p) {
            v.pagerview.render(p);
        }
        v.filtering.setWatermark(this.ext.filterDisplay);
        v.filtering.setValue(this.ext.userQuery);
        v.filtering.render();
    };
    this.load = function(o){
        this.clearEvents();
		if(appdb.components.RelatedContacts.Dialog!=null){
			appdb.components.RelatedContacts.Dialog.hide();
			appdb.components.RelatedContacts.Dialog.destroyRecursive(false);
		}
		appdb.components.RelatedContacts.Dialog = new dijit.Dialog({
					title: "Associate person to application",
					content: $(this.dom)[0],
					style: "width: 730px;height:550px;"
				});
		appdb.components.RelatedContacts.Dialog.show();
        var v = this.views;
        this.ext = o.ext || {};
        if(this.ext.mainTitle){
            this.setComponentTitle(this.ext.mainTitle);
        }
        var _base ;
        v.filtering.setWatermark(this.ext.filterDisplay);
        if(this.ext.baseQuery && this.ext.baseQuery.flt){
            _base = $.extend({},this.ext.baseQuery);
            if(_base.flt[0]!=="+"){
                _base.flt = "+" + _base.flt;
            }
            this._baseQuery = $.extend({},_base);
            if(o.query && o.query.flt){
                o.query =  $.extend({},_base);
                if(this.ext.userQuery){
                    o.query.flt = this.ext.userQuery.flt + " " + o.query.flt;
                }
            }
        }else{
            this._baseQuery = null;
            this.ext.userQuery = o.query;
        }
		var query = o.query || {};
        this._model = new appdb.model.People(query);
        this._model.subscribe({event:"beforeselect",callback:function(){
                this.views.loading.show();
            },caller:this});
        this._model.subscribe({event:"error",callback:function(err){
                this.views.loading.hide();
                this.ErrorHandler.handle({status:"Data transfer error",description:"An error occured during application list data transfer",source : err});
            },caller:this});
        v.pager = this._model.getPager().subscribe({event:'pageload',callback:function(d){
            this.render(d.data,d.pager,d.elapsed);
            this.views.loading.hide();
            $(this._dom).show();
           this.publish({event:'loaded',value:{}});
        },caller : this});
        v.pager.current();
        v.pagerview.subscribe({event:"next",callback : function(){
            this.views.pager.next();
        }, caller : this});
        v.pagerview.subscribe({event:"previous",callback : function(){
            this.views.pager.previous();
        }, caller : this});
        v.pagerview.subscribe({event:"current",callback : function(v){
            this.views.pager.current(v);
        }, caller : this});
        v.filtering.subscribe({event:"filter",callback:function(v){
            this.ext.userQuery = {flt:v.flt};
            v.flt = this._getFullQuery(v.flt);
            if(v.flt !== this._model.getQuery().flt){
                this._model.get(v);
            }
        },caller: this});
        v.peopleList.subscribe({event:"itemclick",callback:function(data){
            var p ,s = this.views.pager.getCurrentPagingState();
            if(s.pagenumber>0){
                p = {pagelength:s.length,pageoffset: s.offset};
            }
			data.item.isSelected(!data.item.isSelected());
        },caller:this});
		
    };
	this.closeDialog = function(){
		if(appdb.components.RelatedContacts.Dialog!=null){
			appdb.components.RelatedContacts.Dialog.hide();
			appdb.components.RelatedContacts.Dialog.destroyRecursive(false);
		}
		this.publish({event : "close",value:this});
		this.destroy();
	};
	this._initContainer = function(){
		var header = document.createElement("div"),  main = document.createElement("div"), loading = document.createElement("div"),
			footer = document.createElement("div"), filter = document.createElement("span"), preview = document.createElement("div"),
			pager = document.createElement("span"), list = document.createElement("ul"), actions = document.createElement("div");
		this.dom = document.createElement("div");
		$(this.dom).addClass("relatedcontactsadder").addClass("viewsearch");
		$(header).addClass("header");
		$(main).addClass("main");
		$(footer).addClass("footer");
		$(filter).addClass("filter").attr("id","filter");
		$(preview).addClass("preview");
		$(loading).addClass("loading");
		$(pager).addClass("pager").attr("id","pager");
		$(list).addClass("list").addClass("itemgrid");
		$(actions).addClass("actions");
		$(header).append(filter).append(loading).append(preview);
		$(main).append(pager).append(list);
		$(footer).append(actions);
		$(this.dom).append(header).append(main).append(footer);
		$(actions).append("<div class='okbutton'></div>").append("<div class='cancelbutton'></div>");
		
		new dijit.form.Button({
			label: "OK",
			style: "float:right;padding:5px;",
            onClick: (function(_this){
				return function() {
					_this.closeDialog();
				};
               
            })(this)
		},$(actions).find(".okbutton")[0]);
		new dijit.form.Button({
			label: "Cancel",
			style: "float:right;padding:5px;",
            onClick:  (function(_this){
				return function() {
					_this.views.peopleList.selectedDataItems.clear();
					_this.closeDialog();
				};
            })(this)
		},$(actions).find(".cancelbutton")[0]);
		$(preview).append("<span ><b>view :  </b></span>");
		$(preview).append("<a class='search focused' href='#' title='Search for contacts to associate with the application' >search</a><span> | </span>");
		$(preview).append("<a class='associated' href='#' title='View already associated contacts of the application' >associated</a><span> | </span>");
		$(preview).append("<a class='selected' href='#' title='Preview selected contacts' >selected</a>");

		$(preview).find("a.search:last").click((function(_this){return function(){
			$(_this.dom).addClass("viewsearch");
			$(_this.dom).find(".preview a").removeClass("focused");
			$(this).addClass("focused");
			_this._model.get();
		};})(this));
		$(preview).find("a.associated:last").click((function(_this){return function(){
			$(_this.dom).removeClass("viewsearch");
			$(_this.dom).find(".preview a").removeClass("focused");
			$(this).addClass("focused");
			_this.render(_this.views.peopleList.excludedDataItems.get());
		};})(this));
		$(preview).find("a.selected:last").click((function(_this){return function(){
			$(_this.dom).removeClass("viewsearch");
			$(_this.dom).find(".preview a").removeClass("focused");
			$(this).addClass("focused");
			_this.render(_this.views.peopleList.selectedDataItems.get());
		};})(this));
	};
    this._init = function(){
        var v = {};
        if(this.ext.mainTitle){
            this.setComponentTitle(this.ext.mainTitle);
        }
		this._initContainer();
        v.peopleList = new appdb.views.RelatedContactList({container : $(this.dom).find("ul.list:last")[0], permissions : {action : [{id:17}]}, canSetContactPoint : false, excluded : o.excluded, onExclude : function(li){
				$(li.dom).find(".item a").unbind("click").css({"cursor":"default"}).attr("title","Already associated with the application");
				$(li.dom).css({"cursor":"default"}).find(".item:last").append("<div class='info'>Already associated with the application</div>");
		}});
        v.pagerview = new appdb.views.PagerPane({container : $(this.dom).find(".pager:last")[0]});
        v.filtering = new appdb.views.Filter({
            container : $(this.dom).find(".filter:last")[0],
            rich : true,
            watermark : this.ext.filterDisplay
        });
        if(this.ext.userQuery){
            v.filtering.setValue(this.ext.userQuery);
        }
		v.loading = new appdb.views.DelayedDisplay({selector: $(this.dom).find(".loading:last")[0],usedefault:true});
        this.views = v;
        this.setViewsParent(this);
    };
    this._init();
},{
	Dialog : null
});
appdb.components.Person = appdb.ExtendClass(appdb.Component,"appdb.components.Person", function(o){
   this.parser = null;
   this.reset = function(){
       this.views.personInfo.hide();
       if(this.views.pubs){
           this.views.pubs.destroy();
       }
       if(this.views.personInfo){
           this.views.personInfo.destroy();
       }
   };
   this.startEditing = function(d){
        var i,len= this.views.personInfo.subviews.length,s;
        for(i=0;  i<len; i+=1){
            s = this.views.personInfo.subviews[i];
            if(s.startEdit){
                s.startEdit(d);
            }
        }
   };
   this.cancelEditing = function(d){
        var i,len= this.views.personInfo.subviews.length,s;
        for(i=0;  i<len; i+=1){
            s = this.views.personInfo.subviews[i];
            if(s.cancelEdit){
                s.cancelEdit(d);
            }
        }
   };
   this.render = function(d){
        this.reset();
	var start = new Date().getTime(), _this = this;
        if(d.publication && $.isArray(d.publication)===false){
            d.publication = [d.publication];
        }
        this.views.personInfo.render(d,function(){
            _this.views.personInfo.show();
            var tc = dijit.byId("personTabContainer");
            tc.selectChild(tc.getChildren()[0]);
            tc.resize();
        });
        this.views.pubs.render(d.publication);
        if($(".dijitTabContainer").length===0){
            dojo.parser.parse("ppl_details");
        }

        $("#editPerson").click(function(){
            if($(this).text()==="edit"){
                _this.startEditing(d);
                $(this).text("cancel");
            }else{
                _this.cancelEditing(d);
                $(this).text("edit");
            }
        });
        var end = new Date().getTime();
        end = end - start;
        if ( appdb.config.appenv != 'production' ) {
            $("#timer").text("Rendered in " + end + "ms");
        }
		this.views.permalink.render({query:this._model.getQuery(),ext:this.ext});
        appdb.views.Main.setNavigationTitle(d.firstname+' '+d.lastname);
   };
   this.load = function(o){
	   this.ext = o.ext || this.ext;
        this._model = new appdb.model.Person(o.query);
        this._model.subscribe({event:"select",callback:function(e){
                this.publish({event:'loaded',value:{}});
                this.render(e);
            },caller:this}).get();
        this._model.subscribe({event:"error",callback:function(e){
            alert("error at person loading of data");
        }});
   };
   this._init = function(){
       var v = {};
       v.personInfo = o.templatepane;
       $(o.container).append(v.personInfo.content);
       v.personInfo.hide();
       v.pubs = new appdb.views.Publications({container: "ppl_details_pubs"});
	   v.permalink = new appdb.views.Permalink({container: $("<span></span>"),datatype : "person"});//used to set appdb.config.permalink, not to be rendered
       this.views = v;
   };
   this._init();
},{
    setPrimaryContact : function(cid,elem){
        if(typeof cid === "undefined" || $.trim(cid)===''){
            return;
        }
        var model = new appdb.model.PrimaryContact();
        if(elem){
            model.subscribe({event : "beforeupdate", callback : function(){
                $(elem).empty().append('<img src="/images/ajax-loader-small.gif" alt="" width="12px" height="12px"  /><span >updating...</span>');
            }});
            model.subscribe({event : "update",callback: function(v){
                if(v.error){
                    appdb.model.PrimaryContact.userPrimaryContact = null;
                    appdb.model.PrimaryContact.userPrimaryContactId = null;
                    $(elem).empty().append("<span>Could not set primary contact. " + v.error + "</span>");
                }else{
                     appdb.model.PrimaryContact.userPrimaryContact = v.val();
                     appdb.model.PrimaryContact.userPrimaryContactId = v.id;
                    $(elem).empty().append("<span>Success</span>");
                }
            }});
            model.subscribe({event : "error", callback : function(){
                $(elem).empty().append("<span>Could not set the primary contact.</span>");
            }});
        }
        model.update({id:cid});
    },
    getPrimaryContact : function(clbck){
         var model = new appdb.model.PrimaryContact();
         model.subscribe({event : "select", callback : function(v){
                 if(v.error){
                    appdb.model.PrimaryContact.userPrimaryContact = null;
                    appdb.model.PrimaryContact.userPrimaryContactId = null;
                 }else{
                     appdb.model.PrimaryContact.userPrimaryContact = v.val();
                     appdb.model.PrimaryContact.userPrimaryContactId = v.id;
                 }
                 if(clbck){
                     clbck(v);
                 }
             }});
         model.get();
    },
    setDefaultNotification : function(enable,args,clbck){
        var model = new appdb.model.MailSubscription();
        model.subscribe({event : "remove", callback : clbck});
        model.subscribe({event : "insert", callback : function(v){
            if(clbck){clbck(v);}
            appdb.model.MailSubscription.defaultNotification = v;
        }});
        model.subscribe({event : "update", callback : clbck});
        model.subscribe({event : "error", callback : clbck});
        if(args && args.flt){
            args.flt =  appdb.utils.base64.encode(args.flt);
        }
        if(typeof enable==="undefined"){
            model.update(args);
        }else if(enable){
            model.insert(args);
        }else{
            model.remove(args);
        }
    },
    getDefaultNotification : function(clbck,args){
        args = appdb.utils.base64.encode(args);
        var model = new appdb.model.MailSubscription();
        model.subscribe({event : "select", callback : function(v){appdb.model.MailSubscription.defaultNotification = v;clbck(v);}});
        model.subscribe({event : "error", callback : clbck});
        model.get({flt:args || ''});
    },
    setRoleNotification : function(enable,args,clbck){
         var model = new appdb.model.RoleMailSubscription();
        model.subscribe({event : "remove", callback : clbck});
        model.subscribe({event : "insert", callback : function(v){
            if(clbck){clbck(v);}
            appdb.model.MailSubscription.roleNotification = v;
        }});
        model.subscribe({event : "error", callback : clbck});
        if(enable){
            model.insert(args);
        }else{
            model.remove(args);
        }
    },
    getRoleNotification : function(clbck,args){
        args = appdb.utils.base64.encode(args);
        var model = new appdb.model.RoleMailSubscription();
        model.subscribe({event : "select", callback : function(v) {appdb.model.MailSubscription.roleNotification = v;clbck(v);}});
        model.subscribe({event : "error", callback : clbck});
        model.get(args);
    }
});

appdb.components.RatingReport = appdb.ExtendClass(appdb.Component,"appdb.components.RatingReport",function(o){
    o = o || {};
    this.ext = o.ext || {};
    this.reset = function(){
        this.views.chart.reset();
        $(this.dom).empty();
        this._initContainer();
    };
    this.render = function(d){
        this.views.chart.render(d.rating);
		this.views.average.render(d);
    };
    this.destroy = function(){
        this.reset();
        this._model.destroy();
        this.views.chart.destroy();
    }
    this.load = function(q){
        q.query = q.query || q;
        q.query.type = q.query.type || "both";
        this._model = new appdb.model.RatingReport(q.query);
		this.views.loading.show();
        this._model.subscribe({event:"select",callback:function(e){
                this.publish({event:'loaded',value:{}});
                this.render(e.ratingreport);
				this.views.loading.hide();
            },caller:this}).get();
        this._model.subscribe({event:"error",callback:function(e){
			this.views.loading.hide();
            alert("error while loading rating report");
        }});
    };
    this._appendMenu = function(type){
        var li = $(document.createElement("li"));
        var a = $(document.createElement("a"));
        a.attr("href","#").click(
            (function(t,mq){
                return function(){
                    var q = t._model.getQuery();
                    q.type = mq;
                    t.load({query:q});
                    $(t.dom).find("li").removeClass("selected");
                    $(li).addClass("selected");
                };
            })(this,type));
            var txt = "both";
        switch(type){
            case "external":
                txt = "anonymous"
                break;
            case "internal":
                txt = "authenticated";
                break;
            default:
                txt = "all";
                break;
        }
        $(a).text(txt);
        $(li).append($(a));
        if(type==="both"){
            $(li).addClass("selected");
        }
        return $(li);
    };
	this._appendDecoration = function(){
		var li = $(document.createElement("li"));
		$(li).addClass("ratingreportmenu-decoration").html("<span>&bull;</span>");
		return $(li);
	};
    this._initContainer = function(){
        var div = $(document.createElement("div"));
        var ul = $(document.createElement("ul"));
        $(div).addClass("ratingreportmenu ");
        $(div).append("<span class='ratingreportmenu-title'>View : </span>");
        $(ul).attr("id","reportchartmenu");
        $(ul).append(this._appendMenu("both"));
		$(ul).append(this._appendDecoration());
        $(ul).append(this._appendMenu("internal",true));
        $(ul).append(this._appendDecoration());
		$(ul).append(this._appendMenu("external",true));
        $(div).append($(ul));
		$(this.dom).append("<div id='ratingreportloading' class='ratingreport-loading'></div>");
        $(this.dom).append($(div));
        $(this.dom).append('<center><div id="ratingChart" class="ratingchart" ></div><div id="ratingChartAverage" ></div></center>');
		$(this.dom).append($("<div style='width:100%;height:10px' ></div><hr/><div style='width:100%;height:8px' ></div>"));
    };
    this._init = function(){
        var v = {};
        if(typeof o.container==="string"){
            this.dom = $(o.container);
        }else{
            this.dom = o.container;
        }
        this._initContainer();
        v.chart = new appdb.views.RatingChart({container : $("#ratingChart")});
		v.average = new appdb.views.RatingAverage({container:$("#ratingChartAverage")});
		v.loading = new appdb.views.DelayedDisplay({selector : "#ratingreportloading",usedefault:true,delay:20});
        this.views = v;
    };
    this._init();
});
appdb.components.ReportAbuse = appdb.ExtendClass(appdb.Component, "appdb.components.ReportAbuse",function(o){
	o = o || {};
	this.ext = o.ext || {};
	this.dom = null;
	this.dialog = null;
	this.events = [];
	this.inited = false;
	this.preInitQueue = [];
	this.reset = function(){
		dojo.forEach(this.events,dojo.disconnect);
		if(this.dialog){
			this.dialog.destroyRecursive(false);
		}
	};
	this.submit = function(d){
		var _this = this;
		$.ajax({
			url : "abuse/submit",
			data : d,
			async : false,
			success : function(){
				_this.dialog.hide();
			},
			error : function(e){
				_this.ErrorHandler.handle({status:"Report error",description:"Report failed to be submitted."});
			}
		});
	};
	this.validateData = function(d){
		var err = null;
		if(d.reason===-1){
			err = "Please select the reason of your report";
		}else if(d.comment===""){
			err = "Please provide a description for your report";
		}else if(d.submitterId===null){
			err = "Only authedicated users can submit a report. Please login and try again";
		}
		if(err!==null){
			this.ErrorHandler.handle({status:"Your report is not valid",description:err,source : null});
			return false;
		}
		return true;
	};
	this.collectData = function(){
		var res = {entryID:((this.ext.type==="application")?this.ext.id:this.ext.commentId),reason:null,comment:"",submitterId:userID,type : this.ext.type};
		res.comment = dijit.byId("reportabuse_comment",this.dialog).getValue();
		res.comment = $.trim(res.comment);
		var r = $(this.dialog.domNode).find("input[name='reportabuse_type_"+this.ext.type+"']:checked");
		res.reason = r.val() || -1;
		return res;
	};
	this.render = function(d){
		if(this.inited===false){
			this.preInitQueue.push({caller:this.render,args:arguments});
			return;
		}
		this.reset();
		this.ext.type = d.type || appdb.components.ReportAbuse.type;
		this.ext.id = d.id || -1;
		this.ext.title = d.title || appdb.components.ReportAbuse.contents[this.ext.type].title;
		this.ext.description = d.description || appdb.components.ReportAbuse.contents[this.ext.type].description;
		if(d.name && d.name.length>=20){
			d.name = d.name.substr(0,17) + "...";
		}
		var title = this.ext.title; 
		if(typeof d.type === "string"){
			switch(d.type){
				case "application":
					title += " (Application: " + d.id + " / "+d.name+")";
					break;
				case "comment":
					this.ext.commentId = d.commentId;
					title += "(Application: " + d.id + " / " + d.name + ", Comment: " + d.commentId + ")";
					break;
			}
		}
		$(this.dom).find("#reportabuse_description").html(this.ext.description);
		$(this.dom).find(".reportabuse-types").css({display:"none"});
		$(this.dom).find("#reportabuse_types_"+this.ext.type+"").first().css({display:"block"});
		
		$(this.dom).find("#reportabuse_title").hide();
		this.dialog = new dijit.Dialog({
			title : title,
			content : $(this.dom).html(),
			style : "width:600px;"
		});
		this.dialog.show();
		this.dialog.resize();
		//set title icon
		dojo.query(".dijitDialogTitle",this.dialog.domNode)[0].innerHTML = '<img style="vertical-align: middle; padding-right: 3px;" border="0" src="/images/stop.png" width="16px"/>'+title;
		this.events[this.events.length] = dojo.connect(dijit.byId("reportabuse_cancel"),'onClick',this,(function(t){
			return function(){
				t.dialog.hide();
			};
		})(this),this);
		this.events[this.events.length] = dojo.connect(dijit.byId("reportabuse_submit"),'onClick',this,(function(t){
			return function(){
				var data = t.collectData();
				if(t.validateData(data)){
					t.submit(data);
				}
			};
		})(this),this);
	};
	this.load = function(q){
		q = q || {};
		this.ext = (q.ext)?$.extend(this.ext,q.ext):$.extend(this.ext,q);
		
	};
	this._init = function(){
		var _subinit = (function(t){
			return function(container){
				if(typeof container==="undefined"){
					t.dom = $(document.createElement("div"));
				}else if(typeof container==="string"){
					t.dom = $(container);
				}else{
					t.dom = container;
				}
				
				t.inited = true;
				for(var i=0; i<t.preInitQueue.length; i+=1){
					t.preInitQueue[i].caller.apply(t,t.preInitQueue[i].args);
				}
			};})(this);
		appdb.ViewLoader.getComponentView(this._type_.getName(),{
			success : function(d){
				_subinit($(d.cache));
			},
			error : function(){
				_subinit();
			}
		});
	};
	this._init();
},{
	description : "",
	title : "Report a problem",
	type : "application",
	contents : {
		application : {
			title : "Report a problem on the content ",
			description : "You are about to report a problem about the contents of this application. Please select a reason and provide a description of the problem. After the submition a report will be sent to be reviewed for validity and further processing."
		},
		comment : {
			title : "Report abuse ",
			description : "You are about to report a problem about a user comment on this application. Please select a reason and provide a description of the problem. After the submition a report will be sent to be reviewed for validity and further processing."
		}
	}
});
appdb.components.LinkStatuses = appdb.ExtendClass(appdb.Component, "appdb.components.LinkStatsuses", function(o){
	this.destroy = function(){
		$("input#linkStatuses_quicksearch").unbind("keyup");
		$(this.dom).empty();
	};
	this.render = function(){
		if($.fn.quicksearch){
			$("input#linkStatuses_quicksearch").quicksearch("table#linkStatuses_results tbody tr");
			$("input#linkStatuses_quicksearch").bind("keyup",function(){
				setTimeout(function(){
					var elem = document.getElementById("linkStatuses_body");
					if (elem.clientHeight == elem.scrollHeight)
						$("table#linkStatuses_tableheader").css("padding-right","0px");
					else
						$("table#linkStatuses_tableheader").css("padding-right","15px");
				},100);
			});
			$("table#linkStatuses_tableheader thead tr th").mouseup(function(){
				var th = $($("table#linkStatuses_results thead tr th").get($(this).index()));
				var t = this;
				setTimeout(function(){
					if($(th).hasClass("headerSortUp")){
						$(t).removeClass("headerSortDown");
						$(t).addClass("headerSortUp");
					}else if($(th).hasClass("headerSortDown")){
						$(t).removeClass("headerSortUp");
						$(t).addClass("headerSortDown");
					}else{
						$(t).removeClass("headerSortUp");
						$(t).removeClass("headerSortDown");
					}
				},100);
				$(th).trigger('click');
			});
		}else{
			$("#linkStatuses_form").hide();
		}
	};
	this.load = function(){
		this.publish({event:"loaded",value:{}});
		this.render();
	};
	this._init = function(){
		var v = {};
        if(typeof o.container==="string"){
            this.dom = $(o.container);
        }else{
            this.dom = o.container;
        }
        this.views = v;
	};
	this._init();
});
appdb.components.Tags = appdb.ExtendClass(appdb.Component,"appdb.components.Tags",function(o){
	this._slider = null;
	this.destroy = function(){
		if(this._slider){
			this._slider.destroyRecursive(false);
		}
		for(var i in this.views){
			this.views[i].reset();
		}
		this._model.destroy();
		$(this.dom).empty();
	};
	this._adjustItems = function(cnt){
        cnt = cnt || -1;
        if(cnt===-1){
            cnt = parseInt(this._slider.attr("value"));
        }
		var d = {};
		d = $.extend(d,this._model.getLocalData());
		d.tag = this._model.getLocalData().tag.slice(0);
		if($.isArray(d.tag)===false){
			d.tag = [d.tag];
		}
		if(d.tag.length===cnt-1){
			return;
		}
		if(d.tag.length>cnt-1){
			d.tag = d.tag.slice(0,cnt-1);
		}
		this.views.cloud.render(d);
		this.render = this._adjustItems;
	};
	this._renderSlider = function(){
		var c = this._model.getLocalData();
		var max = appdb.components.Tags.maxVisibleItems;
		if($.isArray(c.tag)===false){
			c.tag = [c.tag];
		}
		if(c.tag.length<=max){		
			max = c.tag.length;
		}		
		this._slider = new dijit.form.HorizontalSlider({
            name: "slider",
            value: max-1,
            minimum: 1,
            maximum: max,
			discreteValues : max-2,
            intermediateChanges: false,
            style:"width:95%;text-align:center;height:100%;",
            onChange: (function(_this){
				return function(value) {
						value = Math.round(value);
						_this._adjustItems(value);
					};
            })(this)
        },
        $(this.dom).find(".tagcloud-slider").get(0));
        $(this.dom).find(".dijitSliderIncrementIconH , .dijitSliderDecrementIconH").css({"margin-top":"0px","margin-bottom":"0px"});
	};
	this.render = function(d){
		if(d.tag){
			if($.isArray(d.tag)==false){
				d.tag = [d.tag];
			}
			if(d.tag.length>appdb.components.Tags.maxVisibleItems-1){
				d.tag = d.tag.slice(0,appdb.components.Tags.maxVisibleItems-1);
			}
		}
		this._renderSlider();
		this.views.cloud.render(d);
	};
	this.load = function(){
		this._model = appdb.model.Tags;
		this._model.unsubscribeAll(this);
		this._model.subscribe({event:"select",callback:function(e){
                this.publish({event:'loaded',value:{}});
				this.render(e);
                                if(this._slider){
                                        if($.browser.msie){
                                                this._slider.attr("value",((e.tag.length<100)?e.tag.length:99));
                                        }else{
                                                this._slider.attr("value",((e.tag.length<appdb.components.Tags.maxVisibleItems)?e.tag.length:appdb.components.Tags.maxVisibleItems));
                                        }
                                }
            },caller:this});
        this._model.subscribe({event:"error",callback:function(e){
            console.log("ERROR[Tags|model]:",e);
        }});
		this._model.get();
	};
	this._initContainer = function(){
		if($(this.dom).length===0){
			return;
		}
		var tl = document.createElement("div"), header = document.createElement("div");
		if(this._title!==null){
			$(header).addClass("tagcloud-header").html("<span>"+(this.title || "Tag cloud")+"</span>");
			$(this.dom).append($(header));
		}
		$(tl).addClass("tagcloud-list");
		$(this.dom).append("<div class='tagcloud-slider' title='Slide to change the count of visible tags.'></div>").append($(tl));
	};
	this._init = function(){
		var v = {};
		if(typeof o.container==="string"){
			this.dom = $(o.container);
		}else{
			this.dom = o.container;
		}
		this._title = o.title || (o.title===null)?null:"Tag cloud";
		this._initContainer();
		v.cloud = new appdb.views.TagCloud({container:$(this.dom).find(".tagcloud-list").get(0)});
		this.views = v;
	};
	this._init();
},{
	maxVisibleItems : 100
});
appdb.components.MainSearch = appdb.ExtendClass(appdb.Component,"appdb.views.MainSearch",function(o){
    this._cloud = null;
    this._tagdialog = null;
    this.reset = function(){

    };
    this.render = function(){
        this.views.filter.unsubscribeAll();
        this.views.filter.subscribe({event:"filter",callback:(function(_this){
                return function(v){
                    v.target.callback(v.query,v.target.args);
                    this.setValue("");
                };
        })(this),caller: this.views.filter}).subscribe({event:"target",callback:function(v){
            if(v.value==="apps"){
                $(this.dom).find(".mainsearch-tags").css({visibility: "visible"});
            }else{
                $(this.dom).find(".mainsearch-tags").css({visibility: "hidden"});
            }
			if(v.value==='vos'){
				this.views.filter._field = "name";
			}else{
				this.views.filter._field = "flt";
			}
        },caller:this}).render();
    };
    this.load = function(){
    };
    this._initContainer = function(){
        var main = document.createElement("div"), body = document.createElement("div"),footer = document.createElement("div"), a = document.createElement("a");
        this._cloud = document.createElement("div") ;
        $(main).addClass("mainsearch");
        $(body).addClass("mainsearch-body");
        $(footer).addClass("mainsearch-footer");

        $(body).append("<span class='mainsearch-filter' id='mainsearch-filter'></span>");
        $(main).append($(body));
        $(a).attr("href","#").addClass("mainsearch-tags").css({visibility:"hidden"});
        $(footer).append($(a));
        $(this._cloud).addClass("mainsearch-tagcloud").css({"width":"200px"});
        $(a).click((function(_this){
               return function(){
                    setTimeout(function(){
                        dijit.popup.open({
                            parent : $(a)[0],
                            popup: _this._tagdialog,
                            around :$(a)[0],
                            orient: {'BR':'TR','BL':'TL'}
                        });
                        _this.views.cloud.render();
                        $(_this._cloud).click(function(event) {
                            var src = event.srcElement?event.srcElement:event.target;
                            if(src && src.tagName.toLowerCase()==="a"){
                                return true;
                            }
                            return false;
                        });
                    },10);
                };
        })(this)).text("Show tag cloud");
        
        $(main).append($(footer));
        $(this.dom).append($(main));
    };
    this._init = function(){
        var v = {};
		if(typeof o.container==="string"){
			this.dom = $(o.container);
		}else{
			this.dom = o.container;
		}
		this._initContainer();
        v.filter = new appdb.views.ExtendedFilter({
            container : "mainsearch-filter",
            rich : false,
            watermark : "Search...",
            displayClear : false,
            height:10,
            targets:[
//                {text:"Everything",value:"all",image:"/images/all.png",title:"Search Everything",callback : appdb.views.Main.showEverything, args : {mainTitle : "Everything",prepend:[]}},
                {text:"Applications & Tools",value:"apps",image:"/images/app.png",title:"Search Applications & tools",callback : appdb.views.Main.showApplications,args : {mainTitle : "Application & Tools",prepend:[]}},
                {text:"People",value:"people",image:"/images/person.png", title:"Search people",callback : appdb.views.Main.showPeople, args : {mainTitle: "People",prepend:[]}},
                {text:"Virtual Organizations",value:"vos",image:"/images/other.png",title:"Search Virtual Organizations", callback : appdb.views.Main.showVOs, args : {mainTitle: "Virtual Organizations",prepend:[]}}
            ],
            seperator : "<div style='height:1px;'></div><span style='display:inline-block;padding-top:5px;padding-left:5px;padding-right:5px;'>in</span>"
        });
        v.cloud = new appdb.components.Tags({container:$(this._cloud)});
        this.views = v;
        this.views.cloud.subscribe({event : "loaded",callback:function(){
            this._tagdialog =  new dijit.TooltipDialog({content : $(this._cloud).get(0)});
        },caller : this}).load();
        
    };
    this._init();
});

appdb.components.TabContainer = appdb.ExtendClass(appdb.Component,"appdb.components.TabContainer",function(o){
    this.reset = function(){
		
    };
	this._tabs = [];
	this.showTab = function(index){
		index = parseInt(index) || 0;
		var h = $(this._tabs[index].handler);
		var b = $(this._tabs[index].body);
		$(this.dom).find("thead > tr > th > ul > li").removeClass("tab-selected");
		$(h).addClass("tab-selected");

		$(this.dom).find("tbody:first > tr").hide()
		$(b).show();
	};
    this.render = function(){
        $(this.dom).addClass("tabcontainer");
		var ul = $(this.dom).find("thead tr th ul")[0];
		$(ul).addClass("tab-bar");
		$(ul).find("li").each((function(_this){
			return function(index,elem){
				$(this).addClass("tab");
				$(this).find("span").addClass("tab-text");
				_this._tabs[_this._tabs.length] = {handler : this};
			};
		})(this));
		$(ul).find("li").each((function(_this){
			return function(index,elem){
				$(this).click(function(){
					_this.showTab(index);
				});
			};
		})(this));
		$(this.dom).find("tbody:first > tr").each((function(_this){
			return function(index,elem){
				_this._tabs[index]["body"] = $(elem);
				$(elem).hide();
			};
		})(this));
		this.showTab(0);
		
    };
    this.load = function(d){
        
    };
    this._initContainer = function(){
        
    };
    this._init = function(){
        var v = {};
		if(typeof o.container==="string"){
			this.dom = $(o.container);
		}else{
			this.dom = o.container;
		}
		this._initContainer();
        this.views = v;
    };
    this._init();
});

appdb.components.DataList = appdb.ExtendClass(appdb.Component,"appdb.components.DataList", function(o){
	this.reset = function(){
		$(this.dom).empty();
		this._initContainer();
	};
	this.render = function(d,col){
		col = col || 0;
		if(col===0){this.reset();}
		var ul = $($(this.dom).find(".datalist-list").get(col));
		var w = $(ul).css("width");
		var i, len = d.length;
		for(i=0; i<len; i+=1){
			var li = document.createElement("li"), v = null;
			var a = document.createElement("a");
			$(li).addClass("datalist-item").css("width",w);
			v = d[i][this._modelvalue];
			if(typeof v === "undefined"){
				v = d[i].val();
			}
			$(a).attr("href","#").attr("title","").text(v);
			$(li).append($(a));
			if(this._events){
				for(var e in this._events){
					$(a)[e]((function(_this,item,elem){
						return function(){
							_this._events[e](item,elem);
						};
					})(this,d[i],$(li)));
				}
			}
			$(ul).append($(li));
		}
	};
	this.load = function(q){
		var m = appdb.FindNS("appdb.model."+this._modelname, false);
		if(typeof m === "undefined"){
			console.log("ERROR[DataList]:could not find model " + this._modelname);
			return;
		}
		this._model = m;
		this._model.subscribe({event : "select", callback: function(v){
			v = v[this._modelfield];
			if($.isArray(v)===false){
				v = [v];
			}
			var sl = Math.floor(v.length/this._columns);
			var s = 0;
			for(var i=0; i<this._columns; i+=1){
				var vp = v.slice(s,sl+s+1);
				this.render(vp,i);
				s += sl+1;
			}
		},caller:this});
		this._model.subscribe({event:"error",callback: function(e){
				console.log("ERROR[DataList]:An error occured while loading datalist data.",this);
		},caller : this});
	this._model.get();
	};
	this._initContainer = function(){
		$(this.dom).addClass("datalist");
		var w = ""+Math.floor(100/this._columns);
		for(var i=0; i<this._columns; i+=1){
			var ul = document.createElement("ul");
			$(ul).addClass("datalist-list").css("width",w+"%");
			$(this.dom).append($(ul));
		}
	};
	this._init = function(){
		if(typeof o.container==="string"){
			this.dom = $(o.container);
		}else{
			this.dom = o.container;
		}
		
		this._modelname = o.model;
		this._modelfield = o.field;
		this._modelvalue = o.value;
		this._events = o.events;
		this._columns = o.columns || 1;
		this._initContainer();
	};
	this._init();
});
appdb.components.MailSubscription = appdb.ExtendClass(appdb.Component,"appdb.components.MailSubscription",function(o){
    var NewsEventType = appdb.components.MailSubscription.NewsEventType, NewsDeliveryType = appdb.components.MailSubscription.NewsDeliveryType;
    this._subscription = undefined;
    this._dialog = undefined;
    this.events = [
        {value:NewsEventType.E_INSERT, name:"New applications",selected:true},
        {value:NewsEventType.E_UPDATE, name:"Application updates",selected:true},
        {value:NewsEventType.E_INSERT_COMMENT, name:"New comments",selected:false},
        {value:NewsEventType.E_INSERT_CONTACT, name:"New contacts",selected:true}];
    this.deliveries = [
        {value:NewsDeliveryType.D_DAILY_DIGEST, name:"Daily",selected:false},
        {value:NewsDeliveryType.D_WEEKLY_DIGEST, name:"Weekly",selected:true},
        {value:NewsDeliveryType.D_MONTHLY_DIGEST, name:"Monthly",selected:false}];
    this.reset = function(){
        $(this.dom).empty();
	};
	this.render = function(d){
        var i, doc = document, res = doc.createElement("div"), desc = doc.createElement("span"), title = doc.createElement("span"), format=doc.createElement("span"),
            actions=doc.createElement("span"), commands=doc.createElement("span"), progress = doc.createElement("div"), message = doc.createElement("span"), img = doc.createElement("img");
        var eventTypes = NewsEventType.split(this._subscription.events),
            deliveryTypes = NewsDeliveryType.split(this._subscription.delivery);
		$(res).addClass("customsubscribe");
		$(desc).addClass("description");
        $(desc).append("Subscriptions will be send to <i><b>"+appdb.model.PrimaryContact.userPrimaryContact+"</b></i>. To change your primary e-mail contact visit the preferences section of your <a href='#' onclick='appdb.views.Main.showPerson({id:userID});'>profile</a>.");

        //Title rendering
		$(title).append("<span class='title'>Title:</span>").
            append("<input type='text'  />").
            addClass("title");
        (new dijit.form.TextBox({
            value : this._subscription.name,
            "class" : "title",
            onChange : (function(_this){
                    return function(val){
                        _this._subscription.name = val;
                    };
                })(this)
            },$(title).find("input")[0]));

        //Format list rendering
        $(format).append("<span class='title'>Delivery:</span>").addClass("delivery");
        for(i=0; i<this.deliveries.length; i+=1){
            $(format).append("<span class='checkoption'><input type='checkbox' value='"+this.deliveries[i].value+"'   /><span>"+this.deliveries[i].name+"</span></span>");
        }
        $(format).find("span.checkoption > input").each((function(_this,dt){
            return function(index,elem){
              (new dijit.form.CheckBox({
                    checked : dt[$(elem).val()],
                    onChange : (function(val){
                        return function(v){
                            _this._subscription.delivery = ((v)?(_this._subscription.delivery | val):(_this._subscription.delivery ^ val));
                        };
                    })($(this).val())
                },$(this)[0]));
            };
        })(this,deliveryTypes));

        //Actions list rendering
		$(actions).append("<span class='title'>Notify me for:</span>").addClass("events");
        for(i=0; i<this.events.length; i+=1){
            $(actions).append("<span class='checkoption'><input type='checkbox' value='"+this.events[i].value+"' checked  /><span>"+this.events[i].name+"</span></span>");
        }
        $(actions).find("span.checkoption > input").each((function(_this,et){
            return function(index,elem){
                (new dijit.form.CheckBox({
                    checked : et[$(elem).val()],
                    onChange : (function(val){
                        return function(v){
                           _this._subscription.events = ((v)?(_this._subscription.events | val):(_this._subscription.events ^ val));
                        };
                    })($(this).val())
                },$(this)[0]));
            };
        })(this,eventTypes));

        //Commands rendering
        $(commands).addClass("commands");
        if(this._subscription.id){//Already subscribed. The actions will be Update and Unsubscribe
            $(commands).append("<span class='command mailfeed' ><a href='' alt='' title='Click to update the current mail notification settings' target='_blank' id='mailsubscriptionupdate'>Update</a></span>").
            append("<span class='command mailfeed' ><a href='' alt='' title='Click to unsubscribe' target='_blank' id='mailsubscriptionremove'>Unsubscribe</a></span>");
            $(commands).find("#mailsubscriptionupdate").click((function(_this){
                return function(){
                    if(_this._subscription.id){
                        _this._model.update(_this._subscription);
                    }else{
                        console.log("Invalid action UPDATE for mail notification service. No id provided");
                    }
                };
            })(this));
            $(commands).find("#mailsubscriptionremove").click((function(_this){
                return function(){
                    if(_this._subscription.id){
                        _this._model.remove({id:_this._subscription.id,pwd:_this._subscription.unsubscribe_pwd});
                    }else{
                        console.log("Invalid action REMOVE for mail notification service. No id provided");
                    }
                };
            })(this));
        }else{
            $(commands).append("<span class='command mailfeed' ><a href='#' alt='' title='Click to subscribe to mail notification service for this list of items'  id='mailsubscriptioninsert' >Subscribe</a></span>");
            $(commands).find("#mailsubscriptioninsert").click((function(_this){
                return function(){
                    if(_this._subscription.id){
                        console.log("Invalid action INSERT for mail notification service. Subscription already exists id:" + _this._subscription.id);
                    }else{
                        _this._model.insert(_this._subscription);
                    }
                };
            })(this));
        }

        $(message).addClass("message").append("Loading...");
        $(img).attr("src","images/ajax-loader-small.gif").attr("alt","").attr("border","0");
        $(progress).append(img).append(message).addClass("progress").css({"display":"none"});
        
        $(res).append(title).append(format).append(actions).append(progress).append(commands).append(desc);
        this._dialog = $(res)[0];

        $(this._dialog).click(function(event) {
            var src = event.srcElement?event.srcElement:event.target;
            if(src && src.tagName.toLowerCase()==="a"){
                return false;
            }
            return false;
        });
        
        setTimeout((function(_this){
            _this._TooltipDialog = new dijit.TooltipDialog({content:_this._dialog});
            return function(){
                dijit.popup.open({
                    parent: $(_this.dom)[0],
                    popup:  _this._TooltipDialog,
                    around: $(_this.dom)[0],
                    orient: {BR:'TR'},
                    onClose : function(){
                        _this._TooltipDialog.destroyRecursive(false);
                    }
                });
            };
        })(this),10);
	};
    this._renderMessage = function(msg){
        setTimeout((function(_this,message){
            return function(){
                dijit.popup.open({
                    parent: $(_this.dom)[0],
                    popup:  new dijit.TooltipDialog({content:"<div>"+message+"</div>"}),
                    around: $(_this.dom)[0],
                    orient: {BR:'TR'}
                });
            };
        })(this,msg),10);
    };
    this._inProgress = {
        show : function(o,msg){
            var p = $($(o._dialog).find("div.progress")[0]), m = $($(p).find("span.message")[0]);
            var c = $($(o._dialog).find(".commands")[0]);
            $(m).empty().append(msg || "loading...");
            $(p).css({display : "inline-block"});
            $(c).css({display : "none"});
        },
        hide : function(o){
            $($(o._dialog).find("div.progress")[0]).css({display: "none"});
            var c = $($(o._dialog).find(".commands")[0]);
            $(c).css({display : "inline-block"});
        }
    };
	this.load = function(q,persist){
        if(typeof q === "string"){
            q = {flt:'',title:q};
        }
        q = q || {};
        
        this._model = new appdb.model.MailSubscription();
        this._model.subscribe({event:"select",callback : function(v){
            if(v.id){
                this._subscription = {
                    id : v.id,
                    name : v.name,
                    events : v.events,
                    delivery : v.delivery,
                    flt : appdb.utils.base64.encode(q.flt),
                    subjecttype : "app",
                    unsubscribe_pwd : v.unsubscribe_pwd
                }
            }else{
                this._subscription = {
                    name : q.title,
                    events : NewsEventType.E_INSERT | NewsEventType.E_UPDATE,
                    delivery : NewsDeliveryType.D_WEEKLY_DIGEST ,
                    flt : appdb.utils.base64.encode(q.flt),
                    subjecttype : "app"
                }; 
            }
             if(this._TooltipDialog && persist){
                    dijit.popup.close( this._TooltipDialog);
                    setTimeout((function(_this){
                        _this.render();
                    })(this),10);
                }else{
                    dijit.popup.close( this._TooltipDialog);
                }
                this._initContainer();
            
        } , caller : this});
        this._model.subscribe({event : "beforeinsert", callback : function(){
                this._inProgress.show(this,"Subscribing to mail notification service");
            //TODO : prepare UI for SUBSCRIBE Action
        }, caller : this});
        this._model.subscribe({event : "insert", callback : function(){
                this._inProgress.hide(this);
                this._model.get({flt:this._subscription.flt},true);
            //TODO: Set UI for subscribed mail notification
        }, caller : this});
        this._model.subscribe({event : "beforeupdate", callback : function(){
            //TODO: prepare UI for update action
            this._inProgress.show(this,"Updating current subscription");
        }, caller : this});
        this._model.subscribe({event : "update", callback : function(){
            //TODO: set new updated data
            this._inProgress.hide(this);
            this._model.get({flt:this._subscription.flt},true);
        }, caller : this});
        this._model.subscribe({event : "beforeremove", callback : function(){
            //Prepare UI for UNSUBSCRIPTION
            this._inProgress.show(this,"Unsubscribing from mail notification service");
        }, caller : this});
        this._model.subscribe({event : "remove", callback : function(){
            this._inProgress.hide(this);
            this._model.get({flt:this._subscription.flt},true);
        }, caller : this});
        if(userID===null){
            this._initContainer();
        }else{
            this._model.get({flt:appdb.utils.base64.encode(q.flt)});
        }
	};
	this._initContainer = function(){
        this.reset();
        var doc = document, div = doc.createElement("div"), a = doc.createElement("a"),
            img = doc.createElement("img"), title ="Click to subscribe to the mail notification service for the current list" ;
        $(div).addClass("mailnotification");
        $(img).attr("border","0").attr("alt","").attr("src",appdb.components.MailSubscription.images.subscribe);

        if(this._subscription && this._subscription.id){
            title = "Click to customize your subscription to the mail notification services for the current list";
            $(img).attr("src",appdb.components.MailSubscription.images.customize);
        }
        $(a).attr("href","#").attr("title",title).click((function(_this){
            return function(){
                if(userID!==null){
                    if( appdb.model.PrimaryContact.userPrimaryContactId == null){
                        _this._renderMessage("<div style='width:415px;'><div style='padding:3px;'><b>No e-mail contact found in your profile.</b></div><div style='padding:3px;'>At least one e-mail contact is needed in order to subscribe to the e-mail notification service. Visit your profile by clicking  <a href='#' onclick='appdb.views.Main.showPerson({id:userID});'>here</a> to add or edit your contacts.</div><div style='padding:3px;'>In case you wish to add more than one e-mail contacts the system will set as the primary one the first one added.To set a different primary e-mail contact visit the preferences section of your profile.</div></div>");
                    }else{
                        _this.render();
                    }
                }else{
                    _this._renderMessage('<div style="width:420px;">If you wish to subscribe to the applications database e-mail notification service, please <a class="login" href="#" onclick="login();">login</a> first, using your EGI SSO account. If you don\'t have an EGI SSO account you can acquire one <a href="https://www.egi.eu/sso/" target="_blank">here</a></div>');
                }
            };
        }(this)));

        $(a).append(img);
        $(div).append(a);
        $(this.dom).append(div);
	};
	this._init = function(){
		if(typeof o.container==="string"){
			this.dom = $(o.container);
		}else{
			this.dom = o.container;
		}
	};
	this._init();
},{
    NewsEventType : {E_INSERT : 1, E_UPDATE : 2, E_DELETE : 4,  E_INSERT_COMMENT : 8, E_INSERT_CONTACT : 16 , 
        has : function(val,en){return (( val & en ) == en );}, //Checks whether an enumerated variable has the given enumeration
        split : function(val){ //Takes an enumerated variable and split it into an array.
            var res = {}, en = appdb.components.MailSubscription.NewsEventType;
            for(var e in en){
                if(typeof e === "function"){
                    continue;
                }
                res[en[e]] = en.has(val,en[e]);
            }
            return res;
    }},
    NewsDeliveryType : {D_NO_DIGEST : 1, D_DAILY_DIGEST : 2, D_WEEKLY_DIGEST : 4, D_MONTHLY_DIGEST : 8, 
        has : function(val,en){return (( val & en ) == en );},//Checks whether an enumerated variable has the given enumeration
        split : function(val){ //Takes an enumerated variable and split it into an array.
            var res = {}, en = appdb.components.MailSubscription.NewsDeliveryType;
            for(var e in en){
                if(typeof e === "function"){
                    continue;
                }
                res[en[e]] = en.has(val,en[e]);
            }
            return res;
    }},
    images : {
        subscribe : "images/email.png",
        customize : "images/email_notify.png"
    }
});
appdb.components.NameAvailability = appdb.ExtendClass(appdb.Component,"appdb.components.NameAvailability",function(o){
	this.input = undefined;
	this.originalname = undefined;
	this.ctime = -1;
	this.reset = function(){
		if(this.input){
			$(this.input).unbind("keyup").unbind("mouseup").unbind("change");
		}
		$(this.dom).empty();
	};
	this.render = function(d){
		this._initContainer();
	};
	this.load = function(q){
		if(typeof q === "string"){
			q = {name:q};
		}
		q = q || {};
		if(typeof q.name === "undefined"){
			q.name = '';
		}
		this._model.get(q);
	};
	this._validating = function(){
		$(this.dom).find(".validatordisplay").hide();
		$(this.dom).find(".validatorresult").hide();
		$(this.dom).find(".validatorprogress").show();
	};
	this._validationError = function(error){
		$(this.dom).find(".validatorprogress").hide();
		$(this.dom).find(".validatordisplay").show();
		$(this.dom).find(".validatorresult").show();
		$($(this.dom).find(".validatorresult").find("span")[0]).empty().append(error);
        $($(this.dom).find(".validatorresult")[0]).removeClass("valid").addClass("invalid");
		this.publish({event:"error",value : {name : $(this.input).val(),"error" : error}});
	};
    this._showDescription = function(elem,data){
        setTimeout(function(){
              dijit.popup.open({
                parent: elem,
                popup:  new dijit.TooltipDialog({content:"<div class='validator_popup'>"+ data + "</div>"}),
                around: elem,
                orient: {BR:'TR'}
            });
        },10);
    };
	this._validationResult = function(reason,isvalid,description){
		isvalid = (typeof isvalid ==="undefined")?true:isvalid;
		$(this.dom).find(".validatorprogress").hide();
		$(this.dom).find(".validatordisplay").show();
		$(this.dom).find(".validatorresult").show();
		$($(this.dom).find(".validatorresult").find("span")[0]).empty();
		if(isvalid===true){
			if(description){
                $($(this.dom).find(".validatorresult")[0]).removeClass("invalid").removeClass("valid").addClass("valid_warning");
                $($(this.dom).find(".validatordescription")[0]).attr("src","images/question_mark.gif").unbind('click').click((function(_this){
                    return function(){
                        _this._showDescription($(_this.dom).find(".validatordescription")[0],description);
                    };
                })(this)).css("display","inline-block");
                $($(this.dom).find(".validatorresult").find("span")[0]).empty().append("Warn : "+reason);
            }else{
                $($(this.dom).find(".validatorresult")[0]).removeClass("invalid").removeClass("valid_warning").addClass("valid");
                 $($(this.dom).find(".validatorresult").find("span")[0]).empty().append(reason);
                $($(this.dom).find(".validatordescription")[0]).hide();
            }
			this.publish({event:"valid",value : {name : $(this.input).val()}});
		}else{
			$($(this.dom).find(".validatorresult")[0]).removeClass("valid").removeClass("valid_warning").addClass("invalid");
            if(description){
                $($(this.dom).find(".validatordescription")[0]).attr("src","images/question_mark.gif").unbind('click').click((function(_this){
                    return function(){
                        _this._showDescription($(_this.dom).find(".validatordescription")[0],description);
                    };
                })(this)).css("display","inline-block");
                $($(this.dom).find(".validatorresult").find("span")[0]).empty().append(reason);
            }else{
                $($(this.dom).find(".validatordescription")[0]).hide();
            }
			this.publish({event:"invalid",value : {name : $(this.input).val(), "reason" : reason}});
		}
	};
	this._prevalidate = function(){
		var n = $(this.input).val();
		if($.trim(n)===''){
			this._validationResult("Empty name",false,"The application name must not be empty");
		}else if(this.originalname==null || $.trim(n.toLowerCase())!==$.trim(this.originalname.toLowerCase())){
			setTimeout((function(_this,_name){
				_this.ctime++;
				var tcount = _this.ctime;
				return function(){
					if(_this.ctime>tcount){
						return;
					}
					_this.ctime=-1;
					_this._validating(_name);
					_this.load({name:_name});
				};
			})(this,n),300);
		}else{
			$(this.dom).find(".validatorresult").hide();
		}
	};
	this._initContainer = function(){
		this.reset();
		var div = document.createElement("div"), result=document.createElement("div"), 
			display = document.createElement("div"), a = document.createElement("a"),
			progress = document.createElement("div"), img = document.createElement("img"),
            description = document.createElement("img");
		$(div).addClass("namevalidator");
		$(progress).addClass("validatorprogress");
		$(display).addClass("validatordisplay");
        $(description).addClass("validatordescription").attr("src","images/question_mark.gif").attr("title","Click to view description").hide();
		$(result).addClass("validatorresult").append("<span></span>").append(description);
        
        $(display).append($(a));
		$(a).attr("href","#").attr("title","Click to check if the name you typed is available for use or another application has already claimed it.").
			append("Check name availability").
			click((function(_this){
				return function(){
					_this._prevalidate();
				};
			})(this)).hide();
		$(img).attr("src","images/ajax-loader-small.gif").attr("border","0");
		var sp = document.createElement("span");
		$(sp).text("checking");
		$(progress).empty().append(img).append(sp).hide();
		

		$(div).append(display).append(progress).append(result);
		$(this.dom).append(div);
		$(this.input).keyup((function(_this){
			return function(){
				_this._prevalidate();
			};
		})(this));
		$(this.input).change((function(_this){
			return function(){
				_this._prevalidate();
			};
		})(this));
		$(this.input).mouseup((function(_this){
			return function(){
				_this._prevalidate();
			};
		})(this));
	};
	this._init = function(){
		if(typeof o.container==="string"){
			this.dom = $(o.container);
		}else{
			this.dom = o.container;
		}
		this.input = o.input;
		this.originalname = $(this.input).val();
		if($.trim(this.originalname)==''){
			this.originalname=null;
		}
		this._initContainer();
		this._model = new appdb.model.NameAvailability();
		this._model.subscribe({event : "select", callback : function(v){
				if(this.ctime>-1){
					return;
				}
				if($.trim($(this.input).val())===''){
					this._prevalidate();
				}else if(v.error){
					this._validationResult(v.error,false,v.reason);
				}else if(v.warning){
					this._validationResult("Available",true,v.warning);
				}else{
                    this._validationResult("Available",true);
                }
		}, caller : this});
	};
	this._init();
});
appdb.ViewLoader = (function(){
    var _v = {};
    var _shouldLoad = function(o){
        var lo = o.loadOn || "always";
        switch(lo){
            case "absent":
                //if the view is displayed and is cached it shouldn't be loaded
                if($(o.selector).length>0 && o.cache!==null){
                    return false;
                }else{
                    return true;
                }
                break;
            case "always":
                return true;
                break;
            case "nocache":
                return (o.cache===null)?true:false;
                break;
            default:
                return true;
                break;
        }
    };
    var _loadView = function(o){
        var v = o.view, c = o.callbacks , a = {
            url : appdb.config.endpoint.base+  v.url,
            type : 'GET',
            success : function(d){
               v.cache = d;
               if(v.isTemplate===true){
                   v.templatepane = new appdb.TemplatePane({content: v.cache,parent:o});
                   v.cache = v.templatepane.content;
               }
               if(c){
                   c.success(v);
               }
            },
            error : function(d,s){
               v.cache = null;
               if(c){
                   c.error(d);
               }
            },
            async : (c)?true:false
        };
        
        $.ajax(a);
        return v.cache;
    };
    var _getCached = function(o){
        var c = o.callbacks;
        if(typeof c === "undefined"){
            return o.view;
        }else{
            if(c.success){
                c.success(o.view);
            }
        }
        return null;
    };
    var _getView = function(o){
        return {html:((_shouldLoad(o.view)===true)?_loadView(o):_getCached(o)), isTemplate: ((o.view.isTemplate)?o.view.isTemplate:false),templatepane:o.view.templatepane};
    };
    var _clearCache = function(n){
        var i, v = null;
        if(typeof n !== "undefined"){
            if(typeof n === "string"){
                v = [n];
            }else if(typeof n === "array"){
                v = n;
            }
        }        
        if(v===null){
            for(i in _v){
                _v[i].cache = null;
            }
        }else{
            for(i=0; i<v.length; i+=1){
                _v[v].cache = null;
            }
        }
    };
    var _getComponentView = function(type,c){
        for(var i in _v){
            if(_v[i].component===type){
                return _getView({view: _v[i],callbacks :c});
            }
        }
        return null;
    };
    var _init = function(){
        _v["people"] = {loadOn : "nocache", url : "people?flt=role.id:-1", cache : null, selector : "#ppl_main_content",component:"appdb.components.People"};
        _v["apps"] = {loadOn:"nocache", url : "apps?flt=" , cache : null, selector : "#apps_main_content",component:"appdb.components.Applications"};
        _v["vos"] = {loadOn:"nocache", url : "vo/list" , cache : null, selector : "#vos_main_content",component:"appdb.components.VOs"};
        _v["persondetails"] = {loadOn:"nocache",url:"people/details2",cache : null,selector : "#ppl_details",component:"appdb.components.Person",isTemplate : true, templatepane : null};
		_v["reportabuse"] = {loadOn:"nocahce",url: "abuse/report",cache:null,component:"appdb.components.ReportAbuse"};
		_v["linkstatuses"] = {loadOn: "always",url:"news/linkstatus",cache:null,component:"appdb.components.LinkStatuses"};
    };
    _init();
    var _getPeople = function(c){
        return _getView({view : _v.people, callbacks : c});
    };
    var _getApplications = function(c){
        return _getView({view : _v.apps, callbacks : c});
    };
    var _getVOs = function(c){
        return _getView({view : _v.vos, callbacks : c});
    };
    return {
      clearCache : _clearCache,
      getComponentView : _getComponentView,
      getPeople : _getPeople,
      getApplications : _getApplications,
      getVOs : _getVOs
    };
})();
appdb.views.NavigationPane = appdb.ExtendClass(appdb.View,"appdb.views.NavigationPane",function(o){
    this.id = "mainNavigation";
    this.dom = $("#"+this.id);
    this.data = null;
    this._sep = null;
    this._timer = null;
    this._close = null;
    this._toolbar = null;
    this._constructor = function(){
       o = o || {};
        if(typeof o.container !== "undefined"){
            this.dom = $(o.container);
            this.id = $(this.dom).attr("id");
        }
    };
    this.reset = function(){
        this.data = [];
        $(this.dom).empty();
        $(this.dom).addClass("dijitDialogTitleBar").css({"cursor":"default","height":"18px"});
        if(this._sep){
            $(this._sep).empty().remove();
        }
        this._sep = $(document.createElement("span")).css({"padding-right":"3px","padding-left":"3px",display:"inline-block"}).text(">");
        if(this._timer){
            $(this._timer).empty().remove();
        }
         if(appdb.config.appenv!=="production"){
            this._timer = $('<span id="timer" style="float:right;padding-right:5px;" ></span>');
        }else{
            this._timer = $('<span id="timer" style="display:none"></span>');
        }
        if(this._close!==null){
            $(this._close).empty();
        }
        this._close = $(document.createElement("div"));
        $(this._close).attr("style","float:right;margin:0px;padding:0px;vertical-align:top;display:inline-block;position:relative;top:-3px;");
        $(this._close).append('<a href="#" title="click to close current page"><img src="images/closeview.png" border="0" style="vertical-align:top;top:-3px;padding:0px;margin:0px;" width="18" height="18" alt="close"></img></a>');
        
        this._toolbar = $('<div id="toolbarContainer" style="display: inline-block; float: right;"></div>');
        $(this.dom).append(this._timer);
    };
    this.destroy = function(){
        this.reset();
        if($(this.dom).length>0){
            $(this.dom).attr("style","display:none;").empty();
        }
        this.dom = null;
    };
    this.render = function(d){
        this.reset();
        d = d || [];
        
        if($.isArray(d)===false){
            d = [d];
        }
        var i , len = d.length,t;
        for(i=0; i<len; i+=1){
            t = d[i];
			if((i+1)===len){
                this.appendCurrentItem(t);
            }else{
                this.appendItem(t);
            }
            if((i+1)<len){
                this.appendSeperator();
            }
            if(i===(len-2)){
				$(this._close).find("a").first().unbind("click").bind("click",(function(c){
                    return function(){
                        //$("#toolbarContainer").empty();
                        if(c.self && c.callerArgs.length===1){
                            c.callerArgs[c.callerArgs.length] = c.self;
                        }
                        c.caller.apply(null,c.callerArgs);
                    };
                })(t));
            }
            
        }
        if(d.length>0){
            $(this.dom).append($(this._close));
            $(this.dom).append($(this._toolbar));
        }
		this.data = d;
        $(this.dom).show();
    };
    this.appendCurrentItem = function(d){
        var txt = (d.text || ""),title = txt,islist = false;
		islist = (d.self && d.self.isList)?true:false;
        if(txt.length>=25){
            txt = txt.substring(0,23) + "...";
        }
		$(this._close).find("a").attr('title',((islist)?'Return to previous view':'Close current view'));
		$(this._close).find("img").attr('src','images/'+((islist)?'previousview':'closeview')+'.png');
        $(this.dom).append("<span id='lastNavigationItem' title='"+title+"' >"+txt+"</span>");
    };
    this.appendItem = function(d){
        this.data[this.data.length] = d;
        var a = $(document.createElement("a")),txt = d.text,title = txt;
        if(txt.length>=25){
            txt = txt.substring(0,23) + "...";
        }
        $(a).attr("title",title);
        $(a).css({"cursor":"pointer"}).text(txt || "title");
        $(a).click(function(){
                if(d.self && d.callerArgs.length===1){
                    d.callerArgs[d.callerArgs.length] = d.self;
                }
                d.caller.apply(null,d.callerArgs);
            });
        $(this.dom).append($(a));
    };
    this.appendSeperator = function(){
        $(this.dom).append($(this._sep).clone());
    };
    this.clearToolbar = function(){
        $(this.dom).find("#toolbarContainer").first().empty();
    };
    this.hide = function(){
       if($(this.dom).length>0){
           $(this.dom).hide();
       }
    };
    this.getLastItemData = function(){
        if(this.data){
            return (this.data.length)?this.data[this.data.length-1]:null;
        }
        return null;
    };
    this.setLastItemTitle = function(title){
         if(title.length>=25){
            title = title.substring(0,23) + "...";
        }
        $(this.dom).find("#lastNavigationItem").first().text(title);
		if(this.data){
		 var dd = this.data[this.data.length-1];
		 if(dd.componentType==="appdb.components.Application"){
		  document.title = appdb.Navigator.Registry["Application"].title({"name":title});
		 }else if(dd.componentType==="appdb.components.Person"){
		  document.title = appdb.Navigator.Registry["Person"].title({},{"mainTitle":title});
		 }
		}
    };
    this.closeCurrentItem = function(){
        $(this._close).find("a").click();
    };
    this._constructor();
});
appdb.views.Main = (function(){
    var _navpane =null, _navData = [], _currentState = {},_onRefresh = false,_currentPaging = {length:0,offset:0};
    $(document).ready(function(){
        _navpane = new appdb.views.NavigationPane({container:"#mainNavigation"});
    });
    var _currentComponent = null, _container = null,_currentContent = null, _loaded = {};
    var _appendNavigation = function(e){
        if(typeof e.mainTitle === "undefined"){
			if ( _currentComponent !== null ) e.mainTitle = _currentComponent.getComponentTitle();
        }
        _navData[_navData.length] = {text: e.mainTitle , caller : e.componentCaller,callerArgs:e.componentArgs,componentType:e.componentType,self:e};
        _navpane.render(_navData);
    };
    var _createNavigationList = function(e){
		if(_onRefresh){
			_onRefresh=false;
			return;
		}
		e = e || {};
		if(e.prepend){
			if($.isArray(e.prepend)===false){
				e.prepend = [e.prepend];
			}
		}else{
			e.prepend = [];
		}

		if(e.prepend.length>0 && _navData.length>0 &&
			_navData[_navData.length-1].componentType === e.prepend[e.prepend.length-1].componentType &&
			_navData[_navData.length-1].componentType !== e.componentType ){
            if(e.previousPager &&
                e.previousPager.pageoffset &&
                _navData[_navData.length-1].callerArgs.length>0){
                _navData[_navData.length-1].callerArgs[0].pageoffset = e.previousPager.pageoffset;
            }
            
		  _appendNavigation(e);
		   return;
		}
		_clearNavigation();
		if(_navData.length===0){
			_navData[_navData.length] = {text: "Home", title: "Return to home page", caller : appdb.views.Main.showHome,callerArgs:[]};
		}
		if(e.prepend){
			for(var i=0; i<e.prepend.length; i+=1){
                if(e.prepend[i].isTerminal){
                    break;
                }
				_appendNavigation(e.prepend[i]);
			}
		}

		_appendNavigation(e);
    };
    var _clearNavigation = function(){
        _navData = [];
        _navpane.reset();
    };
    var _subContainer = function(typename,contents){
        var tn = typename.replace(/\./g,"_"),res;
        var tni = "#"+tn;
        if($("#main").children(tni).length>0){
            return $(tni);
        }else{
            res = $(document.createElement("div"));
            res.attr("id",tn);
            res.attr("dojoType","dijit.layout.ContentPane" );
            res.css({"width":"100%","height":"100%"});
            $("#main").append(res);
            if(contents){
                $(res).append(contents);
            }
        }
        return res;
    };
    var _setViewContent = function(d){
        $("#details").empty().hide();
        var sc = null, bc = null;
        if(_currentContent===null){
            $("#main").empty();
            sc = _subContainer(d.componentType);
            $(sc).append(d.cache);
            $(sc).show();
        }else{
            sc = _subContainer(_currentContent.componentType);
            if(_currentContent.componentType!==d.componentType){
                if(_currentComponent){
                    _currentComponent.destroy();
                }
                bc = _subContainer(d.componentType,d.cache);
                $(sc).hide();
                $(bc).show();
            }
        }
        _currentContent = d;
    };
    var _getContainer = function(){
        if(_container===null){
            _container = $("#main");
        }
        return _container;
    }
    var _startLoading = function(t){
        var iscached = (_currentComponent)?true:false;
        if($("#details").is(":visible")){
            $("#main").hide();
            showAjaxLoading();
        }
        if(_currentComponent){
           if(_currentComponent.getComponentType()!==t){
                _resetComponent();
                iscached = false;
            }
        }
        $("#details").empty().hide();
        return iscached;
    };
    var _endLoading = function(){
       hideAjaxLoading();
       $("#main").show();
    };
    var _resetComponent = function(){
        _currentComponent.destroy();
        _currentComponent = null;
    };
    var _getComponent = function(type){
        var arr = type.split("."),len = arr.length,i,res = window;
        for(i=0; i<len; i+=1){
            res = res[arr[i]];
        }
        return res;
    };
    var _parseQuery = function(q){
        if(typeof q === "undefined"){
            return {};
        }
        if($.isPlainObject(q)){
            return q;
        }
        if($.trim(q)===""){
            return {};
        }
        var res = "{", ql = q.split("&"), ol = [],i;
        for(i=0; i<ql.length; i+=1){
            ol = ql[i].split("=");
            if(ol.length===2){
                res += ol[0] + ":" + ((ol[1]==='null')?"''":"'"+ol[1]+"'") + ",";
            }
        }
        res = res.substring(0,res.length-1);
        res += "}";
        res = eval("("+res+")");
        return res;
    };
    var _showComponent = function(o,e){
        _endLoading();
        var iscached = _startLoading(e.componentType || ""),c = _getComponent(e.componentType || "");
        
        var d = appdb.ViewLoader.getComponentView(e.componentType,{
            success : function(d){
                d.componentType = e.componentType;
                
                if(!iscached){
                    if(_currentComponent && _currentComponent.destroy && _currentComponent.getComponentType() !== e.componentType){
                        _currentComponent.reset();
                        _currentComponent.destroy();
                    }
                    _setViewContent(d);
                    if(d.isTemplate){
                        d.templatepane.parentContent = _subContainer(e.componentType);
                        _currentComponent = new c({content:d.cache,container:_subContainer(e.componentType),contents:d.cache,templatepane:d.templatepane,ext:e});
                    }else{
                        _currentComponent = new c({content:d.cache,container:_getContainer(),ext:e});
                    }
                }else{
                    _setViewContent(d);
                }
                if(e.mainTitle){
                    _currentComponent.setComponentTitle(e.mainTitle);
                }
                _currentComponent.subscribe({event:'loaded',callback: function(){
                    _createNavigationList(e);
                    _endLoading();
                    this.unsubscribeAll(_currentComponent);
                    window.onresize();
                },caller:_currentComponent}).
                clearEvents().
                load({query:o,ext:e});
            },
            error : _endLoading
        });
    };
	var _showPeople = function(o,e){
	 _currentState = {callback : _showPeople,query:o,ext:e};
        e = e || {};
        if(userID){
            o.userid = userID;
        }
        o.pagelength = optQueryLen;
        e.append = false;
        e.componentCaller = e.componentCaller || appdb.views.Main.showPeople;
        e.mainTitle = e.mainTitle || ((o.flt)?"Filtered":"People");
        if(o.flt!==""){
            e.prepend = e.prepend ||  {
                componentType : "appdb.components.People",
                mainTitle : "People",
                isBaseQuery : false,
                userQuery : '',
                filterDisplay : "Search...",
				isList : true,
                componentCaller: appdb.views.Main.showPeople,
                componentArgs:[{pagelength:optQueryLen,flt:""}]
            };
            if($.isArray(e.prepend)){
                for(var i=0; i<e.prepend.length; i+=1){
                    e.prepend[i].componentCaller =  e.prepend[i].componentCaller || appdb.views.Main.showPeople; //if from permalink
                }
            }else{
				e.prepend = [e.prepend];
			}
        }
        e.componentType = e.componentType || "appdb.components.People";
        e.filterDisplay = e.filterDisplay || "Search...";

        if(e.isBaseQuery){
            e.baseQuery = o;
        }
        e.componentArgs =   [o];
		e.isList = true;
        _showComponent(o,e);
        _selectAccordion("peoplepane");
	};
    var _showPerson = function(o,e){
		var i;
		_currentState = {callback : _showPerson,query:o,ext:e};
        e = e || {};
        o = _parseQuery(o);
        if(userID){
            o.userid = userID;
        }
		//e.append = true;
		e.componentCaller = e.componentCaller || appdb.views.Main.showPerson;
		e.prepend = e.prepend || {
			componentType : "appdb.components.People",
			mainTitle : "People",
			isBaseQuery : false,
			filterDisplay : "Search...",
			componentCaller: appdb.views.Main.showPeople,
			componentArgs:[{pagelength:optQueryLen,flt:""}]
		};
		if($.isArray(e.prepend)){
			for(i=0; i<e.prepend.length; i+=1){
				e.prepend[i].componentCaller =  e.prepend[i].componentCaller || appdb.views.Main.showPeople; //if from permalink
			}
		}
		
		e.componentType = e.componentType || "appdb.components.Person";
        e.componentArgs = [o];
        if ( userID !== null ) {
            if(o.id===0){
                _clearNavigation();
                _createNavigationList(e);
                setTimeout(function(){showPplDetails('/people/details?id='+o.id+'&userid='+userID, true);},1);
            }else{
                 _createNavigationList(e);
                setTimeout(function(){showDetails('/people/details?id='+o.id+'&userid='+userID, '');},1);
            }
        } else {
            _showComponent(o,e);
        }
        _selectAccordion("peoplepane");
    };
	var _showEverything = function(o,e) {
		_showApplications(o,e);
		_showPeople(o,e);
		_showVOs(o,e);
	};
    var _showApplications = function(o,e){
		_currentState = {callback : _showApplications,query:o,ext:e};
        e = e || {};
        o.applicationtype = e.subType || "applications";
        if(optQueryLen<=0){
            window.onresize();
        }
        if(userID){
            o.userid = userID;
        }
        o.pagelength = optQueryLen;
        e.append = false;
        e.componentCaller = e.componentCaller || appdb.views.Main.showApplications;
        e.mainTitle = e.mainTitle || ((o.flt)?"Filtered":"Applications & Tools");
        e.componentType = e.componentType || "appdb.components.Applications";
        e.filterDisplay = e.filterDisplay || "Search...";
        if(o.flt!==""){
            e.prepend = e.prepend || {
                componentType : "appdb.components.Applications",
                mainTitle : "Applications & Tools",
                isBaseQuery : false,
                filterDisplay : "Search...",
				isList : true,
                componentCaller: appdb.views.Main.showApplications,
                componentArgs:[{pagelength:optQueryLen,flt:""}]
            };
            if($.isArray(e.prepend)){
                for(var i=0; i<e.prepend.length; i+=1){
                    e.prepend[i].componentCaller =  e.prepend[i].componentCaller || appdb.views.Main.showApplications; //if from permalink
                }
            }
        }
        if(e.isBaseQuery){
            e.baseQuery = o;
        }
		e.isList = true;
        e.componentArgs =  [o];
        _showComponent(o,e);
        _selectAccordion("applicationspane");
    };
    var _showDiscipline = function(o,e){
		_currentState = {callback : _showDiscipline,query:o,ext:e};
        e = e || {};
        e.append = false;
        e.componentCaller = appdb.views.Main.showDiscipline;
        e.mainTitle = e.mainTitle || "Discipline";
        if(o.flt!==""){
            e.prepend = e.prepend || [{
                componentType : "appdb.components.Applications",
                mainTitle : "Applications & Tools",
                isBaseQuery : false,
                filterDisplay : "Search...",
                componentCaller: appdb.views.Main.showApplications,
                componentArgs:[{pagelength:optQueryLen,flt:""}]
            },{
                componentType : "appdb.components.Applications",
                mainTitle : "Applications",
                isBaseQuery : true,
                filterDisplay : "Search in applications...",
                componentCaller : appdb.views.showApplications,
                componentArgs : [{pagelength : optQueryLen, flt : "tool:false"}]
            }];
            if($.isArray(e.prepend)){
                for(var i=0; i<e.prepend.length; i+=1){
                    e.prepend[i].componentCaller = e.prepend[i].componentCaller || appdb.views.Main.showApplications; //if from permalink
                }
            }
        }
        e.componentType = e.componentType || "appdb.components.Applications";
        e.filterDisplay = e.filterDisplay || "Search in discipline...";
        if(e.isBaseQuery){
            e.baseQuery = o;
        }
        e.componentArgs = [o];
        _showApplications(o,e);
        _selectAccordion("applicationspane");
    };
    var _showSubdiscipline = function(o,e){
		_currentState = {callback : _showSubdiscipline,query:o,ext:e};
        e = e || {};
        e.append = false;
        e.componentCaller = appdb.views.Main.showSubdiscipline;
        e.mainTitle = e.mainTitle || "Subdiscipline";
        if(o.flt!==""){
            e.prepend = e.prepend || [{
                componentType : "appdb.components.Applications",
                mainTitle : "Applications & Tools",
                isBaseQuery : false,
				isList : true,
                filterDisplay : "Search...",
                componentCaller: appdb.views.Main.showApplications,
                componentArgs:[{pagelength:optQueryLen,flt:""}]
            },{
                componentType : "appdb.components.Applications",
                mainTitle : "Applications",
                isBaseQuery : true,
				isList : true,
                filterDisplay : "Search in applications...",
                componentCaller : appdb.views.showApplications,
                componentArgs : [{pagelength : optQueryLen, flt : "tool:false"}]
            }];
            if($.isArray(e.prepend)){
                for(var i=0; i<e.prepend.length; i+=1){
                    e.prepend[i].componentCaller = e.prepend[i].componentCaller || appdb.views.Main.showApplications; //if from permalink
                }
            }
        }
        e.componentType = e.componentType || "appdb.components.Applications";
        e.filterDisplay = e.filterDisplay || "Search in subdiscipline...";
        if(e.isBaseQuery){
            e.baseQuery = o;
        }
        e.componentArgs = [o];
        _showApplications(o,e);
        _selectAccordion("applicationspane");
    };
    var _showApplicationCountry = function(o,e){
		_currentState = {callback : _showApplicationCountry,query:o,ext:e};
        e = e || {};
        e.append = false;
        e.componentCaller = appdb.views.Main.showDiscipline;
        e.mainTitle = e.mainTitle || "Country";
        if(o.flt!==""){
            e.prepend = e.prepend || [{
                componentType : "appdb.components.Applications",
                mainTitle : "Applications & Tools",
                isBaseQuery : false,
				isList : true,
                filterDisplay : "Search...",
                componentCaller: appdb.views.Main.showApplications,
                componentArgs:[{pagelength:optQueryLen,flt:""}]
            }];
            if($.isArray(e.prepend)){
                for(var i=0; i<e.prepend.length; i+=1){
                    e.prepend[i].componentCaller = e.prepend[i].componentCaller || appdb.views.Main.showApplications; //if from permalink
                }
            }
        }
        e.componentType = e.componentType || "appdb.components.Applications";
        e.filterDisplay = e.filterDisplay || "Search in country...";
        if(e.isBaseQuery){
            e.baseQuery = o;
        }
        e.componentArgs = [o];
        _showApplications(o,e);
        _selectAccordion("applicationspane");
    };
    var _showApplicationMiddleware = function(o,e){
		_currentState = {callback : _showApplicationMiddleware,query:o,ext:e};
        e = e || {};
        e.append = false;
        e.componentCaller = appdb.views.Main.showDiscipline;
        e.mainTitle = e.mainTitle || "Middleware";
        if(o.flt!==""){
            e.prepend = e.prepend || [{
                componentType : "appdb.components.Applications",
                mainTitle : "Applications & Tools",
                isBaseQuery : false,
                filterDisplay : "Search...",
				isList : true,
                componentCaller: appdb.views.Main.showApplications,
                componentArgs:[{pagelength:optQueryLen,flt:""}]
            }];
            if($.isArray(e.prepend)){
                for(var i=0; i<e.prepend.length; i+=1){
                    e.prepend[i].componentCaller = e.prepend[i].componentCaller || appdb.views.Main.showApplications; //if from permalink
                }
            }
        }
        e.componentType = e.componentType || "appdb.components.Applications";
        e.filterDisplay = e.filterDisplay || "Search in middleware...";
        if(e.isBaseQuery){
            e.baseQuery = o;
        }
        e.componentArgs = [o];
        _showApplications(o,e);
        _selectAccordion("applicationspane");
    };
	var _showApplicationVO = function(o,e){
	 e.filterDisplay = e.filterDisplay || "Search with vo...";
	 _showApplications(o,e);
	};
    var _showOwned = function(o,e){
		_currentState = {callback : _showOwned,query:o,ext:e};
        e = e || {};
        e.subType = "owned";
        if(typeof e.componentCaller === "undefined"){
            e.componentCaller = appdb.views.Main.showOwned;
        }
        _showApplications(o,e);
    };
    var _showAssociated = function(o,e){
		_currentState = {callback : _showAssociated,query:o,ext:e};
        e = e || {};
        e.subType = "associated";
        if(typeof e.componentCaller === "undefined"){
            e.componentCaller = appdb.views.Main.showAssociated;
        }
        _showApplications(o,e);
    };
    var _showRelatedApps = function(o,e){
		_currentState = {callback : _showRelatedApps,query:o,ext:e};
        e = e || {};
        e.subType = "related";
        e.prepend = e.prepend || [{
                componentType : "appdb.components.Applications",
                mainTitle : "Applications & Tools",
                isBaseQuery : false,
                filterDisplay : "Search...",
                componentCaller: appdb.views.Main.showApplications,
                componentArgs:[{pagelength:optQueryLen,flt:""}]
            },{
                componentType : "appdb.components.Applications",
                mainTitle : "Applications",
                isBaseQuery : true,
                filterDisplay : "Search in applications...",
                componentCaller: appdb.views.Main.showApplications,
                componentArgs:[{pagelength:optQueryLen,flt:"tool:false"}]
            }];
        if(typeof e.componentCaller === "undefined"){
            e.componentCaller = appdb.views.Main.showRelatedApps;
        }
        e.mainTitle = "Related: " + e.appname ;
        _showApplications(o,e);
    };
    var _showModerated = function(o,e){
		_currentState = {callback : _showModerated,query:o,ext:e};
        e = e || {};
        e.subType = "moderated";
        if(typeof e.componentCaller === "undefined"){
            e.componentCaller = appdb.views.Main.showModerated;
        }
        _showApplications(o,e);
    };
    var _showDeleted = function(o,e){
		_currentState = {callback : _showDeleted,query:o,ext:e};
        e = e || {};
        e.subType = "deleted";
        if(typeof e.componentCaller === "undefined"){
            e.componentCaller = appdb.views.Main.showDeleted;
        }
        _showApplications(o,e);
    };
    var _showBookmarks = function(o,e){
		_currentState = {callback : _showBookmarks,query:o,ext:e};
        e = e || {};
        e.subType = "bookmarked";
        if(typeof e.componentCaller === "undefined"){
            e.componentCaller = appdb.views.Main.showBookmarks;
        }
        _showApplications(o,e);
    };
    var _showEditable = function(o,e){
		_currentState = {callback : _showEditable,query:o,ext:e};
        e = e || {};
        e.subType = "editable";
        if(typeof e.componentCaller === "undefined"){
            e.componentCaller = appdb.views.Main.showEditable;
        }
        _showApplications(o,e);
    };
    var _showAppDetails = function(o,e){
		_currentState = {callback : _showAppDetails,query:o,ext:e};
        e = e || {};
		e.append = false;
        e.mainTitle = e.mainTitle || o.name;
		e.prepend = e.prepend || {
			componentType : "appdb.components.Applications",
			mainTitle : "Applications & Tools",
			componentCaller : appdb.views.Main.showApplications,
			isList : true,
			componentArgs : [{flt:""}]
		};
		if($.isArray(e.prepend)){
			for(var i=0; i<e.prepend.length; i+=1){
				e.prepend[i].componentCaller = e.prepend[i].componentCaller || appdb.views.Main.showApplications; //if from permalink
			}
		}else{
			e.prepend = [e.prepend];
		}
        e.componentType = "appdb.components.Application";
        e.componentCaller = showDetails;
        e.componentArgs = ["apps/details?id="+o.id];
        if ( o.id === 0 ) {
            _clearNavigation();
            _createNavigationList(e);
            showAppDetails("apps/details?id="+o.id, true);
        } else {
            _createNavigationList(e);
            showDetails("apps/details?id="+o.id,'');
        }
        _selectAccordion("applicationspane");
    };
    var _showHome = function(callglobal){
        if((typeof callglobal === "boolean" && callglobal===true) || (typeof callglobal==="undefined")){
			showHome();
		}else{
			if($("#homesearchtab").length > 0){
				var homesearchtab = new appdb.components.TabContainer({container : $("#homesearchtab"),style : "width:100%;height:200px;padding:20px;"});
				homesearchtab.render();
				setTimeout(function(){
					var homesearch = new appdb.views.ExtendedFilter({
						container:"homesearch",rich : false,
						watermark : "Search for applications...",
						displayClear : false,
						height:10});
					homesearch.subscribe({event:"filter",callback:function(v){
						appdb.views.Main.showApplications(v,{mainTitle : "Application & Tools",prepend:[]});
					},caller : this})
					homesearch.render();
					
					var hometagcloud = new appdb.components.Tags({container : $("#hometagcloud"),title:null});
					
					setTimeout(function(){
						hometagcloud.load();
					},1000);
					
					var homedisciplines = new appdb.components.DataList({container : $("#homedisciplines"),model:"Disciplines",field:"discipline",value:"", events:{
							click : function(i,e){
								appdb.views.Main.showDiscipline({flt: "=discipline.id:"+i.id},{isBaseQuery:true,mainTitle:i.val()});
							}							
					}});
					homedisciplines.load();
					
					var homemiddlewares = new appdb.components.DataList({container : $("#homemiddlewares"),model:"Middlewares",field:"middleware",value:"",columns : 2, events:{
							click : function(i,e){
								appdb.views.Main.showApplicationMiddleware({flt: "=middleware.name:"+i.val()},{isBaseQuery:true,mainTitle:i.val()});
							}
					}});
					homemiddlewares.load();
				},100);
			}
			if($("#homenewstab").length > 0){
				var homenews = new appdb.components.TabContainer({container : $("#homenewstab"),style : "width:100%;height:200px;padding:20px;"});
				homenews.render();
			}
		}
    };
    var _showNgis = function(sq,e){
		_currentState = {callback : _showNgis,query:sq,ext:e};
        var q = (typeof sq === "number")?"?eu="+sq:"";
        e = e || {};
        e.mainTitle = e.mainTitle || sq;
        if ( e.flt ) {
			if ( q !== '' ) q = q+"&"; else q = "?";
			q = q+'filter='+encodeURIComponent(e.flt);
		}
        if(typeof sq === "number"){
            e.prepend = {
                componentType : "appdb.components.ResourceProviders",
                mainTitle : "Resource Providers",
                componentCaller : appdb.views.Main.showNgis,
				isList : true,
                componentArgs : []
            };
        }
        e.componentType = "appdb.components.ResourceProviders",
        e.mainTitle =  (typeof sq !== "number")?"Resource Providers":((sq===1)?"NGIs":"EIROs"),
        e.componentCaller = appdb.views.Main.showNgis,
        e.componentArgs = [sq];
		e.isList = true;
        _clearComponents();
        _createNavigationList(e);
        ajaxLoad("/ngi"+q,"main", false);
    };
    var _showNgi = function(o,e){
		_currentState = {callback : _showNgi,query:o,ext:e};
        e = e || {};
        e.prepend = {
            componentType : "appdb.components.ResourceProviders",
                mainTitle : "Resource Providers",
				isList : true,
                componentCaller : appdb.views.Main.showNgis,
                componentArgs : []
        };
        e.componentCaller = _showNgi;
        e.componentArgs =[{id:o.id}];
        _createNavigationList(e);
        showNGIDetails("/ngi/details?id="+o.id);
    };
    var _showVOs = function(o,e){
		_currentState = {callback : _showVOs,query:o,ext:e};
        e = e || {};
        o = o || {};
        e.mainTitle = e.mainTitle || 'Virtual Organizations';
        o.pagelength = optQueryLen;
         if(o.name || typeof o.domain !== "undefined"){
            e.prepend = e.prepend ||  {
                componentType : "appdb.components.VOs",
                mainTitle : "Virtual Organizations",
                isBaseQuery : false,
                userQuery : {name:""},
				isList : true,
                filterDisplay : "Search...",
                componentCaller: appdb.views.Main.showVOs,
                componentArgs:[{pagelength:optQueryLen,name:""}]
            };
            if($.isArray(e.prepend)){
                for(var i=0; i<e.prepend.length; i+=1){
                    e.prepend[i].componentCaller =  e.prepend[i].componentCaller || appdb.views.Main.showVOs; //if from permalink
                }
            }
        }
        if(typeof o.name === "undefined"){
            o.name="";
        }
		e.isList = true;
        e.componentType = "appdb.components.VOs";
        e.componentCaller = appdb.views.Main.showVOs,
        e.componentArgs =   [o];
        e.filterDisplay = e.filterDisplay || "Search...";
        if(e.isBaseQuery){
            e.baseQuery = $.extend({},o);
        }
        
        _clearComponents();
        _createNavigationList(e);
       _showComponent(o,e);
        _selectAccordion("vopane");
    };
    var _showVO = function(o,e){
		_currentState = {callback : _showVO,query:o,ext:e};
        e = e || {};
        e.mainTitle = o;//e.mainTitle;
        e.prepend = {
            componentType : "appdb.components.VOs",
                mainTitle : "Virtual Organizations",
                isBaseQuery : false,
				isList : true,
                userQuery : {name:""},
                componentCaller : appdb.views.Main.showVOs,
                componentArgs : [{pagelength:optQueryLen,name:""}]
        };
         if($.isArray(e.prepend)){
            for(var i=0; i<e.prepend.length; i+=1){
                e.prepend[i].componentCaller =  e.prepend[i].componentCaller || appdb.views.Main.showVos; //if from permalink
            }
        }
        e.componentCaller = _showVO;
        e.componentArgs =[];
        _createNavigationList(e);
        showVODetails("vo/details?id="+o,"main");
        _selectAccordion("vopane");
    };
    var _clearComponents = function(){
        if(_currentComponent){
            _currentComponent.destroy();
        }
        _currentComponent = null;
        _container = null;
        _currentContent = null;
        if(_navpane){
            _navpane.hide();
        }
        $("#main").empty();
    };
    var _setLastNavigationTitle = function(title){
        _navpane.setLastItemTitle(title);
    };
	var _refresh = function(){
		_onRefresh = true;
		_currentState.callback(_currentState.query,_currentState.ext);
	};
    var _selectAccordion = function(id){
        var a = dijit.byId(id),n;
        if(a){
            if(a.open){
                return;
            }
            dojo.forEach( dojo.query("div#panediv > .dijitTitlePane"),function(node){
                n=dijit.byNode(node);
                if(n && n.open){
                    n.toggle();
                }
            });
            a.toggle();
        }
    };
	var _showReportAbuse = (function(){
		var ra = null;
		return function(userdata){
			if(ra===null){
				ra = new appdb.components.ReportAbuse();
			}
			ra.render(userdata);
	};})();
	var _showLinkStatuses = function(o,e){
		_currentState = {callback : _showLinkStatuses,query:o,ext:e};
        e = e || {};
        o = o || {};
        e.mainTitle = e.mainTitle || 'Broken Links Report';
        if(typeof o.name === "undefined"){
            o.name="";
        }
		e.isList = true;
        e.componentType = "appdb.components.LinkStatuses";
        e.componentCaller = appdb.views.Main.showLinkStatuses,
        e.componentArgs =   [o];
        
        _clearComponents();
        _createNavigationList(e);
       _showComponent(o,e);
        _selectAccordion("statisticspane");
	};
	var _showActivityReport = function(o,e){
		_currentState = {callback : _showActivityReport,query:o,ext:e};
        e = e || {};
        e.prepend = [];
		e.mainTitle = "Activity Report";
        e.componentCaller = _showActivityReport;
        e.componentArgs =[{}];
        _createNavigationList(e);
         ajaxLoad('/news/report','main',false);
		_selectAccordion("statisticspane");

	};
    var _closeCurrentView = function(){
	   $("#toolbarContainer").empty();
        _navpane.closeCurrentItem();
    };
	var _ajaxLoad = function(url,destination,actions){
	 if (typeof actions !== "boolean" ) {
		 appdb.views.Main.clearComponents();
	 }
	 detailsListHtml = null;
	 $("#details").empty().hide();
	 $("#"+destination).hide();
	 if(url==="/help/usage" || url =="/help/announcements" || url=="/help/faq" || url=="/help/credits" || url=="/changelog" || url=="/changelog/features"){
	  _selectAccordion("helppane");
	 }else if(url.substr(0,9)=="appstats/" || url.substr(0,9)==="pplstats/"){
	  _selectAccordion("statisticspane");
	 }
	 showAjaxLoading();
	 $.get(
		 url, {}, function(data, textStatus) {
			 $('#'+destination).html(data);
			 hideAjaxLoading();
			 $("#"+destination).fadeIn("slow");
			 if (actions!==undefined) eval(actions);
		 }, 'html'
	 );
	 return false;
	};
	var _logout = function(){
	 window.location = 'users/logout';
	};
	
    var retobject =  {
        showHome : _showHome,
        showPeople : _showPeople,
        showEverything: _showEverything,
        showApplications : _showApplications,
        showRelatedApps: _showRelatedApps,
        showModerated: _showModerated,
        showDeleted: _showDeleted,
        showBookmarks : _showBookmarks,
        showEditable : _showEditable,
        showOwned : _showOwned,
        showAssociated : _showAssociated,
        showPerson : _showPerson,
        showApplication : _showAppDetails,
        showNgis : _showNgis,
        showNgi : _showNgi,
        showVOs : _showVOs,
        showVO : _showVO,
        showDiscipline : _showDiscipline,
        showSubdiscipline : _showSubdiscipline,
        showApplicationCountry : _showApplicationCountry,
        showApplicationMiddleware : _showApplicationMiddleware,
		showApplicationVO : _showApplicationVO,
		showReportAbuse : _showReportAbuse,
		showLinkStatuses : _showLinkStatuses,
		showActivityReport : _showActivityReport,
        clearComponents : _clearComponents,
        setNavigationTitle : _setLastNavigationTitle,
        closeCurrentView : _closeCurrentView,
		refresh : _refresh,
		ajaxLoad : _ajaxLoad,
		logout : _logout
    };

	for(var i in retobject){
	 if(retobject.hasOwnProperty(i)){
	  retobject[i] = (function(f,fname){
	   var metadata = appdb.Navigator.Registry[(fname.substr(0,4)=="show")?fname.substr(4):fname];
	   return function(){
		var argv = arguments;
		var ev = appdb.utils.CancelEventTrigger(arguments.callee);
		appdb.utils.DataWatcher.Registry.checkActiveWatcherAsync({notify:true,onClose : function(){
		  f.apply(null,argv);
		  var evtype = (ev && ev.type)?ev.type:"";
		  evtype = (evtype === "hashchange")?false:true;
		  if(metadata && appdb.Navigator.init===true && evtype ){
		   appdb.Navigator.handleHash(metadata,argv);
		  }else{
		   appdb.Navigator.setRawPermalink(window.location.hash);
		   if(metadata && metadata.type!='list'){
			 appdb.Navigator.setTitle(metadata,argv);
		   }
		  }
		}});
	   };})(retobject[i],i);
	 }
	}
	return retobject;
})();
$(document).ready(function(){
    var mainsearch = $("div#mainsearch");
    if(mainsearch.length > 0){
        mainsearch = new appdb.components.MainSearch({container:$("#mainsearch")});
        mainsearch.render();
    }
    if(userID!==null){
        appdb.components.Person.getPrimaryContact();
    }
    appdb.Navigator.init();
});

