//dojo.require("dijit.layout.TabContainer");
//dojo.require("dijit.layout.ContentPane");
//dojo.require("dojox.layout.ContentPane");
//dojo.require("dijit.form.Button");
//dojo.require("dijit.form.CheckBox");
//dojo.require("dijit.form.TextBox");
//dojo.require("dijit.form.FilteringSelect");
//dojo.require("dijit.Dialog");
//dojo.require("dojo.parser");
//dojo.require("dijit.TooltipDialog");
//dojo.require("dijit.form.DropDownButton");
//dojo.require("dojo._base.json");
//dojo.require("dojox.Dialog");
//dojo.require("dijit.layout.TabContainer");
//dojo.require("dojox.grid.Grid");
//dojo.require("dojox.grid.compat._data.model");
var exportDlg;
var appDlg2;
var pplDlg2;
var searchDlg;
var customFilter;
var exportForm;
var list = null;
var SyntacticHelpMsg='<div style="max-height:400px; overflow-y: scroll">'+
	'filter expressions are composed of one or more keywords, optionally prefixed by operators and/or specifiers. The syntax in <a href="http://en.wikipedia.org/wiki/Backus–Naur_Form" target="_blank">BNF</a> is:'+
	'<p>'+
	'<pre>'+
	'&lt;expression&gt; ::= &lt;keyword&gt;*'+
	'\n'+
	'&lt;keyword&gt; ::= [&lt;operator&gt;*][&lt;specifier&gt;:]some_string'+
	'\n'+
	'&lt;operator&gt; ::= = | ~ | <[=] | >[=] | +[=|~|<[=]|>[=]] | -[=|~|<[=]|>[=]]'+
	'\n'+
	'&lt;specifier&gt; ::= &lt;related_entity&gt;[.property_name] | property_name'+
	'\n'+
	'&lt;related_entity&gt; ::= application | person | vo | middleware | country | [sub]discipline | '+
	'</pre>'+
	'</p>'+
	'Rules are as follow:<br/>'+
	'<ul>'+
	'<li>Each keyword without an operator <b>may</b> <b>partially</b> match any property related to the filtered entity.</li>'+
	'<li>If a keyword is prefixed with the "=" operator, then the keyword <b>may exactly</b> match any related property.</li>'+
	'<li>If a keyword is prefixed with the "<" or ">" comparison operator, then the keyword <b>may</b> be <b>greater than</b> or <b>lesser than</b> any related property, respectively. '+
	'Optionally prefixing the "=" operator as well, will make the comparison operator non-strict.</li>'+
	'<li>If a keyword is prefixed with the "~" operator, then the keyword will be treated as a <b>regular expression</b> which <b>may</b> match any related property.</li>'+
	'<li>If a keyword is prefixed with the "+" operator, then the keyword <b>must</b> match any related property.</li>'+
	'<li>If a keyword is prefixed with the "-" operator, then the keyword <b>must not</b> match any related property.</li>'+
	'<li>If a specifier is present, then the keyword applies only to the specified property.</li>'+
	'<li>Specifiers refering to related entities may omit the property name, in which case their default property will be used.</li>'+
	'</ul>'+
	'Some examples:<br/>'+
	'<ul><li><pre>cms atlas</pre></li></ul>'+
	'will return an application named "CMSSW", another named "ATLAS", another belonging to the "atlas" VO, etc.<br/>'+
	'<ul><li><pre>cms atlas +greece</pre></li></ul>'+
	'will return only the subset of the previous example\'s results that actually mention Greece<br/>'+
	'<ul><li><pre>cms atlas +greece</pre></li></ul>'+
	'will return only the subset of the first example\'s results that do not mention Greece<br/>'+
	'<ul><li><pre>vo:atlas</pre></li></ul>'+
	'will return applications that belong to the VO\'s named or described as "atlas" as well as "atlas.ac.il"'+
	'<ul><li><pre>=vo.name:atlas</pre></li></ul>'+
	'will return applications that belong to the VO named "atlas" only'+
	'<ul><li><pre>&lt;dateadded:2011</pre></li></ul>'+
	'will return applications that have been registered before the year 2011'+
	'<ul><li><pre>&gt;=name:x</pre></li></ul>'+
	'will return applications whose names begin with "x","y", or "z"'+
