// COMMON
	var userAppPrivs;
	var editDocDlg;
	var ratingReport;
	var reportCommentAbuseHtml = '<span style="float: right;" class="commentActions"><span class="reportCommentAbuse"><a href="#" title="Submit a report about this comment">Report abuse</a></span></span>';
	var managedSciCons = null;//TODO: replace with managed code
	var managedAppUrls = null;//TODO: replace with managed code
	var managedAppUrlsEditor = null;//TODO: replace with managed code
	function showCountry(cid) {
		var name="Country", i, c = appdb.model.Regional.Countries.get(), len = c.length, id=''+cid;
		for(i=0; i<len; i+=1){
			if(c[i].id===id){
				name = c[i].val();
				break;
			}
		}
		appdb.views.Main.showApplicationCountry({flt: '=country.id:'+cid},{isBaseQuery:true,mainTitle:name,filterDisplay:"Search in "+name+"..."});
	}

	function personImage(p) {
        var ishttp = Boolean(appdb.config.https) && true;
		if ( p.image ) {
            if(ishttp && p.image.substr(4,1)===":") {
				p.image = "https" + p.image.substr(4,p.image.length)
			} else if(p.image.substr(4,1)==="s") {
                p.image= "http:" + p.image.substr(4,p.image.length);
			}
			return p.image+"&req="+encodeURIComponent(p.lastUpdated);
		} else return "/images/person.png";
	}

	function appLogo(p) {
        var ishttp = Boolean(appdb.config.https) && true;
		if ( p.logo ) {
            if(ishttp && p.logo.substr(4,1)===":") {
                p.logo = "https" + p.logo.substr(4,p.logo.length);
            } else if(p.logo.substr(4,1)==="s") {
                p.logo = "http:" + p.logo.substr(4,p.logo.length);
            }
			return p.logo+"&req="+encodeURIComponent(p.lastUpdated);
		} else {
			if (p.tool == "true") return "/images/tool.png"; else return "/images/app.png";
		}
	}

	function hasAppPriv(id) {
		if ( userAppPrivs === null ) return false;
		if ( userAppPrivs === undefined ) return false;
		for(i=0;i<userAppPrivs.length;i++) {
			if ( userAppPrivs[i] == id ) return true;
		}
		return false;
	}

	function getVOData(c) {
		var dat = new appdb.utils.rest({
			endpoint: appdb.config.endpoint.baseapi+'vos',
			async: true
		}).create({},{
			success: function(d) {
				dat = d.vo;
				$ids = new Array();
				$vals = new Array();
				for (i=0; i<dat.length; i++) {
					$ids.push(dat[i].id);
					$vals.push(dat[i].name);
				}
				c({ids: $ids, vals: $vals});
			}
		}).call();
		delete dat;
	}

	function getAPIData(p,e,c) {
		var dat = new appdb.utils.rest({
			endpoint: appdb.config.endpoint.baseapi+p,
			async: true
		}).create({},{
			success: function(d) {
				dat = eval("(d."+e+")");
				var $ids = new Array();
				var $vals = new Array();
				for (var i=0; i<dat.length; i++) {
					$ids.push(dat[i].id);
					$vals.push(dat[i].val());
				}
				if(appdb.config.defaults.api[e]){
					c({ids: $ids, vals: $vals , selected : appdb.config.defaults.api[e]});
				}else{
					c({ids: $ids, vals: $vals});
				}
			}
		}).call();
		delete dat;
	}

	function getPeopleData(c) {
		var dat = new appdb.utils.rest({
			endpoint: appdb.config.endpoint.baseapi+'people?details=-1',
			async: true 
		}).create({},{
			success: function(d) {
				dat = d.person;
				$ids = new Array();
				$vals = new Array();
				for (i=0; i<dat.length; i++) {
					$ids.push(dat[i].id);
					$vals.push(dat[i].firstname+' '+dat[i].lastname);
				}
				c({ids: $ids, vals: $vals});
			}
		}).call();
		delete dat;
	}

	function getRoleData(c) {
		var dat = new appdb.utils.rest({
			endpoint: appdb.config.endpoint.baseapi+'roles',
			async: true 
		}).create({},{
			success: function(d) {
				dat = d.role;
				$ids = new Array();
				$vals = new Array();
				for (i=0; i<dat.length; i++) {
					$ids.push(dat[i].id);
					$vals.push(dat[i].type);
				}
				c({ids: $ids, vals: $vals});
			}
		}).call();
		delete dat;
	}

	function getContactTypeData(c) {
		var dat = new appdb.utils.rest({
			endpoint: appdb.config.endpoint.baseapi+'contacttypes',
			async: true 
		}).create({},{
			success: function(d) {
				dat = d.contact;
				$ids = new Array();
				$vals = new Array();
				for (i=0; i<dat.length; i++) {
					$ids.push(dat[i].id);
					$vals.push(dat[i].type);
				}
				c({ids: $ids, vals: $vals});
			}
		}).call();
		delete dat;
	}

	var statusData;
	var mwData;
	var countryData;
	var voData;
	var domainData;
	var subdomainData;
	var peopleData;
	var urlData;
	var contactTypeData;
	var roleData;

	function refreshAPIData() {
		getRoleData(function(d) {
			delete roleData;
			roleData = JSON.stringify(d).replace(/"/g,"'");
		});
		getContactTypeData(function(d) {
			delete contactTypeData;
			contactTypeData = JSON.stringify(d).replace(/"/g,"'");
		});
		getAPIData('statuses', 'status', function(d) {
			delete statusData;
			statusData = JSON.stringify(d).replace(/"/g,"'");
		});
		getAPIData('middlewares', 'middleware', function(d) {
			delete mwData;
			mwData = JSON.stringify(d).replace(/"/g,"'");
		});
		getAPIData('regional', 'country', function(d) {
			delete countryData;
			countryData = JSON.stringify(d).replace(/"/g,"'");
		});
		getVOData(function(d) {
			delete voData;
			voData = JSON.stringify(d).replace(/"/g,"'");
		});
		getAPIData('disciplines', 'discipline', function(d) {
			delete domainData;
			domainData = JSON.stringify(d).replace(/"/g,"'");
		});
		getAPIData('disciplines', 'subdiscipline', function(d) {
			delete subdomainData;
			d.ids.splice(0,0,"-1");
			d.vals.splice(0,0,'');
			subdomainData = JSON.stringify(d).replace(/"/g,"'");
		});
		getPeopleData(function(d){
			delete peopleData;
			peopleData = JSON.stringify(d).replace(/'/g,"\\'").replace(/"/g,"'");
		});
		delete urlData;
		urlData = JSON.stringify({
			ids: ['Website', 'Documentation', 'Download', 'Support', 'Multimedia'],
			vals: ['Website', 'Documentation', 'Download', 'Support', 'Multimedia']
		}).replace(/"/g,"'");
	}

	//API data is needed only for logged in users in order to add/edit entries
	if (userID !== null) {
		//fetch once initially
		setTimeout(refreshAPIData,100);
		// refetch data from API every 5 min
		setInterval(function(){refreshAPIData();},5*60000);
	}

	function closeDialog(){
		if (dijit.byId("detailsdlg"+dialogCount) !== undefined) dijit.byId("detailsdlg"+dialogCount).onCancel();
	}
	
	function onError(e) {
		//dijit.byId("detailsdlg"+dialogCount).onCancel();
		new appdb.views.ErrorHandler().handle({status: 'Could not save appliation data', description:'There was an error processing your request, most probably due to a bug, or a network communication problem.<br/>Please try again, or notify support through the <a href="http://helpdesk.egi.eu" target="_blank">EGI Helpdesk</a> if the problem persists, by copying and pasting any text provided in the details',source: {code: e.status, description: e.responseText}});
		$("#cancelsavedetails").click();

	}

// APP INDEX
	function filterApps() {
		var sf = $(":input[name='simpleFilter']:last");
		sf.focus();
		var order="&orderby="+$(".orderby").find(":input").next().val();
		var orderOp="&orderbyOp="+$(".orderbyOp").find(":input").next().val();
		var fuzzy="";
		if ($(':input[name="fuzzySearch"]').attr("checked")) fuzzy = "&fuzzySearch=1";
		ajaxLoad(base+'?flt='+encodeURIComponent($(":input[name='simpleFilter']").val())+fuzzy+order+orderOp, "main");
	}

	function initAppIndexView() {
		ajaxCount++;
		if ($("#subindex")[0].value != "") base=base+"/"+$("#subindex")[0].value;
		navpaneclicks($("#applicationspane")[0]);				
		setTimeout(function(){	
			var sf = $(":input[name='simpleFilter']:last");
			searchbox(sf);
			dojo.connect(dijit.byId(sf.attr("id")), "onKeyPress", function(k) { 
				if (k.keyCode == dojo.keys.ENTER) { 
					filterApps(); 
				}
			})
		}, 100);
		initItemView();
	}

// PPL DETAILS

	function makePplElementEditable() {
		var e = $($.find("#ppl_details"));
		e.find("span.ppl-firstname").addClass("editable").attr("edit_name","firstName").attr("edit_type","text");
		e.find("span.ppl-lastname").addClass("editable").attr("edit_name","lastName").attr("edit_type","text");
		e.find("span.ppl-gender").addClass("editable").attr("edit_name","gender").attr("edit_type","combo").attr("edit_data","{ids: ['male', 'female', 'NULL'], vals: ['Male', 'Female', 'N/A']}");
		e.find("span.ppl-country").addClass("editable").attr("edit_name","countryID").attr("edit_type","combo").attr("edit_data",countryData);
		e.find("span.ppl-contactType").addClass("editable").attr("edit_name","contactType").attr("edit_type","combo").attr("edit_data",contactTypeData).attr("edit_group","true");
		e.find("span.ppl-contact").addClass("editable").attr("edit_name","contact").attr("edit_type","text").attr("edit_group","true");
		e.find("tr.ppl-resourceProvider").hide();

		var h=$($.find("#ppl_details"));
		h.html('<form id="editperson" name="editperson" action="/people/update" method="post">'+h.html()+'</form>');
		editForm("editperson");
	}

// APP DETAILS

	function makeAppElementEditable(e, act) {
		if ( act == 5 ) $(e).find("span.app-name").addClass("editable").attr("edit_name","name").attr("edit_type","text");
		if ( act == 6 ) $(e).find("span.app-desc").addClass("editable").attr("edit_name","description").attr("edit_type","text").attr("edit_required","true");
		if ( act == 7 ) $(e).find("p.app-abstract").addClass("editable").attr("edit_name","abstract").attr("edit_type","textarea");
		if ( act == 9 ) $(e).find("span.app-status").addClass("editable").attr("edit_name","statusID").attr("edit_type","combo");
		if ( act == 10 ) $(e).find("span.app-domain").addClass("editable").attr("edit_name","domainID").attr("edit_type","combo").attr("edit_group","true");
		if ( act == 11 ) $(e).find("span.app-subdomain").addClass("editable").attr("edit_name","subdomainID").attr("edit_type","combo").attr("edit_group","true");
		if ( act == 12 ) {
			$(e).find("span.app-country").addClass("editable").attr("edit_name","countryID").attr("edit_type","combo").attr("edit_onchange","fixCountryFlags");
			$(e).find("span.inherited-country").removeClass("editable");
			$(e).find("span.app-countryFlag").addClass("editable").attr("edit_type","none");
		}
		if ( act == 13 ) {
			$(e).find("span.app-vo").addClass("editable").attr("edit_name","vo").attr("edit_type","combo").attr("edit_group","true");
		}
		if ( act == 14 ) {
			//$(e).find("span.app-url").addClass("editable").attr("edit_name","url").attr("edit_type","combolink").attr("edit_group","true").attr("edit_combo_free","true").attr("edit_onchange","setURL");
		}
		if ( act == 20 ) { 
			$(e).find("span.app-mw").addClass("editable").attr("edit_name","mw").attr("edit_type","combo").attr("edit_group","true").attr("edit_combo_free","true");
		}
		if ( act == 23 ) $(e).find("span.app-addedby").addClass("editable").attr("edit_name","addedBy").attr("edit_type","combo");
	}

	function formatDate(d) {
		var subdate;
		if (typeof d === "undefined") {
			subdate = new Date();
		} else {
			subdate = d
		}
		month = ''+(parseInt(subdate.getMonth())+1);
		if ( month.length == "1" ) month = "0"+month;
		day = ''+subdate.getDate();
		if ( day.length == "1" ) day = "0"+day;
		hours = ''+subdate.getHours();
		if ( hours.length == "1" ) hours = "0"+hours;
		minutes = ''+subdate.getMinutes();
		if ( minutes.length == "1" ) minutes= "0"+minutes;
		subdate = subdate.getFullYear()+'-'+month+'-'+day+' '+hours+':'+minutes
		return subdate;
	}

	function buildRating(subname,subdate,r,edit) {
		var rating_counter, rating_html = '', ratingspan, submitter;
		var comment;
		var rating;
		if (typeof edit === "undefined") edit = false;
 		for ( rating_counter=1;rating_counter<=5;rating_counter+=1) {
			rating_html += '<img class="ratingstar" data-rating="'+rating_counter+'" style="cursor: pointer; vertical-align: middle" src="/images/star1.png" border="0"/>';
		}
		ratingspan = $('<div><span class="ratingspan">'+rating_html+'</span></div>');
		ratingspan.find("img.ratingstar").each(function(){
			if ( $(this).attr("data-rating") <= r ) $(this).attr("src","/images/star2.png");
		});
		if ( edit ) {
			$(".newrating").empty().remove();
			submitter = '<div class="dijitDialogTitleBar" style="width:99%">'+ratingspan.html()+'<span> Comment added by <a href="#" onclick="appdb.views.Main.showPerson({id: '+userID+'}, {mainTitle: \''+subname+'\'});">'+subname+'</a>, on '+appdb.utils.FormatISODate(subdate)+'</span>'+reportCommentAbuseHtml+'</div>';
 			comment = '<textarea maxlength="512" dojoType="dijit.form.Textarea" name="comment"></textarea>';
 			rating = $('<div style="padding-bottom: 20px" class="newrating"><div class="dijitDialogTitleBar">'+submitter+'</div><div style="height:20px"></div><div style="padding-left:10px; padding-right:10px; padding-top:10px; padding-bottom: 10px; margin-left: auto; margin-right:auto;border:1px solid grey; width: 90%">'+comment+'</div><div style="height:20px"></div><div style="float:right; margin-right:50px"><a class="submitrating" href="#"><b>Submit</b></a> <a class="cancelrating" href="#"><b>Cancel</b></a></div></div>');
			if ( parseInt(r) != 0 ) rating.attr("data-temprating",r)
			rating.find("img.ratingstar").mouseover(function(){
				var myr = parseInt($(this).attr("data-rating"));
				rating.find("img.ratingstar").each(function(){
					if ( parseInt($(this).attr("data-rating")) <= myr ) {
						$(this).attr("src","/images/star2.png");
					} else {
						$(this).attr("src","/images/star1.png");
					}
				})
			});
			rating.find("img.ratingstar").mouseout(function(){
				var myr = rating.attr("data-temprating");
				rating.find("img.ratingstar").each(function(){
					if ( parseInt($(this).attr("data-rating")) <= myr ) {
						$(this).attr("src","/images/star2.png");
					} else {
						$(this).attr("src","/images/star1.png");
					}
				})
			});
			rating.find("img.ratingstar").click(function(){
				var myr = parseInt($(this).attr("data-rating"));
				rating.attr("data-temprating",myr);
			});
		} else {
			submitter = '<div class="dijitDialogTitleBar" style="width:99%">'+ratingspan.html()+'<span> Comment added by '+subname+', on '+appdb.utils.FormatISODate(subdate)+'</span>'+reportCommentAbuseHtml+'</div>';
			comment = '<i>No comment</i>';
			rating = $('<div class="ratingentry"><div class="dijitDialogTitleBar">'+submitter+'</div><div style="height:20px"></div><div style="padding-left:10px; padding-right:10px; padding-top:10px; padding-bottom: 10px; margin-left: auto; margin-right:auto;border:1px solid grey; width: 90%">'+comment+'</div><div style="height:20px"></div></div>');
		}
		return rating;
	}

	function countStars(e) {
		var r=0;
		e.find("img.ratingstar").each(function(){
			if ( $(this).attr("src") == "/images/star2.png" ) {
				if ( parseInt($(this).attr("data-rating")) > r ) r = parseInt($(this).attr("data-rating"));
			}
		});
		return r;
	}

	function addRating(d, e, r, doSubmit) {
		var comment_text, oldtext;
		var month,day,hours,minutes;
		var rating, voteid;
		var oldrating = null;
		if ( doSubmit === undefined ) doSubmit = false;
		if ( r == 0 ) r = countStars($('div.ratingentry[data-submitterid="'+userID+'"]:first'));
		rating = buildRating(userFullname, formatDate(), r, true);
		$(rating).prependTo(".ratingroot");
		dojo.parser.parse(rating[0]);
		rating.find("a.submitrating").click(function(){
			if ( $(".newrating").length > 0 ) {
				comment_text = $.trim($('<span>'+$(".newrating textarea").val()+'</span>').text().replace(/\n/g,"<br/>"));
			} else {
				if ( userID !== null ) {
					comment_text = $.trim($('<span>'+$('.ratingentry[data-submitterid="'+userID+'"] textarea').val()+'</span>').text().replace(/\n/g,"<br/>"));
					voteid = $('.ratingentry[data-submitterid="'+userID+'"]').attr('data-id');
				}
			}
			if ( typeof $(".newrating").attr("data-temprating") != 'undefined' ) {
				r = $(".newrating").attr("data-temprating");
			}
			if ( (r == 0) && (comment_text == '') ) {
				$('<div title="Warning"><p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>Please enter a rating or a comment first.</p></div>').dialog({
					dialogClass: 'alert',
					autoOpen: true,
					resizable: false,
					height:160,
					modal: true,
					buttons: {
						OK: function() {
							$(this).dialog('close');
						}
					}
				});	
			} else {
				
				var p = $(".newrating textarea").parent();
				$(".newrating textarea").remove();
				submitEponymousRating(e, d, r, comment_text, voteid, true);
				oldtext = comment_text;
				if ( comment_text == '' ) comment_text = '<i>No comment</i>'
				p.html(comment_text).addClass("ratingcomment");
				$("a.submitrating").remove();
				$("a.cancelrating").remove();
				$(".newrating").css("padding-bottom","0");
				if (r==0) {
					$(".ratingspan").html('<i>Unrated</i>');
					$(".ratingspan").attr("style",'width:80px;display:inline-block;text-align:center;font-weight:bold;color:gray;');
				} else { 
					$(".ratingspan").find("img.ratingstar").unbind('click');
					$(".ratingspan").find("img.ratingstar").unbind('mouseover');
					$(".ratingspan").find("img.ratingstar").unbind('mouseout');
				}
				$(".ratingspan").removeClass("ratingspan");
			}
 		});
		rating.find("a.cancelrating").click(function(){
			if ( $(".newrating").length > 0 ) {
				$(".newrating").empty();
	//			dijit.byId("navdiv"+dialogCount).selectChild(dijit.byId('infodiv'+dialogCount));
				$('div.ratingentry[data-submitterid="'+userID+'"]:first').show();
			} else {
				var p = rating.find("textarea").parent();
				rating.find("textarea").remove();
				if(oldtext){
					p.html(oldtext);
				} else {
					p.html('<i>No comment</i>');
				}

				p.addClass("ratingcomment");
				$("a.submitrating").remove();
				$("a.cancelrating").remove();
			}
		});
//		$("#ratingdiv"+dialogCount).scrollTo("0%");
		oldrating = $('div.ratingentry[data-submitterid="'+userID+'"]:first');
		if (oldrating !== null) {
			voteid = oldrating.attr("data-id");
			oldrating.hide();
			
			try {
				oldtext = oldrating.find(".ratingcomment").html().replace(/\<br\>/ig,"\n").replace(/\<br\/\>/ig,"\n").replace(/\<br\>\<\/br\>/ig,"\n");
				rating.find("a.submitrating").html("<b>Update</b>");
			} catch (ex) {
				oldtext = 'No comment';
			}
			if ( ($('<span>'+oldtext+'<span>').text() !== 'No comment') &&
				 ($('<span>'+oldtext+'<span>').text() !== 'Comment removed due to abuse report') ) {
				$(".newrating textarea").val(oldtext);
			}
		} else {
			voteid = false;
		}
		if ( doSubmit ) submitEponymousRating(e, d, r, comment_text, voteid, false);
		if (oldrating !== null) {
			dijit.byId("navdiv"+dialogCount).selectChild(dijit.byId('ratingdiv'+dialogCount));
			$(".newrating textarea").focus();
			setTimeout(function(){
				var ratingInfoMsg = new dijit.TooltipDialog({
					title: 'Information',
					content: 'You can set or change your rating from here.'
				});
				dijit.popup.open({
					popup: ratingInfoMsg,
					parent: $(".ratingspan")[0],
					around: $(".ratingspan")[0],
					orient: {TL:'BL'}                    
				});
				$(ratingInfoMsg.domNode).hide();
				$(ratingInfoMsg.domNode).fadeIn();
				setTimeout(function(){
					$(ratingInfoMsg.domNode).fadeOut();
					setTimeout(function(){
						dijit.popup.close(ratingInfoMsg);
						delete ratingInfoMsg;
					},5000);
				},3000);
			},50);
		}
	}
	function populateTags(id,e,_d){
		var cont = $(e).find("div.app-tags")[0];
		var v = new appdb.views.TagList({container: $(cont)});
		v.render(_d.application);
	}
	function populateRatings(id,e,_d) {
		var root = $('<div class="ratingroot"></div>');
		var ratings, rating, submitter, subname, comment, subdate, d1, d2, rating_html, rating_counter, ratingspan;
		var _endpoint = appdb.config.endpoint.baseapi;
		var dat = new appdb.utils.rest({
			endpoint: _endpoint+"applications/"+id+'/ratings',
			async: true
		}).create({},{
			success: function(d) {
				if ( d.rating ) {
					ratings = d.rating;
					if ( ! $.isArray(ratings) ) ratings = [ratings];
					for(i=0; i<ratings.length; i+=1) {
						subdate = ratings[i].submittedOn;
						d1 = subdate.split("T");
						if(d1.length>0 && typeof d1[0] === "string"){
							d2 = d1[1].split(":")
							d2 = d2[0]+':'+d2[1]
						}
						if(d1.length>0 && typeof d1[0] === "string"){
							d1 = d1[0].split("-");
						}
						if(d1.length===3){
							d1 = ''+d1[0]+'-'+d1[1]+'-'+d1[2];
						} else {
							d1 = "";
						}
						subdate = d1+' '+d2;
						rating_html = '';
						if ( typeof ratings[i].rating !== "object" ) { 
							for ( rating_counter=1;rating_counter<=5;rating_counter+=1) {
								rating_html += '<img class="ratingstar" data-rating="'+rating_counter+'" style="cursor: pointer; vertical-align: middle" src="/images/star1.png" border="0"/>';
							}
							ratingspan=$("<div><span></span></div>");
							ratingspan.html(rating_html);
							ratingspan.find("img.ratingstar").each(function(){
								if ( $(this).attr("data-rating") <= ratings[i].rating ) $(this).attr("src","/images/star2.png");
							});
						} else {
							ratingspan=$("<div><span style='width:80px;display:inline-block;text-align:center;font-weight:bold;color:gray;'><i>Unrated</i></span></div>");
						}
						if ( ratings[i].submitter.type == "internal" ) {
							subname = ratings[i].submitter.person.firstname+' '+ratings[i].submitter.person.lastname;
							submitter = '<div class="dijitDialogTitleBar" style="width:99%">'+ratingspan.html()+'<span> Comment added by <a href="#" onclick="appdb.views.Main.showPerson({id: '+ratings[i].submitter.person.id+'}, {mainTitle: \''+subname+'\'});">'+subname+'</a>, on '+appdb.utils.FormatISODate(subdate)+'</span>'+reportCommentAbuseHtml+'</div>';
						} else {
							try {
								subname = ratings[i].submitter.val();
							} catch (ex) {
								subname = '';
							}
							if ( subname != '') {
								if ( ratings[i].submitter.email ) subname = subname + ' ('+ratings[i].submitter.email+')';
								submitter = '<div class="dijitDialogTitleBar" style="width:99%">'+ratingspan.html()+'<span> Comment added by '+subname+', on '+appdb.utils.FormatISODate(subdate)+'</span>'+reportCommentAbuseHtml+'</div>';
							} else {
								submitter = '<div class="dijitDialogTitleBar" style="width:99%">'+ratingspan.html()+'<span> Comment added by <i>an anonymous guest</i>, on '+appdb.utils.FormatISODate(subdate)+'</span>'+reportCommentAbuseHtml+'</div>';
							}
						}
						if (subname != '') {
							if ( ratings[i].comment ) {
								comment = '<span>'+ratings[i].comment+'<span>';
							} else {
								comment = '';
							}
							comment = $(comment.replace(/\<br\/\>/g,"\n")).text().replace(/\n/g,"<br/>");
							if ( comment == '' ) comment = '<i>No comment</i>';
							rating = $('<div class="ratingentry">'+submitter+'<div style="height:20px"></div><div class="ratingcomment" style="padding-left:10px; padding-right:10px; padding-top:10px; padding-bottom: 10px; margin-left: auto; margin-right:auto;border:1px solid grey; width: 90%">'+comment+'</div><br/></div>');
							if (ratings[i].submitter.type == "internal") {
								rating.attr("data-isanon","false");
								rating.attr("data-submitterid",ratings[i].submitter.person.id);
							} else {
								rating.attr("data-isanon","true");
							}
							rating.attr("data-id",ratings[i].id);
							if (ratings[i].moderated == "true") {
								rating.attr("data-moderated","true");
								rating.find(".ratingcomment").html("<i>Comment removed due to abuse report</i>");
							} else {
								rating.attr("data-moderated","false");
							}
							rating.appendTo(root);
						}
					}
				} else {
					root.html('<div style="padding-left: 10px" class="noratings">No comments or ratings yet...</div>');
				}
				var leaveComment = $('<div style="padding-left: 10px" class="leavecomment" style="padding-left:10px"><a href="#">Leave a comment...</a></div><br/>');
				if (userID !== null) {
					leaveComment.find("a").click(function(){
						addRating(_d, e, 0, false);
					});
				} else {
					leaveComment.find("a").click(function(){
						var leaveCommentMsg = $('<div title="Leave comment"><p><span class="ui-icon ui-icon-info" style="float:left; margin:0 7px 20px 0;"></span>If you wish to leave a comment, please <a class="login" href="#" style="color:#D96B00;text-decoration:none;">login</a> first using your EGI SSO account.<br/><br/>If you don\'t have an EGI SSO account you can acquire one <a style="color:#D96B00;text-decoration:none;" href="http://www.egi.eu/about/intranet/sso" target="_blank">here</a></p></div>');
						leaveCommentMsg.find("a.login").click(function(){
							leaveCommentMsg.dialog('close');
							login();
						});
						leaveCommentMsg.dialog({
							dialogClass: 'info',
							autoOpen: true,
							resizable: false,
							width:400,
							height:190,
							modal: true,
							buttons: {
								OK: function() {
									$(this).dialog('close');
								}
							}
						});	
					});
				}
				leaveComment.appendTo($("#ratingdiv"+dialogCount));
				if ( root.html() == '' ) root.html('<div style="padding-left: 10px" class="noratings">No comments yet...</div>');
				root.appendTo($("#ratingdiv"+dialogCount));
				createRatingsControl(e,_d);
				if ( (userRole == 5) || (userRole == 7) ) {
					$(".ratingentry").each(function(){
						var cid = $(this).attr("data-id");
						if ( $(this).attr("data-moderated") == "false" ) {
							$(this).find(".commentActions").prepend('<span class="moderateComment"><a href="#">Moderate</a><span style="padding-left: 5px; padding-right: 5px;" class="reportLinkSeparator">•</span></span>');
						} else {
							$(this).find(".commentActions").prepend('<span class="moderateComment"><a href="#">Unmoderate</a><span style="padding-left: 5px; padding-right: 5px;" class="reportLinkSeparator">•</span></span>');
						}
					});
				}
				$(".moderateComment a").each(function(){
					$(this).click(function(){
						var cid = $(this).parents(".ratingentry").attr("data-id");
						if ( $(this).text() == "Moderate" ) {
							$.ajax({
								url: '/abuse/moderatecomment',
								data: {
									id: cid,
									moderate: "1"
								},
								success: function(data) {
									try {
										data = JSON.parse(data);
									} catch (ex) {
										errh = new appdb.views.ErrorHandler();
										errh.handle({status:"Server error", description: "An error occured while committing your action.", source: ex});
										return;
									}
									var e = $('.ratingentry[data-id="'+data.id+'"]');
									e.find(".ratingcomment").html('<i>Comment removed due to abuse report</i>');
									e.find(".moderateComment a").html('Unmoderate');
								}
							});
						} else {
							$.ajax({
								url: '/abuse/moderatecomment',
								data: {
									id: cid,
									moderate: "0"
								},
								success: function(data) {
									try {
										console.log(data);
										data = JSON.parse(data);
									} catch (ex) {
										errh = new appdb.views.ErrorHandler();
										errh.handle({status:"Server error", description: "An error occured while committing your action.", source: ex});
										return;
									}
									var e = $('.ratingentry[data-id="'+data.id+'"]');
									var s = decode64(data.comment,true);
									if ( s == '' ) s = '<i>No comment</i>';
									e.find(".ratingcomment").html(s);
									e.find(".moderateComment a").html('Moderate');
								}
							});
						}
					});
				});
				$(".reportCommentAbuse").each(function(){
					$(this).click(function(){
						if ( userID !== null ) {
							var cid = $(this).parents(".ratingentry").attr("data-id");
							console.log('cid: '+cid);
							appdb.views.Main.showReportAbuse({"id": id, type: 'comment',commentId:cid,name:_d.application.name});
						} else {
							$('<div title="Report a Problem"><p><span class="ui-icon ui-icon-info" style="float:left; margin:0 7px 20px 0;"></span>If you wish to file a report about a problem regarding a comment, please <a class="login" href="#" style="color:#D96B00;text-decoration:none;">login</a> first using your EGI SSO account.<br/><br/>If you don\'t have an EGI SSO account you can acquire one <a style="color:#D96B00;text-decoration:none;" href="http://www.egi.eu/about/intranet/sso" target="_blank">here</a></p></div>').dialog({
								dialogClass: 'info',
								autoOpen: true,
								resizable: false,
								width:400,
								height:190,
								modal: true,
								buttons: {
									OK: function() {
										$(this).dialog('close');
									}
								}
							});	
						}
					});
				});
			}
		}).call();
	}

	function separateMultipleItems(e) {
		var i;
		$(e).parent().find(".comboseperator").remove();
		for(i=0; i<e.length - 1; i+=1) {
			$(e.get(i)).after('<span class="comboseperator">•</span>');
		}
	}

	function submitEponymousRating(e, d, r, comment, voteid, doNotify) {
		var verb = '';
		var _data = {};
		if (doNotify === undefined) doNotify = false;
		_data.appid = d.application.id;
		_data.rating = r;
		_data.submitterid = userID;
		if ( voteid !== false ) _data.ratingid = voteid;
		if ( comment !== null) _data.comment = comment;
		$.ajax({
			url: '/apps/addrating',
			data: _data,
			success: function(data) {
				try {
					data = JSON.parse(data);
				} catch (ex) {
					errh = new appdb.views.ErrorHandler();
					errh.handle({status:"Server error", description: "An error occured while committing your action.", source: ex});
					return;
				}
				//refresh rating on the fly
				var appratingspan = $(e).find("span.app-rating");
				appratingspan.empty();
				d.application.rating = data.average;
				if ( (voteid === false) || (typeof voteid === "undefined" ) ) {
					verb = 'submitted';
					d.application.ratingCount=parseInt(d.application.ratingCount)+1;
				} else {
					verb = 'updated';
				}
				$(".noratings").remove();
				$(".newrating").addClass("ratingentry").removeClass("newrating").attr("data-id",data.id).attr("data-submitterid",userID);
				createRatingsControl(e,d);
				ratingReport.load({query: {type:"both",appid:d.application.id}});
				if (doNotify) $('<div title="Information"><p><span class="ui-icon ui-icon-info" style="float:left; margin:0 7px 20px 0;"></span>Your entry has been '+verb+'.</p></div>').dialog({
					dialogClass: 'info',
					autoOpen: true,
					resizable: false,
					height:160,
					modal: true,
					buttons: {
						OK: function() {
							$(this).dialog('close');
						}
					}
				});	
			},
			error: function(err) {
				var errh = new appdb.views.ErrorHandler();
				errh.handle({status:"Server error", description: "An error occured while committing your action.", source: err.responseText});
			}
		});
	}

	function submitAnonymousRating(e,d,star,vote) {
		var _data = {};
		var errh, rating, verb;
		_data.appid = d.application.id;
		_data.rating = $(star).attr("data-rating");
		if ( vote !== false ) _data.ratingid = vote;//.id;
		$.ajax({
			url: '/apps/addrating',
			data: _data,
			success: function(data) {
				try {
					data = JSON.parse(data);
				} catch (ex) {
					errh = new appdb.views.ErrorHandler();
					errh.handle({status:"Server error", description: "An error occured while committing your action.", source: ex});
					return;
				}
				var ratingstore = getRatingStore();
				ratingstore['app'+d.application.id] = data.id;
				$.cookie('ratings', JSON.stringify(ratingstore), {expires: 360, path: '/'});
				//refresh rating on the fly
				var appratingspan = $(e).find("span.app-rating");
				appratingspan.empty();
				d.application.rating = data.average;
				if ( vote === false ) {
					d.application.ratingCount = parseInt(d.application.ratingCount) + 1;
				}
				rating = buildRating('<i>an anonymous guest</i>', formatDate(), _data.rating);
//				$(rating).prependTo(".ratingroot");
				createRatingsControl(e,d);
				ratingReport.load({query: {type:"both",appid:d.application.id}});
				if ( vote !== false ) verb = 'updated'; else verb = 'submitted';
				$('<div title="Information"><p><span class="ui-icon ui-icon-info" style="float:left; margin:0 7px 20px 0;"></span>Your entry has been '+verb+'.</p></div>').dialog({
					dialogClass: 'info',
					autoOpen: true,
					resizable: false,
					height:160,
					modal: true,
					buttons: {
						OK: function() {
							$(this).dialog('close');
						}
					}
				});	
			},
			error: function(err) {
				errh = new appdb.views.ErrorHandler();
				errh.handle({status:"Server error", description: "An error occured while committing your action.", source: err.responseText});
			}
		});
	}

	function getRatingStore() {
		var ratingstore = $.cookie('ratings');
		if ( (ratingstore != null) && (ratingstore != '') ) {
			try {
				ratingstore = JSON.parse(ratingstore); 
			} catch(ex) {
				ratingstore = {};
			}
		} else {
			ratingstore = {};
		}
		return ratingstore;
	}

	function ratingToString(rating) {
		var txt = '';
		r = Math.round(rating)
		if (r==1) {
			txt = 'Poor';
		} else if (r==2) {
			txt = 'OK';
		} else if (r==3) {
			txt = 'Good';
		} else if (r==4) {
			txt = 'Very Good';
		} else if (r==5) {
			txt = 'Excellent';
		}
		return txt;
	}
	//Casts a number into a string with the given precision
	//If given precision is greater than the precision of the number then the function is padding with 0
	//e.g ratingPrecision(10.34,4) => "10.3400" (padding) , ratingPrecision(10.346,2) => "10.34"
	function ratingPrecision(r,p){
		r = '' + r;
		var res = '' , i, len, sd, s = r.split(".");
		if(s.length===1){
			sd = [];
			for(i=0; i<p; i+=1){
				sd.push("0");
			}
		}else{
			sd = s[1];
		}
		len = sd.length;
		res = s[0]+".";
		for(i=0; i<p; i+=1){
			res += (i<len)?sd[i]:"0";
		}
		return res;
	}

	function revokeRating(e,d) {
		$(".newrating").empty().remove();
		$('<div title="Revoke rating"><p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>You are about to revoke your previous rating and the associated comment (if any). Are you sure you want to proceed?</p></div>').dialog({
			dialogClass: 'alert',
			autoOpen: true,
			resizable: false,
//			height:250,
//			width: 400,
			modal: true,
			buttons: {
				Yes: function() {
					$(this).dialog('close');
					var _data = {};
					var errh;
					_data.appid = d.application.id;
					$.ajax({
						url: '/apps/revokerating',
						data: _data,
						success: function(data) {
							try {
								data = JSON.parse(data);
							} catch (ex) {
								errh = new appdb.views.ErrorHandler();
								errh.handle({status:"Server error", description: "An error occured while revoking your entry.", source: ex});
								return;
							}
							d.application.rating = data.average;
							d.application.ratingCount -= 1;
							var appratingspan = $(e).find("span.app-rating");
							appratingspan.empty();
							ratingReport.load({query: {type:"both",appid:d.application.id}});
							$('div.ratingentry[data-id="'+data.id+'"]').empty().remove();
							if ( userID === null ) {
								var ratingstore = getRatingStore();
								delete ratingstore['app'+d.application.id];
								$.cookie('ratings', JSON.stringify(ratingstore), {expires: 360, path: '/'});
							}
							createRatingsControl(e,d);
							$('<div title="Revoke entry"><p><span class="ui-icon ui-icon-info" style="float:left; margin:0 7px 20px 0;"></span>Your entry has been successfully revoked.</p></div>').dialog({
								dialogClass: 'info',
								autoOpen: true,
								resizable: false,
								height:160,
								modal: true,
								buttons: {
									OK: function() {
										$(this).dialog('close');
									}
								}
							});	
							if ( $(".ratingroot").html() == '' ) {
								if ( d.application.ratingCount == 0 ) {
									$(".ratingroot").html('<div style="padding-left: 10px" class="noratings">No comments or ratings yet...</div>'); 
								} else {
									$(".ratingroot").html('<div style="padding-left: 10px" class="noratings">No comments yet...</div>'); 
								}
							}
						},
						error: function(err) {
							errh = new appdb.views.ErrorHandler();
							errh.handle({status:"Server error", description: "An error occured while revoking your entry.", source: err.responseText});
						}
					});
				},
				No: function(){
					$(this).dialog('close');
				}
			}
		});	

	}

	function createRatingsControl(e,d) {
		
		function hasSubmitted() {
			var ratingstore = getRatingStore();
			if ( ratingstore['app'+d.application.id] ) {
				return ratingstore['app'+d.application.id];
			} else {
				return false;
			}
		}

		function setRating(r) {
			var dec = 0;
			appratingspan.find("img.ratingstar").each(function(){
				if ( $(this).attr("data-rating") <= Math.floor(r) ) $(this).attr("src","/images/star2.png");
			});
			if ( r > Math.floor(r) ) {
				dec = r - Math.floor(r);
				if ( (dec >= 0.25) && (dec <= 0.75) ) {
					appratingspan.find("img.ratingstar").each(function(){
						if ( $(this).attr("data-rating") == Math.floor(r) + 1 ) $(this).attr("src","/images/star15.png");
					});
				} else if ( dec > 0.75 ) {
					appratingspan.find("img.ratingstar").each(function(){
						if ( $(this).attr("data-rating") == Math.floor(r) + 1) $(this).attr("src","/images/star2.png");
					});
				}
			}
		}

		var cancelSubmit = function() {
			starmouseoutdisabled = false;
			appratingspan.find("img.ratingstar").attr("src","/images/star1.png");
			$(".app-info-votecount").html(votecount_text);
			setRating(rating_num);
		};

		var starmouseoutdisabled = false;
		var appratingspan = $(e).find("span.app-rating");
		if ( ! d.application.rating ) {d.application.rating = 0;}
		var rating_html = '<table cellpadding="0" cellspacing="0" border="0" style="width:100%"><tr><td style="width:80px">';
		var rating_num = Math.round(d.application.rating*100)/100;
		for ( rating_counter=1;rating_counter<=5;rating_counter+=1) {
			rating_html += '<a href="#"><img style="cursor: pointer; vertical-align: middle" class="ratingstar" data-rating="'+rating_counter+'" style="vertical-align: middle" src="/images/star1.png" border="0"/></a>';
		}
		rating_html += '</td><td style="width:16px">';
		var canrevokerating = false;
		if ( ( userID === null ) && ( hasSubmitted() !== false ) ) canrevokerating = true;
		if ( ( userID !== null ) && ( $('div.ratingentry[data-submitterid="'+userID+'"]:first').length>0 ) ) canrevokerating = true;
		if ( canrevokerating ) rating_html += '<span class="revokerating"><a href="#"><img border="0" style="vertical-align: middle" src="/images/cancelicon.png"/></a></span>';
		rating_html += '</td><td><span> <span style="vertical-align: middle" class="app-info-votecount" style="margin-left: 10px">'+((parseFloat(d.application.rating) == 0)?"<i>( unrated</i> ":ratingToString(d.application.rating)+' ( Avg.: '+ratingPrecision(d.application.rating,2)+' by '+d.application.ratingCount+' vote'+((d.application.ratingCount==1)?'':'s'))+')</span></span>';
		rating_html += '</td></tr></table>';
		appratingspan.html(rating_html);
		$(".revokerating").hide();
		appratingspan.find("img.ratingstar").click(function(){
			var _this = $(this);
			var hasSubmittedText;
			if ( userID === null ) {
				if ( hasSubmitted() === false ) {
					hasSubmittedText = '';
				} else {
					hasSubmittedText = '<br/><b>Please note that you have already sumbitted a rating for this application; if you proceed, your previous rating will be replaced</b>.';
				}
				starmouseoutdisabled = true;
				var mustLoginMsg = $('<div title="Rating submission"><p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>You are about to submit your rating as an anonymous user. If you would also like to acompany your rating with a comment, please <a class="login" href="#" style="color:#D96B00;text-decoration:none;">login</a> first using your EGI SSO account.<br/><br/>If you don\'t have an EGI SSO account you can acquire one <a style="color:#D96B00;text-decoration:none;" href="http://www.egi.eu/about/intranet/sso" target="_blank">here</a><br/>'+hasSubmittedText+'</p></div>');
				mustLoginMsg.find("a.login").click(function(){
					cancelSubmit();
					mustLoginMsg.dialog('close');
					login();
				});
				mustLoginMsg.dialog({
					dialogClass: 'alert',
					autoOpen: true,
					resizable: false,
					height:250,
					width: 400,
					modal: true,
					close: cancelSubmit,
					buttons: {
						OK: function() {
							$(this).dialog('close');
							submitAnonymousRating(e,d,_this, hasSubmitted());
						},
						Cancel: function(){
							$(this).dialog('close');
						}
					}
				});	
			} else {
				addRating(d, e, $(_this).attr("data-rating"), true);
			}
		});
		setRating(rating_num);
		var votecount_text;
		var hideRevokeRating;
		$(".revokerating a").click(function(){
			revokeRating(e,d);
		});
		appratingspan.find("img").mouseover(function(){
			hideRevokeRating = false;
			$(".revokerating").show();
			var r = $(this).attr("data-rating");
			appratingspan.find("img.ratingstar").each(function(){
				if ( $(this).attr("data-rating") <= r ) $(this).attr("src","/images/star2.png"); else $(this).attr("src","/images/star1.png"); 
			});
			if ($(this).parent().parent().hasClass("revokerating")) {
				var txt = "Revoke my previous rating and/or comment";
			} else {
				var txt = ratingToString(r);
			}
			votecount_text = $(".app-info-votecount").html();
			$(".app-info-votecount").html(txt);
		});
		appratingspan.find("img").mouseout(function(){
			hideRevokeRating = true;
			setTimeout(function(){if (hideRevokeRating) $(".revokerating").fadeOut();},700);			
			if ( ! starmouseoutdisabled ) {
				$(".app-info-votecount").html(votecount_text );
				appratingspan.find("img.ratingstar").attr("src","/images/star1.png");
				setRating(rating_num);
			}
		});
	}

	function showModerationDetails(d) {
		var moddername = '';
		if (d.moderator) moddername = ' by <a href="#" style="color:#D96B00;text-decoration:none;" onclick="appdb.views.Main.showPerson({id: '+d.moderator.id+'},{mainTitle: \''+d.moderator.firstname+" "+d.moderator.lastname+'\'});">'+d.moderator.firstname + ' '+ d.moderator.lastname+'</a>';
		var modDlg = $('<div title="Moderation Information"><p><span class="ui-icon ui-icon-info" style="float:left; margin:0 7px 20px 0;"></span>Application '+d.name+' has been moderated '+moddername+' for the following reason:</p><div style="padding:10px; border: 1px solid grey"><p>'+(d.moderationReason || '<i>No reason specified</i>')+'</p></div></div>');
		modDlg.dialog({
			dialogClass: 'info',
			autoOpen: true,
			resizable: false,
			width:400,
			height:'auto',
			modal: true,
			buttons: {
				Close: function() {
					$(this).dialog('close');
				}
			}
		});	
		
	}

	function showAppModInfo(e,d) {
		e = e || null;
		d = d || {};
		var modrow;
		if ( e === null ) {
			modrow = $($.find(".app-modrow"));
		} else {
			modrow = $(e).find(".app-modrow");
		}
		var moderator = d.application.moderator || '';
		var moderatedOn = d.application.moderatedOn || '';
		var modreason = d.application.moderationReason || '';
		var modtext = '<br/><b>Moderated';
		if (moderator != '') modtext += ' by <a href="#" onclick="appdb.views.Main.showPerson({id: '+moderator.id+'},{mainTitle: \''+moderator.firstname+" "+moderator.lastname+'\'});">'+moderator.firstname+' '+moderator.lastname+'</a>';
		if (moderatedOn != '') {
			var moddate = moderatedOn.split("T");
			if(moddate.length>0 && typeof moddate[0] === "string"){
				moddate = moddate[0].split("-");
			}
			if(moddate.length===3){
				moddate = ''+moddate[0]+'-'+moddate[1]+'-'+moddate[2];
			} else {
				moddate = "";
			}
			modtext += ' on '+appdb.utils.FormatISODate(moddate);
		}
		modtext += '</b> <a class="moddetails" href="#"><span style="font-size:8pt"><i>(more...)</i></span></a>';
		modrow.find("td").html(modtext);
		modrow.find("a.moddetails").click(function(){
			showModerationDetails(d.application);
		});
		modrow.show();
	}
	
	function showAppDelInfo(e,d) {
		e = e || null;
		d = d || {};
		var delrow;
		if ( e === null ) {
			delrow = $($.find(".app-delrow"));
		} else {
			delrow = $(e).find(".app-delrow");
		}
		var deleter = d.application.deleter || '';
		var deletedOn = d.application.deletedOn || '';
		var deltext = '<br/><b>Deleted';
		if (deleter != '') {
			deltext += ' by <a href="#" onclick="appdb.views.Main.showPerson({id: '+deleter.id+'},{mainTitle: \''+deleter.firstname+" "+deleter.lastname+'\'});">'+deleter.firstname+' '+deleter.lastname+'</a>';
		} else {
			deltext += ' by an unknown user ';
		}
		if (deletedOn!= '') {
			var deldate = deletedOn.split("T");
			if(deldate.length>0 && typeof deldate[0] === "string"){
				deldate = deldate[0].split("-");
			}
			if(deldate.length===3){
				deldate = ''+deldate[0]+'-'+deldate[1]+'-'+deldate[2];
			} else {
				deldate = "";
			}
			deltext += ' on '+appdb.utils.FormatISODate(deldate);
		}
		deltext += '</b>';
//	   	deltext += ' <a class="deldetails" href="#"><span style="font-size:8pt"><i>(more...)</i></span></a>';
		delrow.find("td").html(deltext);
//		delrow.find("a.moddetails").click(function(){
//			showDeletionDetails(d.application);
//		});
		delrow.show();
	}
	
	function populateAppDetails(e,id) {
		var recordFound = true;
		var _endpoint = appdb.config.endpoint.baseapi;
		var u = '', cid = 0;
		$(e).hide();
		showAjaxLoading();
		$($.find("a.app-mod")).hide();
		$($.find("a.app-del")).hide();
		$($.find("a.app-edit")).hide();
		if ( userID != null ) {
			u = "?userid="+userID+"&passwd="+$.cookie('cookpass');
			u += "&cid="+cid+"&src="+reqsrc;
		} else {
			$($.find("a.app-bm")).hide();
			u = "?cid="+cid+"&src="+reqsrc;
		}
		if ( id != '' && id != 0 ) {	// show existing app
			var dat = new appdb.utils.rest({
				endpoint: _endpoint+"applications/"+id+u,
				async: true,
				authorization : {
				   type : appdb.utils.rest.authorization.types.query,
				   mode : appdb.utils.rest.authorization.modes.authonly
			   }
			}).create({},{
				success: function(d) {
					if ( d.application ) { // record was found
						var isTool = d.application.tool == "true"?true:false;
						if (d.application.bookmarked == "true") $($.find("a.app-bm img")).attr("src","/images/star2.png");
						var titlebar;
					    if ( detailsStyle == 1) titlebar = $("#detailsdlg"+dialogCount+":last div span"); else titlebar = $(".detailsdlg:last div span");
						if (id===null) titlebar[0].innerHTML = 'New Application/Tool';
						if (isTool) {
							$("#disciplineRow"+dialogCount).hide();
							$("#subdisciplineRow"+dialogCount).hide();
							if(titlebar.length>0){
								titlebar[0].innerHTML = 'Tool Details - <I>'+d.application.name+'</I>';
							}
						} else {
							if(titlebar.length>0){
								titlebar[0].innerHTML = 'Application Details - <I>'+d.application.name+'</I>';
							}
						}
						if (detailsStyle == 0 ) $(titlebar.parent()[0]).hide();
						$(e).find("img.app-logo").attr("src",appLogo(d.application));
						$(e).find("span.app-type").html((d.application.tool == "true"?"Tool":"Application"));
						$(e).find("span.app-name").html(d.application.name);
						appdb.views.Main.setNavigationTitle(d.application.name);
						$(e).find("span.app-desc").html(d.application.description);

						//disciplines
						var disciplines = d.application.discipline;
						if ( ! $.isArray(disciplines) ) disciplines = [disciplines];
						for (i=0; i<disciplines.length; i++) {
							if (disciplines[i] && disciplines[i].val) $(e).find("span.app-domains").append($('<span class="app-domain"><a href="#" onclick="appQuickLink('+disciplines[i].id+',4,{mainTitle : \''+disciplines[i].val()+'\'});">'+disciplines[i].val()+'</a></span>'));
						}
						separateMultipleItems($(e).find("span.app-domain"));

						//subdisciplines
						var subdisciplines = d.application.subdiscipline;
						if ( ! $.isArray(subdisciplines) ) subdisciplines = [subdisciplines];
						for (i=0; i<subdisciplines.length; i++) {
							if (subdisciplines[i] && subdisciplines[i].val) $(e).find("span.app-subdomains").append($('<span class="app-subdomain"><a href="#" onclick="appQuickLink('+subdisciplines[i].id+',5,{mainTitle : \''+subdisciplines[i].val()+'\'});">'+subdisciplines[i].val()+'</a></span>'));
						}
						separateMultipleItems($(e).find("span.app-subdomain"));
						$(e).find("span.app-subdomain").each(function(){
							if ( $(this).text() == '' ) $(this).attr("edit_isempty","true").html('<i>n/a</i>');
						});

						if (d.application.moderated) {
							if (d.application.moderated == "true") showAppModInfo(e,d);
						}
						if (d.application.deleted) {
							if (d.application.deleted == "true") showAppDelInfo(e,d);
						}
						$(e).find("p.app-abstract").html(d.application["abstract"]);
						$(e).find("span.app-status").html(d.application.status.val());
						if(managedAppUrls){
							managedAppUrls.destroy();
							managedAppUrls = null;
						}
						if ( d.application.url ) {
							$(e).find("span.app-urls").empty();
							var urls = d.application.url;
							if ( !$.isArray(urls) ) urls = [urls];

							//TODO : replace with managed code
							$(e).find("span.app-urls").append("<div id='applicationurlscontainer' class='hideonedit'></div>");
							if(managedAppUrls){
								managedAppUrls.destroy();
								managedAppUrls = null;
							}
							managedAppUrls = new appdb.views.ApplicationUrls({container : $(e).find("span.app-urls > #applicationurlscontainer").first()});
							managedAppUrls.render(urls);
							
							/*for(i=0;i<urls.length;i++) {
								if ( urls[i].val ) $(e).find("span.app-urls").append('<span class="app-url"><a target="_blank" href="'+urls[i].val()+'">'+urls[i].type+'</a></span> ');
							}*/
							//separateMultipleItems($(e).find("span.app-url"));
							//$(e).find("span.app-urls > .app-url , span.app-urls > .comboseperator").hide();
						}
						if ( d.application.country ) {
							$(e).find("span.app-countries").empty();
							var c = d.application.country;
							var inh;
							if (! $.isArray(c)) c = [c];
							for(i=0;i<c.length;i++) {
								if ( c[i].inherited == "true" ) inh = ' inherited-country'; else inh = '';
								var cflag = '<span class="app-country'+inh+'">'+'<a href="#" onclick="appQuickLink('+c[i].id+',2,{mainTitle:\''+c[i].val()+'\'});">'+c[i].val()+'</a>'+'</span> <span class="app-countryFlag">';
								var ciso = c[i].isocode.toLowerCase().split("/");
								for (j=0;j<ciso.length;j++) {
									cflag = cflag + '<img border="0" src="/images/flags/'+ciso[j]+'.png" style="vertical-align: middle;border:1px solid #BFBFBF"/> ';
								}
								cflag = cflag + '</span> ';
								$(e).find("span.app-countries").append(cflag);
							}
							separateMultipleItems($(e).find("span.app-countryFlag"));
						}
						if ( d.application.vo ) {
							$(e).find("span.app-vos").empty();
							var v = d.application.vo;
							if ( ! $.isArray(v)) v = [v];
							for(i=0;i<v.length;i++) {
								$(e).find("span.app-vos").append('<span class="app-vo">'+'<a href="#" onclick="appdb.views.Main.showVO(\''+v[i].name+'\',{mainTitle: \''+v[i].name+'\'});">'+v[i].name+'</a>'+'</span> ');
							}
							separateMultipleItems($(e).find("span.app-vo"));
						}
						if ( d.application.middleware ) {
							$(e).find("span.app-mws").empty();
							var v = d.application.middleware;
							if ( ! $.isArray(v)) v = [v];
							for(i=0;i<v.length;i++) {
								$(e).find("span.app-mws").append('<span class="app-mw">'+'<a href="#" onclick="appQuickLink(\''+v[i].val()+'\',1,{mainTitle:\''+v[i].val()+'\'});">'+(v[i].comment || v[i].val())+'</a>'+'</span> ');
							}
							separateMultipleItems($(e).find("span.app-mw"));
						}
						var d1 = d.application.addedOn.split("T");
						if(d1.length>0 && typeof d1[0] === "string"){
							d1 = d1[0].split("-");
						}
						if(d1.length===3){
							d1 = ''+d1[0]+'-'+d1[1]+'-'+d1[2];
						} else {
							d1 = "";
						}
						//d2 = d2.replace(/-(.)-/,"-0$1-").replace(/-(.)$/,"-0$1");
						$(e).find("span.app-addedon").html("Added on "+appdb.utils.FormatISODate(d1));
						if ( d.application.owner ) {
							if ( d.application.owner.id !== undefined ) {
								$(e).find("span.app-addedby").html('<a href="#" onclick="appdb.views.Main.showPerson({id: '+d.application.owner.id+'},{mainTitle: \''+d.application.owner.firstname+" "+d.application.owner.lastname+'\'});">'+d.application.owner.firstname+" "+d.application.owner.lastname+'</a>').prev().append("<span style='padding-right:3px;'>, by </span>");
//								$(e).find("span.app-addedby").append(" <img style='vertical-align: middle' border='0' src='"+personImage(d.application.owner)+"' width='24px' height='24px'/>");
							}
						}
						if(managedSciCons){
							managedSciCons.destroy();
							managedSciCons = null;
						}
						if(typeof d.application.contact === "undefined"){d.application.contact=[];$(e).find("#mainscicondiv"+dialogCount +" .mainscicontitle").hide();}
						managedSciCons= new appdb.views.RelatedContactList({container : $("#managedSciConDiv"),permissions:d.application.permissions,data:d.application,useToggleButton:true});
						managedSciCons.render();
						managedSciCons.subscribe({event : "itemselected", callback : function(v){
								var item = v.item;
								if(item._isSelected==true){
									v.item._itemData.toRemove = true;
									//$(item.dom).find(".selectedtext:last").text("to be removed");
									$(item.dom).addClass("toberemoved");
								}else{
									$(item.dom).find(".selectedtext:last").text("");
									$(item.dom).removeClass("toberemoved");
									v.item._itemData.toRemove = false;
								}
						},caller : managedSciCons});


						delete userAppPrivs;
						userAppPrivs = null;
						if ( (userRole == 5) || (userRole == 7) ) {
							var appmod = $($.find("a.app-mod"));
							if ( d.application.moderated ) if ( d.application.moderated == "true" ) {
								appmod.find("span").html('Unmoderate');
							}
							appmod.click(function(){
								moderateApplication(d.application.id,d.application.moderated);
							});
							appmod.show();
						}
						var perms = d.application.permissions || null;
						if ( perms !== null ) {
							var a;
							var acts = perms.action || null;
							if (acts !== null) {
								userAppPrivs = new Array();
								if (!$.isArray(acts)) {a = new Array();a.push(acts)} else {a = acts}
								for (i=0;i<a.length;i++) {
									if (id != 0) {
										$($.find("a.app-edit")).show();
										var appDeleted = d.application.deleted || false;
										if ( ! appDeleted ) {
											if ( a[i].id == 4 ) $($.find("a.app-del")).show();
										}
									} 
									userAppPrivs.push(a[i].id);
									makeAppElementEditable(e,a[i].id);
								}
							}
						}
						$(e).find("div.reportAbuse a").click(function(){
							if (userID !== null) {
								appdb.views.Main.showReportAbuse({id: d.application.id ,type:'application',name:d.application.name});
							} else {
								var reportAbuseDlg = $('<div title="Report a Problem"><p><span class="ui-icon ui-icon-info" style="float:left; margin:0 7px 20px 0;"></span>If you wish to file a report about a problem regarding this application, please <a class="login" href="#" style="color:#D96B00;text-decoration:none;">login</a> first using your EGI SSO account.<br/><br/>If you don\'t have an EGI SSO account you can acquire one <a style="color:#D96B00;text-decoration:none;" href="http://www.egi.eu/about/intranet/sso" target="_blank">here</a></p></div>');
								reportAbuseDlg.dialog({
									dialogClass: 'info',
									autoOpen: true,
									resizable: false,
									width:400,
									height:190,
									modal: true,
									buttons: {
										OK: function() {
											$(this).dialog('close');
										}
									}
								});	
								reportAbuseDlg.find("a.login").click(function(){
									reportAbuseDlg.dialog('close');
									login();
								});
							}
						});
						$("#ratingdiv"+dialogCount).append('<div id="ratingreport" style="width:100%" ></div>');
						ratingReport = new appdb.components.RatingReport({container:$("#ratingreport")});
						ratingReport.load({query: {type:"both",appid:d.application.id}});
						populateTags(id,e,d);
						populateRatings(id,e,d);
						makeAppDocs(d,dlgHeight);
						hideAjaxLoading();
						$(e).show();
						dijit.byId("ratingdiv"+dialogCount).resize();
						if ( detailsStyle == 1 ) {
							var ee = $(e).parent().parent().parent().parent();
							ee.css("position","absolute");
							ee.css("top", ( $(window).height() - ee.height() ) / 2+$(window).scrollTop() + "px");
							ee.css("left", ( $(window).width() - ee.width() ) / 2+$(window).scrollLeft() + "px");
						}
					} else { //record not found
						hideAjaxLoading();
						$(e).parent().parent().parent().html('<div style="text-align: center"><img alt="error" width="32px" src="/images/error.png" style="vertical-align: middle"/> <b>Record not found</b></div>');
						$(".appviewtoolbar").hide(); 
					}
					
		 		}
			}).call();
			delete dat;
			var dat = new appdb.utils.rest({
				endpoint: appdb.config.endpoint.baseapi+"applications/"+id+"/relatedapps"+u,
				async: true
			}).create({},{
				success: function(d) {
					if (d.relatedapp) {
						var apps = d.relatedapp;
						if (! $.isArray(apps)) apps = [apps];
						var ul = $(e).find("div.relatedapps ul");
						ul.css('margin-top','-15px');
						var li;
						var maxDescLen;
						var app;
						var s;
						var s_rank;
						for (i=0;i<apps.length;i++) {
							if (apps[i].application) {
								app = apps[i].application;
								li = ul.append('<li style="float: right"></li>').find("li:last");
								if ( app.name.length > 10 ) {
									maxDescLen=40-app.name.length-10;
								} else {
									maxDescLen=40;
								}
								s = "<a href=\"#\" title='"+app.name+"' onclick='appdb.views.Main.showApplication({id: "+app.id+"}, {mainTitle: \""+app.name+"\"});'><img border='0' src='"+appLogo(app)+"' height='50px'>"+app.name+"<span>"+app.description.substr(0,maxDescLen);
								if (app.description.length > maxDescLen) s = s + "...";
								if (Right(''+apps[i].rank,1) == 1) {
									s_rank = apps[i].rank+'st';
								} else if (Right(''+apps[i].rank,1) == 2) {
									s_rank = apps[i].rank+'nd';
								} else if (Right(''+apps[i].rank,1) == 3) {
									s_rank = apps[i].rank+'rd';
								} else s_rank = apps[i].rank+'th';
								s = s + "<br/><br/><i>Relation Rank: </i>"+s_rank;
								s = s + "</span><span>"+app.description+"<p/></span></a>";
								li.html(s);
							}
//							if (i==4) {
//								if (apps.length>5) {
//									ul.parent().append('<span style="margin-top: 10px; float: right;"><a href="#" onclick="appdb.views.Main.showRelatedApps({appid:'+id+'},{mainTitle:\'Related\'});">Show all</a></span>');
//								}
//								break;
//							}
						}
						$("div.relatedapps").css('max-height','600px');
						$("div.relatedapps").parent().append('<span style="margin-top: 10px; float: right;"><a href="#" onclick="appdb.views.Main.showRelatedApps({appid:'+id+'},{mainTitle:\'Related\',appname:\''+apps[0].parentname+'\'});">Show all</a></span>');
						animateRelatedApps();
					} else {
						$("div.relatedapps").hide();
						$("div.relatedapps").parent().css('border','none');
					}
				}
			}).call();
			delete dat;
		} else {	// register new application
			hideAjaxLoading();
			delete userAppPrivs;
			userAppPrivs = new Array(4,5,6,7,8,9,10,11,12,13,14,15,16,20,23);
			for(i=0;i<userAppPrivs.length;i++) {
				makeAppElementEditable(e,userAppPrivs[i]);
			}	
			$(e).show();
			$($.find("a.app-bm")).hide();
			$(e).find("img.app-logo").attr("src","/images/app.png");
			$(e).find("span.app-name").text("");
			$(e).find("span.app-desc").text("");
			$(e).find("p.app-abstract").html(" ");
			$(e).find("span.app-countries").prev().prev().remove();
			$(e).find("span.app-countries").prev().remove();
			$(e).find("span.app-countries").remove();
			var canSetOwner = false;
			var dat = new appdb.utils.rest({
				endpoint: appdb.config.endpoint.baseapi+"people/"+userID,
				async: false
			}).create().call();
			if ( dat.person ) if ( dat.person.privileges ) if ( dat.person.privileges.action ) {
				var acts = dat.person.privileges.action;
				if ( ! $.isArray(acts) ) acts = [acts];
				for (i=0;i<acts.length;i++) {
					if (acts[i].id == 23) {
						canSetOwner = true;
						break;
					}
				}
			}delete dat;
			if ( ! canSetOwner ) { 
				$(e).find("span.app-addedby").remove();
			} else {
				$(e).find("span.app-addedby").prev().append("Added by ");
				$(e).find("span.app-addedby").text(userFullname);
			}
			$("div.reportAbuse").hide();
			//onAppEdit(null);
		}
	}

	function hideRatingTab() {
		var navdiv = dijit.byId("navdiv"+dialogCount);
		var ratingdiv = dijit.byId("ratingdiv"+dialogCount);
		if (typeof navdiv !== "undefined") {
			if ( typeof ratingdiv !== "undefined" ) navdiv.removeChild(ratingdiv);
		}
	}

	function onAppEdit(entryid) {
			$('editapp'+dialogCount).addClass("editmode");
			$($.find("a.app-edit")).hide();
			hideRatingTab();
			$("span.app-rating").parent().parent().hide();
			$("span.inherited-country").next().remove();$("span.inherited-country").remove();
			$("#vodiv"+dialogCount).find("span[edit_name='vo']").attr("edit_data",voData);
			$("#mwdiv"+dialogCount).find("span[edit_name='mw']").attr("edit_data",mwData);
			$("span[edit_name='statusID']").attr("edit_data",statusData);
			$("span[edit_name='countryID']").attr("edit_data",countryData);
			$("span[edit_name='url']").attr("edit_data",urlData);
			$("span[edit_name='domainID']").attr("edit_data",domainData);
			$("span[edit_name='subdomainID']").attr("edit_data",subdomainData);
			$("span[edit_name='addedBy']").attr("edit_data",peopleData);
			$("a.relatedapps").click();
			$("div.altRelatedApps").hide();
			$("div.relatedapps").parent().empty().css("border-left","");
			$("div.relatedapps").hide();
			editForm('editapp'+dialogCount); 
			if ( entryid === null ) { 
				if ( $("#newapphint"+dialogCount)[0] == undefined )
					$("#navdiv"+dialogCount).parent().height("90%");
					$("#navdiv"+dialogCount).height("90%");
					$(".detailsdlgcontent:last").height("90%");
					$(".detailsdlgcontent:last").prepend("<span id='newapphint"+dialogCount+"' class='newapphint'><div><b>Hint</b>: additional information, like associated VOs, Countries, middleware(s), Tags, People etc, will be available for edit after saving.</div></span>");
			}
			$("#abstractdiv"+dialogCount+" textarea").text($("#abstractdiv"+dialogCount+" textarea").text().replace(/<BR>/ig,"\n").replace(/<BR\/>/ig,"\n"));
			$('#regiondiv'+dialogCount).hide();
			$(".ngirow").hide();    
			
			if (hasAppPriv(12)) $('#addcountry'+dialogCount).show();
			if (hasAppPriv(13)) $('#adddomains'+dialogCount).show();
			if (hasAppPriv(13)) $('#addsubdomains'+dialogCount).show();
			if (hasAppPriv(13)) $('#addvos'+dialogCount).show();
			if (hasAppPriv(14)) editAppUrls();//$('#addurldiv'+dialogCount).show();
			if (hasAppPriv(15)) $('#editdoc'+dialogCount).show();
			if (hasAppPriv(16)) editSciCon();
			if (hasAppPriv(20)) $('#addmws'+dialogCount).show();
			if (hasAppPriv(8)) {
				if ( $('#uploadlogo'+dialogCount).length == 0 ) {
					$('#applogo'+dialogCount).parent().html($('#applogo'+dialogCount).parent().html()+'<div id=\'uploadlogo'+dialogCount+'\'>Upload image...</div>');
				}
				$('#applogo'+dialogCount).attr('onmouseover',''); 
				$('#applogo'+dialogCount).attr('onmouseout',''); 
				prepareUpload();
			}
			$(".listhandlercontainer").addClass("editmode");
			//TODO : replace with managed code
			$("span.app-urls:last > .app-url").append("<br/>").show();
			$(".hideonedit").hide();
			$(":input[name='documents']:last").after("<input type='hidden' name='initialDocuments'/>");
			$(":input[name='initialDocuments']:last").val(serializeAppDocs());
			appdb.utils.DataWatcher.Registry.activate("application");
	}

	function appDocDataToJSON(data) {
		var _intAuthors = [];
		var auths = "<span>"+data[10].toString()+"</span>";
		$(auths).find("a").each(function(e){
			_intAuthors.push([$(this).attr("data-authorid"), $(this).attr("data-authorMain")]);
		});
		var _extAuthors = [];
		$(auths).find("span").each(function(e){
			_extAuthors.push([$(this).attr("data-authorname"), $(this).attr("data-authorMain")]);
		});
		return data2={
			'id': $(data[0][0]).attr("data-docid"),
			'title': $(data[0][0]).text(),
			'url': $(data[0][0]).find("a").attr("href"),
			'type': $(data[1][0]).text(),
			'typeID': $(data[1][0]).attr("data-doctypeid"), 
			'conference': data[2],
			'volume': data[3],
			'pageStart': (data[4].split(' - '))[0],
			'pageEnd': (data[4].split(' - ')[1]),
			'year': data[5],
			'publisher': data[6],
			'isbn': data[7],
			'proceedings': data[8],
			'journal': data[9],
			'intAuthors': _intAuthors,
			'extAuthors': _extAuthors
		};
	}
	function serializeAppDocs(){
	  if ( docgrid.model !== undefined ) {
		 var data;
		 var allData='<documents>';
		 for (i=0; i<docgrid.model.count; i=i+1) {
			 data=docgrid.model.getRow(i);
			 var data2 = JSON.stringify(appDocDataToJSON(data));
			 allData=allData+'<document>'+encode64(encodeURI(data2),false)+'</document>';
		 }
		 allData=allData+'</documents>';
		 return allData;
	 } else return 'UNCHANGED';
	}
	function validateApp() {
		var i, found = false, invalid = [], mandatory = {
			"name" : "name",
			"description" : "description",
			"abstract":"abstract",
			"statusID" : "status"
		}, lists = {
			"vo" :  {name: "vo"},
			"countryID" :  {name: "country"},
			"mw" :  {name: "middleware"},
			"addedBy" : {name : "added by"}/*,
			"combo_url" : {name : "Url type"},
			"url" : {name : "Url value"}*/
		};
		if(!( $('#:input[name="tool"]:last').is(":checked"))){
			lists.domainID= {name: "descipline", required : true};
			lists.subdomainID = {name: "subdiscipline"};
		}
		
		for(i in mandatory){
			if ($.trim($(':input[name="'+i+'"]:last').val()) === '' ) {
				invalid[invalid.length] = mandatory[i];
			}
		}
		for(i in lists){
			found = false;
			if(lists[i].required && $('#details :input[name^="'+i+'"]').length == 0) {
				found = true;
			} else{
				$('#details :input[name^="'+i+'"]').each(function(index,elem){
					if($.trim($(elem).val()) === '' ||  $.trim($(elem).val()) === appdb.config.defaults.api[lists[i].name]){
						found = true;
					}
				});
			}
			if(found == true){
				invalid[invalid.length] = lists[i].name;
			}
		}
		if(managedAppUrlsEditor !== null){
		 if(managedAppUrlsEditor.canAddNew() !== true){
		  invalid[invalid.length] = "Url values";
		 }
		}
		if(invalid.length>0){
			var html = '<div title="Error"><div><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>Please fill the mandatory field'+((invalid.length>1)?'s':'')+'  displayed bellow:</p></div><ul style="padding:0px;margin:0px;margin-left:35px;">';
			for(i=0; i<invalid.length; i+=1){
				html += "<li style='padding:0px;margin:0px;padding-left:5px;'>" + invalid[i] + "</li>";
			}
			html += '</ul></div>';
			$(html).dialog({
				dialogClass: 'alert',
				autoOpen: true,
				resizable: false,
				modal: true,
				buttons: {
					OK: function() {
						$(this).dialog('close');
					}
				}
			});	
			return false;
		}
		$(':input[name="documents"]:last').val(serializeAppDocs());
		$("#details").fadeOut();
		$(".app-mw").each(function(){
			$(this).find(":input:last").val($("<span>"+$(this).find(":input:last").val()+"</span>").text());
		});
		return true;
	}

	function addDoc(data) {
		delete editDocDlg;
		editDocDlg = new dojox.Dialog({
			"id" : "editDocDialog",
			"title": "Edit publication data",
			"style": "width: 60%",
			onCancel : function(){
				this.destroyRecursive(false);
			}
		});
		if ( data !== undefined ) {
			var data2=appDocDataToJSON(data);
			editDocDlg.setHref("apps/editdoc?data="+encodeURIComponent(JSON.stringify(data2)));
		} else editDocDlg.setHref("apps/editdoc");
		editDocDlg.show();
		try {
			dojo.disconnect(dijit.byId("detailsdlg"+dialogCount)._modalconnects.pop());
		} catch(e) {}
	}

	function remDoc() {
        if (docgrid.selection.getFirstSelected() >=0 ) docgrid.removeSelectedRows();
	}
	
	function editDoc() {
        var r=docgrid.selection.getFirstSelected();
        if (Number(r) >= 0 ) addDoc(docgrid.model.getRow(r));
	}

	function toggleBookmark() {
		if ( $('img[src^="/images/star"]').attr('src').substr(12,1) == "1" ) 
			$('img[src^="/images/star"]').attr('src','/images/star2.png');
		else
			$('img[src^="/images/star"]').attr('src','/images/star1.png');
		sendform($('#bookmarkapp'+dialogCount)[0]);
	}

	var flagImages = new Array();
	function populateFlagImages() {
		jQuery.support.cors = true;
		var regional = new appdb.utils.rest({
			endpoint: appdb.config.endpoint.baseapi+'regional',
			async: true 
		}).create({},{
			success: function(regional) {
				for (i in regional.country) {
					flagImages[''+regional.country[i].id] = regional.country[i].isocode.toLowerCase();
				}
			}
		}).call();
	}

	populateFlagImages();

	function fixCountryFlags() {
		$("span[edit_name='countryID']").each(function(){
			var e = $(this).children("div:first");
			var cid=$(this).find(':input:last').val();
			var flags;
			if (flagImages[cid] !== undefined) flags = flagImages[cid].split("/");
			var flag;
			if (flags !== undefined) flag = "/images/flags/"+flags[0]+".png";
			if(flag){
				$(this).next().find('img').css({"display" : "inline-block"}).attr('src',flag);
			}else{
				$(this).next().find('img').css({"display" : "none"}).attr('src','');
			}
			$(this).find(':input:last').prev()[0].setAttribute('value',$(this).find(':input:last').prev().val());
		});
	}

	function _fixCountryFlags() {
		var cid=focusedDijitItem.find(':input:last').val();
		var flags;
		if (flagImages[cid] !== undefined) flags = flagImages[cid].split("/");
		var flag;
		if (flags !== undefined) flag = "/images/flags/"+flags[0]+".png";
		focusedDijitItem.next().find('img').attr('src',flag);
		focusedDijitItem.find(':input:last').prev()[0].setAttribute('value',focusedDijitItem.find(':input:last').prev().val());
	}

	function setURL() {
		var s = focusedDijitItem.find(':input:last').val();
		s = $.trim(s);
		focusedDijitItem.find(':input:last')[0].setAttribute('value',s);
	}

	function editSciCon() {
		$("#mainscicondiv"+dialogCount).show();
		$("#addSciConDiv"+dialogCount).show();
		if(managedSciCons && managedSciCons!=null){
			managedSciCons.EditMode(true);
			$("#mainscicondiv"+dialogCount +" .mainscicontitle").show();
			$(managedSciCons.dom).show();
			$("#editapp"+dialogCount).addClass("editmode");
		}
		
		$("a.scicontoggler").attr("title","").css({"cursor":"default"}).removeAttr("onclick");
	}
	function editAppUrls(){
	 $("#urldiv"+dialogCount).after("<div id='urldivEditor' class='appurls_editor'></div>").hide();
	 if(managedAppUrlsEditor !== null){
	  managedAppUrlsEditor.reset();
	  managedAppUrlsEditor = null;
	 }
	 managedAppUrlsEditor = new appdb.views.ApplicationUrlsEditor({container : $("#urldivEditor")});
	 managedAppUrlsEditor.render(((managedAppUrls)?managedAppUrls._data:[]),"type");
	}
	function addSciConOld() {
		var d = new dojox.Dialog({
			"title": "Associate person to application",
			"style": "width: 60%"
		});
		d.setHref('people/ppllist');
		d.show();
		try {
			dojo.disconnect(dijit.byId("detailsdlg"+dialogCount)._modalconnects.pop());
		} catch(e) {}
	}
	function addSciCon() {
		var relcon = new appdb.components.RelatedContacts({excluded:managedSciCons._listData});
		relcon.subscribe({event:"close", callback : function(v){
			if(managedSciCons && managedSciCons != null){
				managedSciCons.addNewContacts(this.views.peopleList.selectedDataItems.get());
				managedSciCons.render();
				managedSciCons.checkForChanges();
			}
		},caller:relcon});
		relcon.load({query:{flt:"",pagelength:12,userid:userID},ext:{}});
	}
	
	function addSciConOld2() {
		var h=$("#SciConDiv"+dialogCount).html();
		h=h+' <span class="editable" edit_type="combo" edit_data="'+ed+'" edit_name="vo" edit_group="true"></span>';
		$("#vodiv"+dialogCount).html(h);
		var e=new editForm('editapp'+dialogCount);
	}
	
	function remSciCon() {
		$('#SciConDiv'+dialogCount).find('input').each(function(x){
			if ( $(this).attr('checked') != '' ) {$(this).parent().parent().remove();};
		});
	}

	function onAppUpdate(response,data) {
		if ( data.appID == "0" ) data.appID = '';
       
		try {
			dijit.byId("detailsdlg"+dialogCount).onCancel();
		} catch(e) {}
		if(data.appID===''){
            //from a newly registered application
            appdb.views.Main.showApplication({id: data.appID});
        }else{
            //from an application editing
            appdb.views.Main.refresh();
        }
	}

	function pplTabClick(e,i) {
		$(e).parent().find('li').each(function() {$(this).removeClass("active");});
		$(e).addClass("active");
		$(e).parent().parent().parent().find("div.tabdiv").hide();
		$(e).parent().parent().parent().find('#'+i+'div'+dialogCount).show();
		if ( i == "doc" ) {
			setTimeout(function(){makePersonDocs();},250);
		}
	}

	function appTabClick(e,i) {
		$(e).parent().find('li').each(function() {$(this).removeClass("active");});
		$(e).addClass("active");
		$(e).parent().parent().parent().find("div.tabdiv").hide();
		$(e).parent().parent().parent().find('#'+i+'div'+dialogCount).show();
		if ( i == "doc" ) {
			setTimeout(function(){makeAppDocs(entryid,dlgHeight);},250);
		}
	}

	function makePplDocs(pplID,dlgHeight) {
		makeDocs(appID,dlgHeight,'people','person');
	}

	function makeAppDocs(appID,dlgHeight) {
		makeDocs(appID,dlgHeight,'applications','application');
		var d = dijit.byId("navdiv"+dialogCount) || null;
		if ( d !== null ) d.resize();
	}

	function hideDocGridCols() {
		$("table.dojoxGrid-row-table").find("tr:first").each(function(){
			$($(this).find("th.dojoxGrid-cell").get(3)).hide();
		});
		$("table.dojoxGrid-row-table").find("tr:first").each(function(){
			$($(this).find("td.dojoxGrid-cell").get(3)).hide();
		});
		$("table.dojoxGrid-row-table").find("tr:first").each(function(){
			$($(this).find("th.dojoxGrid-cell").get(0)).hide();
		});
		$("table.dojoxGrid-row-table").find("tr:first").each(function(){
			$($(this).find("td.dojoxGrid-cell").get(0)).hide();
		});
		$("th.dojoxGrid-cell").click(function(){
			setTimeout(function(){hideDocGridCols();},50);
		});
	}



	function makeDocs(appID,dlgHeight,u1,u2) {
		if ( docgrid == false ) {
//			var app = new appdb.utils.rest({
//				endpoint: appdb.config.endpoint.baseapi+u1+'/'+appID,
//				async: false
//			}).create({}).call();
//			var docs = app[u2].publication || null;
			var docs = appID[u2].publication || null;
			docgrid = new dojox.grid.Grid({},"docgrid"+dialogCount);
			var data = [];
			if (docs !== null) {
				if (! $.isArray(docs)) {docs = [docs];}
				for (i=0; i<docs.length; i++) {
					var doc = docs[i];
					if (doc.startPage == "") {
						var pageStart = doc.endPage;
						var pageEnd = "";
					} else {
						var pageStart = doc.startPage;
						var pageEnd = doc.endPage;
					}
					if (pageStart == "0") pageStart = "";
					if (pageEnd == "0") pageEnd = "";
					if (pageStart == pageEnd) pageEnd = "";
					var pages = ""+pageStart;
					if ( pageEnd != "" ) pages+=" - "+pageEnd;
					if (doc.url != "") {
						var title = "<a href=\""+doc.url+"\" target=\"_blank\">"+doc.title.replace(/'/g,"\\'")+"</a>";
					} else {
						var title = doc.title;
					}
					title = "<span data-docid=\""+doc.id+"\">"+title+"</span>"
					var authors = [];
					if (doc.author) {
						if ( ! $.isArray(doc.author)) {doc.author = [doc.author];}
						for (j=0; j<doc.author.length; j++) {
							var author = doc.author[j];
							var authorstr = '';
//							if (author.main) authorstr = "<b>";
							if (author.type == "external") {
								if ( typeof author.extAuthor !== "undefined" ) {
									authorstr += " <span data-authorMain=\""+author.main+"\" data-authorname=\""+author.extAuthor.replace(/'/g,"\\'")+"\">"+author.extAuthor.replace(/'/g,"\\'")+"</span>";
								}
							} else {
								authorstr += " <a data-authorMain=\""+author.main+"\" data-authorid=\""+author.person.id+"\" href=\"#\" onclick=\"appdb.views.Main.showPerson({id: "+author.person.id+"},{mainTitle: '"+author.person.firstname.replace(/'/g,"\\'")+' '+author.person.lastname.replace(/'/g,"\\'")+"'})\">"+author.person.firstname.replace(/'/g,"\\'")+' '+author.person.lastname.replace(/'/g,"\\'")+"</a>";
							}
//							if (author.main) authorstr += "</b>";
							if (authorstr !== '') authors.push(authorstr);
						}
					}
					var doctype = "<span data-doctypeid=\""+doc.type.id+"\">"+doc.type.val()+"</span>";
					data.push([[title], [doctype], doc.conference, doc.volume, pages, doc.year, doc.publisher, doc.isbn, doc.proceedings, doc.journal, authors]);
				}
			}
			var model = new dojox.grid.data.Table(null, data);
			var view = {
			cells: [[
/*					{name: 'ID', rowSpan: 2, width:'0%'}, */
					{name: 'Title', rowSpan: 2, width:'20%'},
					{name: 'Type', rowSpan: 2, width:'5%'},
/*					{name: 'TypeID', rowSpan: 2, width:'0%'},*/
					{name: 'Conference', width:'20%'},	
					{name: 'Volume', width:'5%'},
					{name: 'Pages', width:'5%'},
					{name: 'Year', width:'3%'},
					{name: 'Publisher', width:'10%'},
					{name: 'ISBN', width:'10%'}                    
				],[
					{name: 'Proceedings'},
					{name: 'Journal', colSpan:3},
					{name: 'Authors', colSpan:2}
				]]
			};
			var structure = [ view ];
			docgrid.setModel(model);
			docgrid.setStructure(structure);
			detailsStyle = 0;
			if (detailsStyle == 0) docgrid.domNode.style.height = (document.body.clientHeight-200)+'px'; else docgrid.domNode.style.height = dlgHeight+'px';
			if ( detailsStyle == 1 ) {
				dojo.parser.parse(dojo.byId("detailsdlgcontent"+dialogCount));
			} else {
				dojo.parser.parse($(".detailsdlgcontent")[0]);
			}
			docgrid.render();
            // Force hide colums
			// hideDocGridCols();
		} 
	}

    function prepareUpload2() {
        $('#uploadlogo'+dialogCount).html('<iframe scrolling="no" style="width:110px; height:55px; border:none; overflow:hidden" src="apps/uploadframe"></iframe>');
	}
	
	function prepareUpload() {
        $('#uploadlogo'+dialogCount).html('<a href="#" onclick="prepareUpload2();">Change logo</a>');
    }

	function moderateApplication(appID,mstate) {
		var mtext;
		if (mstate == "true") {
			mtext = '<div title="Moderate/Unmoderate Application"><p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>Are you sure you wish to unmoderate this entry and make it visible to the public?</p></div>';
		} else {
			mtext = '<div title="Moderate/Unmoderate Application"><p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>Please provide a reason for moderating this entry and hidding it from the public:</p><div class="modinput" style="padding:10px; border:1px solid grey"><p><textarea maxlength="512" dojoType="dijit.form.Textarea" name="modreason"></textarea></p></div></div>';
		}
		var $delAppDialog = $(mtext).dialog({
			dialogClass: 'alert',
			autoOpen: false,
			resizable: false,
			height:'auto',
			modal: true,
			buttons: {
				OK: function() {
					var _data;
					_data = {
						id: appID,
						userid: userID
					}
					if (mstate != "true") {
						_data.reason = $('textarea[name="modreason"]').val();
					}
					$.ajax({
						url: '/apps/togglemod',
						data: _data,
						success: function(data) {
							try {
								console.log(data);
								data = JSON.parse(data);
							} catch (ex) {
								errh = new appdb.views.ErrorHandler();
								errh.handle({status:"Server error", description: "An error occured while committing your action.", source: ex});
								return;
							}
							appmod = $($.find(".app-mod"));
							appmod.unbind('click');
							if ( data.moderated == "1" ) {
								$(".app-mod").find("span").html('Unmoderate');
								$(".app-modrow").find("td").empty();
								var modinfo = {};
								modinfo.application = {};
								modinfo.application.moderator = {};
								modinfo.application.moderator.id = data.moderatorID;
								modinfo.application.moderator.firstname = decode64(data.moderatorFirstname);
								modinfo.application.moderator.lastname = decode64(data.moderatorLastname);
								modinfo.application.id = data.id;
								modinfo.application.name = decode64(data.name);
								modinfo.application.moderated = "true";
								modinfo.application.moderatedOn = data.moderatedOn;
								modinfo.application.moderationReason = decode64(data.reason);
								showAppModInfo(null,modinfo);
								appmod.click(function(){
									moderateApplication(appID,"true");
								});
							} else {
								$(".app-mod").find("span").html('Moderate');
								$(".app-modrow").find("td").empty();
								$(".app-modrow").hide();
								appmod.click(function(){
									moderateApplication(appID,"false");
								});
							}
						}
					});					
					if ( $(".modinput textarea").length > 0 ) {
						try {
							dijit.byNode(dojo.query(".modinput textarea")[0]).destroyRecursive(false);
						} catch (e) {
						}
					}
					if ( $(".modinput").length > 0 ) $(".modinput").remove();
					$(this).dialog('close');
				},
				Cancel: function() {
					if ( $(".modinput textarea").length > 0 ) {
						try {
							dijit.byNode(dojo.query(".modinput textarea")[0]).destroyRecursive(false);
						} catch (e) {
						}
					}
					if ( $(".modinput").length > 0 ) $(".modinput").remove();
					$(this).dialog('close');
				}
			}
		});
		$delAppDialog.dialog('open');
		if ( $(".modinput").length > 0 ) dojo.parser.parse($(".modinput")[0]);
	}

    function deleteApplication(appID) {
		var $delAppDialog = $('<div title="Delete Application"><p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>Permanently delete application and associated data?</p></div>').dialog({
			dialogClass: 'alert',
			autoOpen: false,
			resizable: false,
			height:160,
			modal: true,
			buttons: {
				Delete: function() {
					sendform($('<form method="post" action="apps/delete"><input name="id" type="text" value="'+appID+'"/></form>')[0]);
					$(this).dialog('close');
					$(".appviewtoolbar").hide(); 
					if (detailsStyle == 1) {
						dijit.byId("detailsdlg"+dialogCount).onCancel();
					} else {
                       //goDetailsBack();
                       appdb.views.Main.closeCurrentView();
                    }
				},
				Cancel: function() {
					$(this).dialog('close');
				}
			}
		});
		$delAppDialog.dialog('open');
	}

    function toggleAbstract(elem) {
        jQuery.fn.center = function () {
            this.css("position","absolute");
            this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
            this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
            return this;
        };
        if ($("#abstractdiv"+dialogCount).is(":visible")) {
            $("#abstractdiv"+dialogCount).fadeOut("fast");
			$(elem).next().fadeIn("fast");
        } else {
            $("#abstractdiv"+dialogCount).fadeIn("fast");
			$(elem).next().fadeOut("fast");
        }
        if (detailsStyle == 1) setTimeout(function(){$("#detailsdlg"+dialogCount).center();},500);
    }

    function toggleSciCon() {
		jQuery.fn.center = function () {
            this.css("position","absolute");
            this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
            this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
            return this;
        };
        if ($("#managedSciConDiv").is(":visible")) {
            $("#managedSciConDiv").fadeOut("fast");
        } else {
            $("#managedSciConDiv").fadeIn("fast");
        }
        if (detailsStyle == 1) setTimeout(function(){$("#detailsdlg"+dialogCount).center();},500);
    }

	function onToggleBookmark() {
        if ( bmInfoDlg!== undefined ) dijit.popup.close(bmInfoDlg);
        bmInfoDlg = new dijit.TooltipDialog({
            title: 'Information',
            content: 'Item bookmark toggled'
		});
		setTimeout(function(){
			dijit.popup.open({
				popup: bmInfoDlg,
				parent: $('img[src^="/images/star"]')[0],
				around: $('img[src^="/images/star"]')[0],
				orient: {BL:'TL'}                    
			});
			setTimeout('dijit.popup.close(bmInfoDlg)',1000);
		},200);
    }

	function animateRelatedApps() {
		clearInterval(RelAppIntId);
		$("div.relatedapps").each(function() {
			if ($(this).find("li").length > 5) {
				var indx = 0;
				$(this).find("li").each(function(){
					if (indx <= 4) $(this).show(); else $(this).hide();
					indx++;
				});
				RelAppIntId = setInterval((function(e){
					return function() {
					if ( ($(e).find("li").length > 5) && ($(e).find("ul").is(":visible")) ) {
						$(e).find("ul").fadeOut("fast");
						setTimeout((function(e){
							return function() {
							$(e).find("ul").prepend($(e).find("li:last"));
//							$(e).find("li:last").remove();
						}})(e), 150);
						var ind = 0;
						$(e).find("li").each(function(){
							if (ind <= 4) $(this).show(); else $(this).hide();
							ind++;
						});
						$(e).find("ul").fadeIn();
					}
				}})(this), 10000);
			} else if ($(this).find("li").length == 0 ){
				$("div.relatedapps").parent().empty().css("border-left","");
			}
		});
	}

	var rebuildCountryData = function() {
		var ed = countryData;
        var h="";
        $("input[name^=countryID]").each(function(index,e){
            var v=$(this).prev().val();
            h=h+' <span class="editable app-country" edit_onchange="fixCountryFlags" edit_type="combo" edit_data="'+ed+'" edit_name="countryID" edit_group="true">'+v+'</span> <span class="editable app-countryFlag" edit_type="none"><img border="0" style="vertical-align:middle;border:1px solid #BFBFBF;" src=""/></span>';
            $(this).remove();
        });
        var ih='';
        $("#countryDiv"+dialogCount).find(".iCountryID").each(function(e){
            ih=ih+'<span class="iCountryID">'+$(this).html()+'</span> <span>'+$(this).next().html()+'</span>';
        });
        h=ih+h;
		$("#countryDiv"+dialogCount).html( h );
    };

	var canAddListItem = function(datatype,elems,def){
		var found = -1;
		def = $.trim(def || '');
		var invalidelem = null;
		$(':input[name^="'+datatype+'"]').each(function(index,elem){
			if($.trim($(elem).val()) === def ){
				found = (found<0)?index:found;
				invalidelem = $(elem);
			}
		});
		if(found>-1 && elems && elems.length>0){
			var ee = invalidelem.parent().parent();
			var prevColor = invalidelem.parent().parent().css("background-color") || "";
			ee.animate({"opacity":"0.5","background-color":"red"},300,function(){setTimeout(function(){ee.animate({"opacity":"1","background-color":prevColor},400);},10);});
		}
		
		return (found<0)?true:false;
	};

	var addCountry = function() {
		if(canAddListItem("countryID",$("#countryDiv"+dialogCount).find(".app-country")) === false)	return;
		
        rebuildCountryData();
        var h=$("#countryDiv"+dialogCount).html();
		var ed = countryData;
		h=h + '<span class="editable app-country" edit_onchange="fixCountryFlags" edit_type="combo" edit_data="'+ed+'" edit_name="countryID" edit_group="true"></span> <span class="editable app-countryFlag" edit_type="none"><img border="0" style="vertical-align:middle;border:1px solid #BFBFBF;" src=""/></span>';
		$("#countryDiv"+dialogCount).html(h);
		var e=new editForm('editapp'+dialogCount);
		fixCountryFlags();
		separateMultipleItems($("#countryDiv"+dialogCount).find("span.app-countryFlag"));
	};

	var remCountry = function() {
		if ( focusedDijitItem !== undefined ) {
			if ( focusedDijitItem.attr('edit_name') == 'countryID' ) {
				focusedDijitItem.next(".comboseperator").remove();
				focusedDijitItem.next().remove();
				focusedDijitItem.remove();
				separateMultipleItems($("#countryDiv"+dialogCount).find("span.app-countryFlag"));
			}
		}
	};

    function rebuildMWData() {
   		var ed = mwData;
		var h='';
        $("input[name^=mw]").each(function(index,elem){
            var v=$(elem).val();
            h=h+' <span class="editable app-mw" edit_type="combo" edit_combo_free="true"  edit_data="'+ed+'" edit_name="mw" edit_group="true">'+v+'</span>';
        });
        $("#mwdiv"+dialogCount).html(h);
    }

    function rebuildDomainData() {
		var ed = domainData;
		var h='';
        $("input[name^=domainID]").each(function(e){
            var v=$(this).prev().val();
			h=h+' <span class="editable app-domain" edit_type="combo"  edit_data="'+ed+'" edit_name="domainID" edit_group="true">'+v+'</span>';
        });
        $(".app-domains").html(h);
    }

    function rebuildSubdomainData() {
		var ed = subdomainData;
		var h='';
        $("input[name^=subdomainID]").each(function(e){
            var v=$(this).prev().val();
			h=h+' <span class="editable app-subdomain" edit_type="combo"  edit_data="'+ed+'" edit_name="subdomainID" edit_group="true">'+v+'</span>';
        });
        $(".app-subdomains").html(h);
    }

    function rebuildVOData() {
		var ed = voData;
		var h='';
        $("input[name^=vo]").each(function(e){
            var v=$(this).prev().val();
			h=h+' <span class="editable app-vo" edit_type="combo"  edit_data="'+ed+'" edit_name="vo" edit_group="true">'+v+'</span>';
        });
        $("#vodiv"+dialogCount).html(h);
    }

	var addMW = function() {
		if(canAddListItem("mw",$("#mwdiv"+dialogCount).find(".app-mw"),appdb.config.defaults.api.middleware) === false) return;

        rebuildMWData();
		var h=$("#mwdiv"+dialogCount).html();
   		var ed = mwData;
		h=h+' <span class="editable app-mw" edit_type="combo" edit_combo_free="true"  edit_data="'+ed+'" edit_name="mw" edit_group="true">'+appdb.config.defaults.api.middleware+'</span>';
		$("#mwdiv"+dialogCount).html(h);
		var e=new editForm('editapp'+dialogCount);
		separateMultipleItems($("#mwdiv"+dialogCount).find("span.app-mw"));
	}

	var addDomain = function() {
		if(canAddListItem("domain",$(".app-domains").find(".app-domain")) === false) return;

        rebuildDomainData();
		var h=$(".app-domains").html();
   		var ed = domainData;
		h=h+' <span class="editable app-domain" edit_type="combo" edit_data="'+ed+'" edit_name="domainID" edit_group="true">'+appdb.config.defaults.api.discipline+'</span>';
		$(".app-domains").html(h);
		var e=new editForm('editapp'+dialogCount);
		separateMultipleItems($(".app-domains").find("span.app-domain"));
	};

	var remDomain = function() {
		if ( focusedDijitItem !== undefined ) {
			var p=focusedDijitItem;
			if ( p.attr('edit_name') == "domainID" ) p.next(".comboseperator").remove(),p.remove(),separateMultipleItems($(".app-domains").find("span.app-domain"));
		}
	};

	var addSubdomain = function() {
		if(canAddListItem("subdomain",$(".app-subdomains").find(".app-subdomain")) === false) return;

        rebuildSubdomainData();
		var h=$(".app-subdomains").html();
   		var ed = subdomainData;
		h=h+' <span class="editable app-subdomain" edit_type="combo" edit_data="'+ed+'" edit_name="subdomainID" edit_group="true">'+appdb.config.defaults.api.subdiscipline+'</span>';
		$(".app-subdomains").html(h);
		var e=new editForm('editapp'+dialogCount);
		separateMultipleItems($(".app-subdomains").find("span.app-subdomain"));};

	var remSubdomain = function() {
		if ( focusedDijitItem !== undefined ) {
			var p=focusedDijitItem;
			if ( p.attr('edit_name') == "subdomainID" ) p.next(".comboseperator").remove(),p.remove(),separateMultipleItems($(".app-subdomains").find("span.app-subdomain"));
		}	
	};
		
	var addVO = function() {
		if(canAddListItem("vo",$("#vodiv"+dialogCount).find(".app-vo")) === false) return;

        rebuildVOData();
		var h=$("#vodiv"+dialogCount).html();
   		var ed = voData;
		h=h+' <span class="editable app-vo" edit_type="combo" edit_data="'+ed+'" edit_name="vo" edit_group="true">'+appdb.config.defaults.api.vo+'</span>';
		$("#vodiv"+dialogCount).html(h);
		var e=new editForm('editapp'+dialogCount);
		separateMultipleItems($("#vodiv"+dialogCount).find("span.app-vo"));
	};
	
	var remMW = function() {
		if ( focusedDijitItem !== undefined ) {
			var p=focusedDijitItem;
			if ( p.attr('edit_name') == "mw" ) {
				var id = p.find(":input[type='text']:last").val();
				validateItemRemoval("middleware",id,function(){p.next(".comboseperator").remove(),p.remove(),separateMultipleItems($("#mwdiv"+dialogCount).find("span.app-mw"));});
			}
		}
	};	
	var validateItemRemoval = function(type,id,callback){
		type = type.toLowerCase();
		if(managedSciCons && managedSciCons!=null ){
			var items = managedSciCons.filterItems(function(item){
				var i, len, d = item._itemData.contactItem || [];
				if($.isArray(d)==false){
					d = [d];
				}
				len = d.length;
				for(i=0; i<len; i+=1){
					var did = d[i].id;
					if(type === 'middleware'){
						if(did == 5){
							did = d[i].comment;
						}else{
							did = d[i].val();
						}
					}
					if(d[i].type.toLowerCase()==type && did==id ){
						if(typeof d[i].toRemove === "undefined" || (d[i].toRemove && d[i].toRemove==false)){
							d[i].toRemoveImplicit = true;
							return true;
						}
					}
				}
				return false;
			});
			if(items.length>0){
				var cont = document.createElement("div"), commands =  document.createElement("div"), cancel = document.createElement("span"), ok = document.createElement("span");
				$(commands).addClass("commands");
				$(cont).addClass("removeentitywarning");
				var msg = "There are contacts which have been set as experts on this " + ((type=='vo')?"virtual organization":type) +" listed bellow.<br/><ul>";
				for(i=0; i<items.length; i+=1){
					msg += "<li>" + items[i]._itemData.firstname + " " +  items[i]._itemData.lastname + "</li>";
				}
				msg += "</ul><br/>Clicking <b>continue</b> will remove the relevant entries saving the application. Click <b>cancel</b> to keep this item instead.";
				$(cont).append(msg);
				$(cont).append(commands);
				$(commands).append(ok).append(cancel);
				new dijit.form.Button({
					label: "Cancel",
					style: "float:right;padding:5px;",
					onClick: function() {
						appdb.views.ContactPointEditor.WarningDialog.hide();
					}
				},cancel);
				new dijit.form.Button({
					label: "Continue",
					style: "float:right;padding:5px;",
					onClick: function() {
						appdb.views.ContactPointEditor.WarningDialog.hide();
						var items = managedSciCons.subviews, len = items.length, i;
						for(i=0; i<len; i+=1){
							if(items[i]._itemData.contactItem){
								appdb.views.RelatedContactList.CheckForChanges(items[i]);
							}
						}
						callback();
					}
				},ok);
				if(appdb.views.ContactPointEditor.WarningDialog != null){
					appdb.views.ContactPointEditor.WarningDialog.hide();
					appdb.views.ContactPointEditor.WarningDialog.destroyRecursive(false);
				}
				appdb.views.ContactPointEditor.WarningDialog = new dijit.Dialog({
					title: "Associated contacts",
					content: cont,
					style: "width: 420px"
				});
				appdb.views.ContactPointEditor.WarningDialog.show();
				return;
			}
		}
		callback();
	};
	var remVO = function() {
		if ( focusedDijitItem !== undefined ) {
			var p=focusedDijitItem;
			if ( p.attr('edit_name') == "vo" ){
				var id = p.find(":input[type='hidden']:last").val();
				validateItemRemoval("vo",id,function(){p.next(".comboseperator").remove(),p.remove(),separateMultipleItems($("#vodiv"+dialogCount).find("span.app-vo"));});
			}
		}
	};

	/*var rebuildURLData = function() {
   		var ed = urlData;
        var h='';
        $("input[name^=combo_url]").each(function(e){
            var v1=$(this).val();
            var v2=$("input[name="+$(this).attr("name").substring(6)+"]").val();
            h=h+'<span class="editable app-url" edit_onchange="setURL" edit_combo_free="true" edit_type="combolink" edit_data="'+ed+'" edit_name="url" edit_group="true"><a href="'+v2+'">'+v1+'</a></span><br/> ';
        });
        $("#urldiv"+dialogCount).html(h);
		$("#urldiv"+dialogCount).show();
	};

	var addURL = function() {
		if(canAddListItem("combo_url",$("#urldiv"+dialogCount).find(".app-url")) === false) return;
		if(canAddListItem("url",$("#urldiv"+dialogCount).find(".app-url")) === false) return;
		
        rebuildURLData();
		var h=$("#urldiv"+dialogCount).html();
		var ed = urlData;
		h=h+'<span class="editable app-url" edit_onchange="setURL" edit_combo_free="true" edit_type="combolink" edit_data="'+ed+'" edit_name="url" edit_group="true"><a href=""></a></span><br/>';
		$("#urldiv"+dialogCount).html(h);
		var e=new editForm('editapp'+dialogCount);
		separateMultipleItems($("#urldiv"+dialogCount).find("span.app-url"));
	};
	
	var remURL = function() {
		if ( focusedDijitItem !== undefined ) {
			p=focusedDijitItem;
			if ( p.attr('edit_name') == "url" )  p.next(".comboseperator").remove(),p.remove(),separateMultipleItems($("#urldiv"+dialogCount).find("span.app-url"));
		}
	};*/

appdb.utils.DataWatcher.Registry.set("application",{items :[
 {selector : ".app-name > .dijitTextBox" ,type : "name", name : "Application Name"},
 {selector : ".app-desc > .dijitTextBox", type : "description", name:"Application Description"},
 {selector : ".app-domain > .dijitComboBox", type : "domain", name : "Discipline"},
 {selector : ".app-subdomain > .dijitComboBox", type : "subdomain", name : "Subdiscipline"},
 {selector : function(watcher){
   if(managedAppUrlsEditor !== null){
	return managedAppUrlsEditor.hasChanges();
   }
   return false;
 }, type : "url",  name : "Application Url"},
 {selector : "textarea[name='abstract'].dijitTextArea", type : "abstract", name : "Application Abstract"},
 {selector : ".app-country > .dijitComboBox", type:"country" , name : "Related Countries"},
 {selector : ".app-vo > .dijitComboBox",type : "vo", name : "Virtual Organization"},
 {selector : ".app-mw > .dijitComboBox",type : "mw", name: "Middleware"},
 {selector : ".app-status > .dijitComboBox", type : "status", name : "Status"},
 {selector : ".app-addedby > .dijitComboBox", type : "addedBy" , name :"Owner"},
 {selector : function(watcher){
   if(managedSciCons && managedSciCons!==null){
	 return managedSciCons.hasChanges();
   }
   return false;
 },type : "contacts" , name : "Contacts"},
 {selector : 
   function(watcher){
	var sd = serializeAppDocs();
	if($(":input[name='initialDocuments']:last").val() === sd || sd === "UNCHANGED"){
	 return false;
	}
	return true;
   
  }, "type" :"docs" , "name" : "Documents"}
 ],
 canCheckType : function(type){
  if($(":input[name='tool']").length==0){
   return true;
  }
  var chk = dijit.byNode($(":input[name='tool']").parent()[0]);
  if(typeof chk === "undefined"){
   return true;
  }
  chk = dijit.byNode($(":input[name='tool']").parent()[0]).attr("value");
  if(chk=="true"){
   if(type==="domain" || type=="subdomain"){
	return false;
   }
  }
  return true;
 }});

appdb.utils.DataWatcher.Registry.set("person",{items :[
 {selector : ":input[name='firstName']:last", type : "firstname", name : "First Name"},
 {selector : ":input[name='lastName']:last", type : "lastname", name : "Last Name"},
 {selector : ":input[name='gender']:last", type : "gender", name : "Gender"},
 {selector : ":input[name='positionTypeID']:last",  type : "positiontypeid" , name : "Role"},
 {selector : ":input[name='institution']:last",  type : "institution" , name : "Institute"},
 {selector : ":input[name='countryID']:last",  type : "countryID", name : "Country"},
 {selector : ":input[name^='contactType']",  type : "contactType", name : "Contact type"},
 {selector : ":input[name^='contact']",  type : "contact", name : "Contact value"}
]});