'</div>';

function navpaneclicks2 (e) {
	$(e).find(".egimenuarrow").attr('src','/images/egiarrowdown.png');
	if (dijit.byId($(this).attr("id")) !== undefined) if ( ! dijit.byId($(e).attr("id")).open ) dijit.byId($(e).attr("id")).toggle();
	var s = $(e);
	$("#panediv").find("div.dijitTitlePane").each(function() {
		if ( $(this).attr("id") != s.attr("id") ) {
			if (dijit.byId($(this).attr("id")) !== undefined) if ((dijit.byId($(this).attr("id")).open) && ($(this).attr("id") != "newspane")) dijit.byId($(this).attr("id")).toggle();
			$(this).find(".egimenuarrow").attr('src','/images/egiarrowleft.png');
		};
	});
}
function navpaneclicks (e){
	var id  = ((typeof e == 'object')?$(e).attr("id"):e);
	var a = dijit.byId(id),n;
	if(a){
		if(a.open){
			dojo.forEach( dojo.query("div#panediv > .dijitTitlePane"),function(node){
				n=dijit.byNode(node);
				if(n && n.open){
					n.toggle();
				}
			});
		}else{return;}
		a.toggle();
	}
}
function appQuickLinkOld(e,t) {
	var i;
	switch(t) {
		case 1:
			i = '"middleware.name:'+e+'"';
			break;
		case 2:
			i = 'country.id:'+e+'';
			break;
		case 4:
		   	i = 'discipline.id:'+e+'';
			break;
		case 5:
		   	i = 'subdiscipline.id:'+e+'';
			break;
	}
	appdb.views.Main.showApplications({flt: i});
}

function appQuickLink(e,t,ext){
    var i, m = appdb.views.Main;
    ext = ext || {};
    ext.isBaseQuery = true;
    switch(t) {
            case 1: //middleware
                    i = '"=middleware.name:'+e+'"';
                    m.showApplicationMiddleware({flt: i},ext);
                    break;
            case 2: //country
                    i = '=country.id:'+e+'';
                    m.showApplicationCountry({flt: i},ext);
                    break;
            case 4: //discipline
                    i = '=discipline.id:'+e+'';
                    m.showDiscipline({flt: i},ext);
                    break;
            case 5: //subdiscipline
                    i = '=subdiscipline.id:'+e+'';
                    m.showSubdiscipline({flt: i},ext);
                    break;
    }
    //appdb.views.Main.showApplications({flt: i});
}

function closeDialog() {
	shortcut.remove("esc");
}

function showFlash() {
//	$('#flashcontent').show();
	if (detailsStyle == 1) if ($("#detailsdlg"+dialogCount)[0] !== undefined) dijit.byId("detailsdlg"+dialogCount).destroyRecursive();
	if (RelAppIntId) clearInterval(RelAppIntId);
}

function goDetailsBack() {
	if ($.trim(detailsListHtml) == '') {
			$("#details").empty();
			$("#details").hide();
			showHome();
			$("#main").fadeIn("fast");
    } else if (detailsListHtml !== null) {
			$("#details").empty();
			$("#details").hide();
	//		$("#main").html(detailsListHtml);
			$("#main").fadeIn("fast");
			animateList();
	}
    detailsListHtml = null;
}

function setDetailsDisplayStyle(style) {
    if (style !== null) {
		detailsStyleAuto = false;
        detailsStyle = style;
    } else {
		detailsStyleAuto = true;
		checkDetailsStyle();
	}
}

function showNGIDetails(url) {
	showDetails(url,'Resource Provider Details');
}

function showVODetails(url) {
	showDetails(url, 'VO Details');
}

function showAppDetails2(url) {
	detailsStyle = 0;
	var qs=url.split('?')[1];
	var parms=qs.split('&');
	var _id;
	for(i=0;i<parms.length;i++){
		if ( parms[i].split("=")[0] == 'id' ) {
			_id = parms[i].split("=")[1];
			break;
		}
	}
	appdb.views.Main.showApplication({id: _id});
}

function showAppDetails(url, edit) {
	detailsStyle = 0;
	showDetails(url,'Application/Tool Details');
	if (edit) {
		$("#infodiv"+dialogCount).ready(function(){
			appdb.utils.ExecuteOnLoad(function(){
				onAppEdit(null);
				$("#docdiv"+dialogCount).hide();
				onload_appdetails();
			},{
				id : "RegisterNewApplication",
				time:1000,
				checker:function(){return (typeof onload_appdetails !== "undefined")?true:false;}
			});
		});
	}
}

function showPplDetails(url, edit) {
	detailsStyle = 0;
	showDetails(url,'Person Profile');
	if (edit) {
		if(typeof onEdit == "function"){
			onEdit = undefined;
		}
		$("#infodiv"+dialogCount).ready( function(){
			var onEdit_loader = function(){
				if(typeof onEdit  == "function"){
					onEdit();
					$("#docdiv"+dialogCount).hide();
				}else{
					setTimeout(onEdit_loader,100);
				}
			};
			onEdit_loader();
		});
	}
}

function showNGIDetails2(url) {
	detailsStyle = 0;
	var qs=url.split('?')[1];
	var parms=qs.split('&');
	var _id;
	for(i=0;i<parms.length;i++){
		if ( parms[i].split("=")[0] == 'id' ) {
			_id = parms[i].split("=")[1];
			break;
		}
	}
	appdb.views.Main.showNgi({id: _id}, {mainTitle: ' '});
}

function showVODetails2(url) {
	detailsStyle = 0;
	var qs=url.split('?')[1];
	var parms=qs.split('&');
	var _id;
	for(i=0;i<parms.length;i++){
		if ( parms[i].split("=")[0] == 'id' ) {
			_id = parms[i].split("=")[1];
			break;
		}
	}
	appdb.views.Main.showVO(_id, {mainTitle: ' '});
}

function showPplDetails2(url) {
	detailsStyle = 0;
	var qs=url.split('?')[1];
	var parms=qs.split('&');
	var _id;
	for(i=0;i<parms.length;i++){
		if ( parms[i].split("=")[0] == 'id' ) {
			_id = parms[i].split("=")[1];
			break;
		}
	}
	appdb.views.Main.showPerson({id: _id}, {mainTitle: ' '});
}

function showDetails(url,title) {
	detailsStyle = 0;
	if (detailsStyle == 1) if ($("#detailsdlg"+dialogCount)[0] !== undefined) dijit.byId("detailsdlg"+dialogCount).onCancel();
	$('div [id^="dijit_TooltipDialog"]').each(function(x){
		try {
			dijit.popup.close(dijit.byId($(this).attr('id')));
		} catch(err) {
		}
	});
	dialogCount++;
	url+="&dc="+dialogCount;
	if ( detailsStyle == 1 ) {
		appDlg = new dojox.Dialog({
			title: "Application/Tool Details",
			style: "width: 80%",
			onCancel: showFlash,
			id: "detailsdlg"+dialogCount,
	        href: url
		});
		$('.dijitDialogPaneContent:last')[0].setAttribute("id","detailsdlgcontent"+dialogCount);
		appDlg.show();
	} else {
		detailsListHtml = $("#main").html();
     	$("#main").hide();
		$.get(
    	    appdb.config.endpoint.base+url, {}, function(data, textStatus) { 
				$('#details').html(displayStyleHtmlStart+'<div class="detailsdlg" style="height: 100%;"><div class="dijitDialogTitleBar"><span class="dijitDialogTitle"></span></div><div class="detailsdlgcontent" style="height:100%;">'+data+'</div></div>'+displayStyleHtmlEnd); 
				$("#details").fadeIn("slow");
			}, 'html'
		);
	}
}

function showLogo(id) {
    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;
    };
	appDlg2 = new dijit.Dialog({
		title: "Logo preview",
        style: "width: auto; position: absolute",
        onLoad: function(){
            setTimeout(function(){$(appDlg2.domNode).center();},250);
        }
	});
	appDlg2.setHref('apps/showlogo?id='+id);
    appDlg2.startup();
	appDlg2.show();
	$('div[id^="dijit_Dialog"]:last').css('z-index','1000');
}

function showImage(id) {
    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;
    };
	pplDlg2 = new dijit.Dialog({
		title: "Image preview",
        style: "max-width: 300 px; width: auto; position: absolute",
        onLoad: function(){
            setTimeout(function(){$(pplDlg2.domNode).center();},250);
        }
	});
	pplDlg2.setHref('people/showimage?id='+id);
    pplDlg2.startup();
	pplDlg2.show();
	$('div[id^="dijit_Dialog"]:last').css('z-index','1000');
}

function gotoPage(p) {
	$("#main").fadeOut(); 
	var len = Number($("#length")[0].value);
	var ofs=(p-1)*(len+1);
	var base = $("#viewtype")[0].value;
	var args = '';	
	if (base == "app") {
		base="apps";
		if ($("#subindex")[0].value != "") base=base+"/"+$("#subindex")[0].value;
	}
	if (base == "ppl") base="people";
	if (base == "vo") {
		if ( voCriteria.name != '' ) args = args + '&name='+voCriteria.name;
		if ( voCriteria.domainID != '' ) args = args + '&domain='+voCriteria.domainID;
	}
	ajaxLoad(base+'?gid=&ofs='+ofs+'&len='+len+args,"main");
}

function prevPage() {
	var currentPage = Number($("#currentPage")[0].value);
	gotoPage(currentPage);
}

function nextPage() {
	var currentPage = Number($("#currentPage")[0].value);
	gotoPage(currentPage+2);
}

function setView(mode) {
        var gv = document.getElementById("gridviewimg"), lv = document.getElementById("listviewimg"); //fixes ie8 bug
	if (mode == 2) {
		document.getElementById($("#viewtype")[0].value+"mainlist").setAttribute("class","mainlist2");
		document.getElementById($("#viewtype")[0].value+"mainlist").setAttribute("className","mainlist2");
                if(gv){
                    gv.setAttribute("src","images/gridview.png");
                }
		if(lv){
                    lv.setAttribute("src","images/listview_s.png");
                }
		$("#"+$("#viewtype")[0].value+"mainlist li:odd").css('background-color','#FFFFE8');
	} else {
		document.getElementById($("#viewtype")[0].value+"mainlist").setAttribute("class","mainlist");
		document.getElementById($("#viewtype")[0].value+"mainlist").setAttribute("className","mainlist");
                if(gv){
                    gv.setAttribute("src","images/gridview_s.png");
                }
		if(lv){
                    lv.setAttribute("src","images/listview.png");
                }
		$("#"+$("#viewtype")[0].value+"mainlist li:odd").css('background-color','white');
	}
	appViewMode = mode;
}

function animClose(id,selected) {
	if (selected) {
		document.getElementById(id).setAttribute("src","images/close_s.png");
	} else document.getElementById(id).setAttribute("src","images/close_s.png");
}

function animateList() {
	if ( $.browser.msie ) {
		if ($("#viewtype")[0] !== undefined) {
			if ($("#viewtype")[0].value == "app" ) list = dojo.query("#appmainlist li");
			if ($("#viewtype")[0].value == "ppl" ) list = dojo.query("#pplmainlist li");
			if ($("#viewtype")[0].value == "vo" ) list = dojo.query("#vomainlist li");
			if ($("#viewtype")[0].value == "ngi" ) list = dojo.query("#ngimainlist li");
		}
		if ( list != null ) {
			var props = {
				i: {width:96, height:96, top:-16, left:-102},
				o: {width:64, height:64, top:0, left:-80}
			};
			list.forEach(function(n){
				var img = dojo.query("img", n)[0], a;
				dojo.connect(n, "onmouseenter", function(e){
					a && a.stop();
					a = dojo.anim(img, props.i, 175)
				});
				dojo.connect(n, "onmouseleave", function(e){
					a && a.stop();
					a = dojo.anim(img, props.o, 175, null, null, 75)
				});
			});
		}
	}

}

function filterHelp(p) {
	setTimeout(function(){
		var dlg = new dijit.TooltipDialog({
			title: "Filter Help",
			height: '400px',
			onCancel: showFlash,
			content: SyntacticHelpMsg
		});
		dijit.popup.open({
			popup: dlg,
			parent: p,
			around: p,
			orient: {BL:'TL'}                    
		})
	},500);
}

function searchbox(sf) {
	if (sf.val() == "Search...") {
		sf.css("color","#CCCCCC");
	}
	dojo.connect(dijit.byId(sf.attr("id")), "onFocus", function(k) {
		if (sf.val() == "Search...") {
			sf.val('');
			sf.css("color","inherit");
		}
	});
	dojo.connect(dijit.byId(sf.attr("id")), "onBlur", function(k) {
		sf.val($.trim(sf.val()));
		if (sf.val() == '') {
			sf.val('Search...');
			sf.css("color","#CCCCCC");
		}
	});
}

function initItemView() {
	if ( $("#viewtype")[0] !== undefined ) {
		if ( $("#viewtype")[0].value == "app" ) exportForm = '<form id="exportapps" name="exportapps" method="GET" action="apps/export">';
		if ( $("#viewtype")[0].value == "ppl" ) exportForm = '<form id="exportppl" name="exportppl" method="GET" action="people/export">';
	}
	delete exportDlg;
	exportDlg = new dijit.TooltipDialog({
			title: 'Filter',
			content:  exportForm +
					'<input type="text" id="exportType" name="type" style="display:none"/>'+
					'<span style="white-space: nowrap"><a title="Machine oriented, full data export" href="#" onclick="exportApps(\'xml\');">Export to XML</a></span><br/>' +
					'<span style="white-space: nowrap"><a title="Human oriented, concise data export" href="#" onclick="exportApps(\'csv\');">Export to CSV</a></span>' +
					'</form>'
	});
	animateList();
	if ( $("#viewtype")[0] !== undefined ) {
		if ( ($("#viewtype")[0].value == "app" ) || ($("#viewtype")[0].value == "ppl" ) ) {
			var exportApps = function(type) {
				document.getElementById("exportType").value = type;
				var base = $("#viewtype")[0].value;
				if ( base == "app" ) document.getElementById("exportapps").submit();
				if ( base == "ppl" ) document.getElementById("exportppl").submit();
				exportDlg && dijit.popup.close(exportDlg); 
			};
				
			var exportButton = new dijit.form.DropDownButton({
					label: 'Export',
					dropDown: exportDlg
			});
		}
	}
	if ( list != null ) {
		if ( $("#viewtype")[0] !== undefined ) {
			if ( ($("#viewtype")[0].value == "app" ) || ($("#viewtype")[0].value == "ppl" ) ) {
				customFilter = function () {
					dojo.query("table",searchDlg.domNode)[0].innerHTML = customFilterContents();
					dojo.parser.parse(dojo.query("table",searchDlg.domNode)[0]);
				};
				searchDlg = new dijit.TooltipDialog({
					title: 'Filter',
					content: '<table>' +
					customFilterContents() +
					'</table>'
				});
				var searchButton = new dijit.form.DropDownButton({
					id: "searchButton"+ajaxCount,
					label: "Filter",
					dropDown: searchDlg
				});
				detailsHistory = new Array();
				if (document.getElementById('exportdiv') != undefined) {
					exportButton.domNode.style.width='15px';
					document.getElementById('exportdiv').appendChild(exportButton.domNode);
					exportButton.domNode.style.display='none';
					exportDlg.domNode.style.display='none';
				}
			}
			setView(appViewMode);
		}
		dojo.parser.parse(dojo.byId("main"));
	}
};

dojo.addOnLoad(function(){initItemView();});

