var logged_in = "";	
	
var login_link = '';
var redirect_href = '';

var query_url = "../cgi/queryms.cgi";
var editusr_url = "../cgi/editusr.cgi";

var approvedState = {};
var currentGridInView = '';
var refreshList = {};

var queryms_url = query_url;
 
var tmpURL = window.location.href;
tmpURL = tmpURL.replace(/\?.*/,'');
if ( /peptidome\/$/.test( tmpURL ) ) {  
	queryms_url = "cgi/queryms.cgi";
	editusr_url  = "cgi/editusr.cgi"; 
}	

var token_from_param = get_url_parameter( 'token' )
var token = token_from_param ? token_from_param : '';
var tokenAppendURL = '';	
if(token){ tokenAppendURL = '&token='+token;}

	
var ftp_url = "ftp://ftp.ncbi.nih.gov/pub/peptidome/";
var returnObj = [];

var layout_height = 700;
var offset = 266; // originally 205
var numberPerPage = 10;	

if( window.innerHeight ){
	layout_height = window.innerHeight - offset;
}
else if( document.documentElement && document.documentElement.clientHeight ){
	layout_height = document.documentElement.clientHeight - offset;
}
else if( document.body.clientHeight ){
	layout_height = document.body.clientHeight - offset;
}
    
// calculate the number of rows based on the window size
if(layout_height <  300){
	layout_height = 300;
	numberPerPage = 10 ;
}
else {
	numberPerPage = Math.round((layout_height - 2 - 55 - 33)/20) - 0;
}

function processApproveDisapprove(el,type,acc){
	var actionType = 'approve';
	if(approvedState[acc]){ actionType = 'disapprove';}
	var msg = "Do you want to <b>"+actionType+"</b> all samples for this this study?";
	if(type == 'sample'){msg = "Do you want to <b>"+actionType+"</b> this sample ("+acc+")?"}
	// Prompt user:
	Ext.Msg.show({
		title: 'Alert',
		msg: msg,
		width: 350,
		buttons: {yes:'Yes', no :'No' },
			fn: function(btn, text) { 
				userResponse = btn ;
				if(userResponse && userResponse === 'yes'){  // yes to all								
					approveDisapproveStudy(el,true,acc);		
				}else{
					approveDisapproveStudy(el,false,acc);
				}
			},   							 
			icon: Ext.MessageBox.WARNING
	});	

	//approveDisapproveStudy(this);	
}

var public_private_renderer = function( value, metaData, record, rowIndex ) {	
	 
	//var checkedImg = '/core/extjs/ext-2.1/resources/images/default/menu/checked.gif';
	var checkedImg = '../img/lock.png';
	var uncheckedImg = '/core/extjs/ext-2.1//resources/images/default/menu/unchecked.gif';
	var cb = ''
		+ '<div style="text-align:center;height:16px;overflow:visible">'
		+ '<img style="vertical-align:-3px" src="'
		+ checkedImg
		//+ (value ? checkedImg : uncheckedImg)
		+ '"'
		+ ' />'
		+ '</div>'
	;
	
	var html = (value) ? '' : cb;
	return html;
	//return "<input type='checkbox'" + (value ? "checked='checked'" : "") + "disabled>";
	/*var html = '';
	if(value){html = 'Yes';}
	else{html = 'No';}		
	return html;*/
}

function toggleApproveLink(el,ar){
	if(ar){
		// display disapprove	
		el.removeClass('approve');
		el.addClass('disapprove');
		el.update('Disapprove');
	}
	else{
		el.removeClass('disapprove');
		el.addClass('approve');
		el.update('Approve');
	}
}
var approveDisapproveStudy = function(el,allSamples,acc){
	var paramsObj = {cmd : 'togglehold', acc : acc };
	if(allSamples){
		paramsObj.allSamples='';
	}
	Ext.Ajax.request(
	{
		url: query_url,
		params: paramsObj,

		success: function ( result, request ) 
		{
			var obj = '';
			obj = Ext.decode( result.responseText );
			if(obj instanceof Object && obj.MS_QueryResponse){					
				if ( obj.MS_QueryResponse) {
					approvedState[acc] = !approvedState[acc];
					toggleApproveLink(el,approvedState[acc]);
					
					//location.reload(true); 
					/*if(el){
						el.un('click', function(){});						 
						el.removeClass('approve');
						el.update('Approved');
						el.addClass('approvedDeactivated');
					}*/
				}						
			}
			else{	                    
			}						 				
		},
		failure: function (){ 				
		}
	})
	
}


var renderSingleDownloadURL = function(id,type){
	var html = '';

	var tmp = id+'';
	if(!tmp.match(/(PSE|PSM)/)){
		if(type == 'study'){ id = 'PSE'+id;}
		else {id = 'PSM'+id;	}	
	}
		
	var folder = folderPath(id);
	
	if(type == 'study'){ folder = 'studies/PSE'+folder+'/'+id+'/';}
	else{folder = 'samples/PSM'+folder+'/'+id+'/';}
	html = '<div id="ftpDownload"><a href="'+ftp_url+folder+'" target="_new">Download</a></div>';
	
	return html;
} 

var folderPath = function(id){
	var dir = '';
	if(!checkNumeric(id)){
		id = id.replace(/(PSE|PSM)/,'');
	}
	
	var i = Math.floor(id / 1000);

	if(i > 0){
		dir = i+'nnn';			
	}else{ dir = 'nnn';}
		
	return dir	
}


var contact_renderer = function( obj ){
	var html = "<table cellpadding='0' cellspacing='0' border='0' class='contactinfo'>";
	
	if (checkIfExists(obj.name)){ html += '<tr><td valign="top" id="specWidth"><b>Name:</b></td><td valign="top">'+obj.name+'</td></tr>';}
	if (checkIfExists(obj.org)){ html += '<tr><td valign="top" id="specWidth"><b>Organization:</b></td><td valign="top">'+obj.org+'</td></tr>';}
	if (checkIfExists(obj.email)){ html += '<tr><td valign="top" id="specWidth"><b>Email:</b></td><td valign="top">'+obj.email+'</td></tr>';}
	if (checkIfExists(obj.address)){ 
		html += '<tr><td valign="top" id="specWidth"><b>Address:</b></td><td valign="top">'+obj.address;
		if (checkIfExists(obj.city)){ html += '<br>'+obj.city;}
		if (checkIfExists(obj.state)){ html += ', '+obj.state;}
		if (checkIfExists(obj.zip)){ html += ' '+obj.zip;}
		
		html += '</td></tr>';
	}
	
	html += "</table>";
	return html;
};

var characteristics_renderer = function ( obj ){
	var html = "";
	
	if(obj instanceof Object) {
		var html = "<table cellpadding='0' cellspacing='0' border='0'>";
		
		for (var i in obj){
			if(obj[i] && typeof(obj[i]) != 'function'){
				if (checkIfExists(obj[i].tag) && checkIfExists(obj[i].value)){ 
					var tag = initialCap(obj[i].tag.replace("_",' '));
					tag = tag.replace("_", ' ');
					html +='<tr><td valign="top" id="specWidth"><b>'+tag+':</b></td><td id="bottomAlign">'+obj[i].value+'</td></tr>';
				}
			}
		}	
		html += "</table>";
	}			
	return html;	
};

function date_renderer( value, metaData, record, rowIndex ){
	var html = value;

	if(typeof value == 'object'){
		var month_names = new Array ( );
		month_names[0] = '';
		month_names[month_names.length] = "January";
		month_names[month_names.length] = "February";
		month_names[month_names.length] = "March";
		month_names[month_names.length] = "April";
		month_names[month_names.length] = "May";
		month_names[month_names.length] = "June";
		month_names[month_names.length] = "July";
		month_names[month_names.length] = "August";
		month_names[month_names.length] = "September";
		month_names[month_names.length] = "October";
		month_names[month_names.length] = "November";
		month_names[month_names.length] = "December"
		
		html = month_names[value.month] + ' '+value.day +', '+value.year;
		
	}
	
	return html;
}

function get_url_parameter( name )
{
	name = name.replace( /[\[]/, "\\\[" ).replace( /[\]]/, "\\\]" );

	var regexS = "[\\?&]" + name + "=([^&#]*)";
	var regex = new RegExp( regexS,'i' );
	var results = regex.exec( window.location.href );

	if( results == null )
	return "";
	else
	return results[ 1 ];
}

function errorMSG(id,msg){	
	if(!id){id ='err';}
	if(msg === undefined){msg ='Your request could not be completed at this time. Please try again later';}	 
	return "<div id='expandedContent'><div id='"+id+"'><p id='errorMSG'>"+msg+"</p></div></div>";		
}
		
function checkIfExists(v){
	if( v !== null && v !== undefined && v != '') { return true;}
	return false;
}
	
function checkNumeric( value ){
	var anum=/(^\d+$)|(^\d+\.\d+$)/;
    if (anum.test(value)){ return true;}
    return false;
}		
	
function initialCap(str) {
	return str = str.substr(0, 1).toUpperCase() + str.substr(1);	
}		

function print_array (arr){
	var html = '';
	if (arr instanceof Array) {
		for (var key in arr) {	
			if(typeof arr[key] == 'function'){continue;}
			html += "<p>"+arr[key]+'</p>';		
		}
	}
	else if (arr instanceof Object) {
		html = print_r( arr, {} );
	}
	return html;	
}

function print_r( array, skipped ) {
 	var output = "", pad_char = " ", pad_val = 4; 	

	var formatArray = function (obj, cur_depth, pad_val, pad_char, skip) {
		 
    	if (cur_depth > 0) {
        	cur_depth++;
        }
 
	    /*var base_pad = repeat_char(pad_val*cur_depth, pad_char);
    	var thick_pad = repeat_char(pad_val*(cur_depth+1), pad_char);*/
        var str = "";
 
	     if (obj instanceof Array || obj instanceof Object) {
        	 for (var key in obj) {					
            	 if (obj[key] instanceof Array || obj[key] instanceof Object) {
					
				 	if(key != 'std'){
						var keyName = key;
						 
						if(!checkNumeric(key)){keyName = initialCap(key);}
						keyName = keyName.replace(/\_/,' ');
						if(key == 'metadata'){
							keyName = 'Meta data update';
						}
						if (obj[key] instanceof Array ){
							str += '<table cellspacing="0" cellpadding="0" border="0"><tr><td valign="top" id="specWidth"><b>'+keyName+':</b></td><td id="bottomAlign">';
							for( var i in obj[key]){
								if(typeof obj[key][i] == 'function'){continue;}
								str += '<p>'+obj[key][i]+'</p>';	
							}
							str += '</td></tr></table>';
						}else{
							str += "<b>"+keyName+":</b> "+formatArray(obj[key], cur_depth+1, pad_val, pad_char, skip);
						}
						
					}else{
						str += formatArray(obj[key], cur_depth+1, pad_val, pad_char, skip);
					}
	             } else {
    	         	if(obj[key]) {
						var openTable ='<table cellspacing="0" cellpadding="0" border="0"><tr><td valign="top" id="specWidth"><b>';
						var closeTable = '</td></tr></table>';
						var inbetweenTD = '</b></td><td id="bottomAlign">';
						if(key == 'year' || key =='month'){
							if(key == 'year') {str += '<span>';}
							str +=  obj[key] + "/";
						}
						else if(key == 'day' && !skip[key]){
							str +=  obj[key] + "</span><br>";
						}
						
						else if(key == 'samples' && !skip[key] ){								
							str += "<b>"+initialCap(key)+':</b>  <a class="clickable" id="viewSamplesTextLink">View samples ('+obj[key]+')</a> &nbsp;&nbsp;<br>';
						}
						else if(key == 'spectra' && !skip[key] ){								
							str += "<b>"+initialCap(key)+':</b>  '+obj[key]+' &nbsp;&nbsp;';
						}
						else if(key == 'proteins' && !skip[key]){								
							str += "<b>"+initialCap(key)+":</b>  <a class='clickable' id='switchpr'>" + obj[key] + "</a> &nbsp;&nbsp;";
						}
						else if(key == 'peptides' && !skip[key]){							 
							str += "<b>"+initialCap(key)+":</b>  <a class='clickable' id='switchpe'>" + obj[key] + "</a> &nbsp;&nbsp;";
						}
						else if(key == 'org' && !skip[key]){								
							str += "<p><b>Organization:</b> " + obj[key] + "</p>";
						}	
						else if(key == 'spectra' || key == 'samples' || key == 'proteins'  || key == 'peptides' ){								
							str += "<b>"+initialCap(key)+':</b>  '+obj[key]+' &nbsp;&nbsp;';
						}
						else{
							str += openTable+"<p><b>"+initialCap(key)+":</b>  "+inbetweenTD + obj[key] + "</p>"+closeTable;
						}
					}
        	    }
            }
		} else if(obj == null || obj == undefined) {
        	str = '';
	    } else {
    	    str = "<p>"+obj.toString()+"</p>";
		}
 
	    return str;
    };
 
	var repeat_char = function (len, pad_char) {
    	var str = "";
	    for(var i=0; i < len; i++) { 
    		str += pad_char; 
        }
	    return str;
    };
	output = formatArray(array, 0, pad_val, pad_char, skipped);
	
	return output;    	
}	

var dateHTMLRenderer = function ( rD,dD,mUD,daD ){
	var html = '';
	var openTable ='<table cellspacing="0" cellpadding="0" border="0"><tr><td valign="top" id="specWidth"><p><b>';
	var openTable2 ='<table cellspacing="0" cellpadding="0" border="0"><tr><td valign="top" width="70"><p><b>';
	var closeTable = '</p></td></tr></table>';
	var inbetweenTD = '</p></b></td><td id="bottomAlign"><p>';
			
	var top = "<h3>Dates</h3><div id='box' style='width:500px;'><table class='datatable' width='auto' border='0'><tr>";
	var details = '';

	var c = 0;								
	var classStr = openTable;
	if(checkIfExists(rD)){ c++;}
	details += checkIfExists(rD)? "<td>"+classStr+"<b>Release:</b> "+inbetweenTD +rD+ ""+closeTable+"</td>":'';
	if(checkIfExists(dD)){  c++; if (c >1){ classStr = openTable2;}else{classStr = openTable;}}
	details += checkIfExists(dD)? "<td>"+classStr+"<b>Deposit:</b> "+inbetweenTD +dD+ ""+closeTable+"</td>":'';
	if(checkIfExists(mUD)){ c++; if(c > 2){c = 1; details += '</tr><tr>';}if (c >1){ classStr = openTable2;}else{classStr = openTable;}}
	details += checkIfExists(mUD)? "<td>"+classStr+"<b>Metadata update:</b> "+inbetweenTD +mUD+ ""+closeTable+"</td>":'';
			
	if(checkIfExists(daD)){ c++; if(c > 2){c = 1; details += '</tr><tr>';}if (c >1){ classStr = openTable2;}else{classStr = openTable;}} 
	details += checkIfExists(daD)? "<td>"+classStr+"<b>Data update:</b> "+inbetweenTD +daD+ ""+closeTable+"</td>":'';
    		
	var end = "</tr></table></div>";
	if(details){html = top+''+details+''+end;}
	
	return html;
}

var addNode = function ( hash, key, cnts, val ) {
   	if ( this.usearray == true ) {              // into array
       	if ( cnts == 1 ) hash[key] = [];
        hash[key][hash[key].length] = val;      // push
   	} else if ( this.usearray == false ) {      // into scalar
       	if ( cnts == 1 ) hash[key] = val;       // only 1st sibling
    } else if ( this.usearray == null ) {
   	    if ( cnts == 1 ) {                      // 1st sibling
       	    hash[key] = val;
        } else if ( cnts == 2 ) {               // 2nd sibling
   	        hash[key] = [ hash[key], val ];
       	} else {                                // 3rd sibling and more
            hash[key][hash[key].length] = val;
   	    }
    } else if ( this.usearray[key] ) {
   	    if ( cnts == 1 ) hash[key] = [];
       	hash[key][hash[key].length] = val;      // push
    } else {
   	    if ( cnts == 1 ) hash[key] = val;       // only 1st sibling
    }
};

var xml2Json = function ( elem ) {
   	//  COMMENT_NODE
    if ( elem.nodeType == 7 ) {
   	    return;
    }

   	//  TEXT_NODE CDATA_SECTION_NODE
    if ( elem.nodeType == 3 || elem.nodeType == 4 ) {
        var bool = elem.nodeValue.match( /[^\x00-\x20]/ ); // for Safari
   	    if ( bool == null ) return;     // ignore white spaces
       	return elem.nodeValue;
    }

    var retval;
   	var cnt = {};

    //  parse attributes
   	if ( elem.attributes && elem.attributes.length ) {
       	retval = {};
        for ( var i=0; i<elem.attributes.length; i++ ) {
   	        var key = elem.attributes[i].nodeName;
       	    if ( typeof(key) != "string" ) continue;
           	var val = elem.attributes[i].nodeValue;
            if ( ! val ) continue;
   	        if ( typeof(cnt[key]) == "undefined" ) cnt[key] = 0;
       	    cnt[key] ++;
           	addNode( retval, key, cnt[key], val );
        }
   	}

	    //  parse child nodes (recursive)
    if ( elem.childNodes && elem.childNodes.length ) {
   	    var textonly = true;
       	if ( retval ) textonly = false;        // some attributes exists
        for ( var i=0; i<elem.childNodes.length && textonly; i++ ) {
   	        var ntype = elem.childNodes[i].nodeType;
       	    if ( ntype == 3 || ntype == 4 ) continue;
            textonly = false;
   	    }
       	if ( textonly ) {
           	if ( ! retval ) retval = "";
            for ( var i=0; i<elem.childNodes.length; i++ ) {
   	            retval += elem.childNodes[i].nodeValue;
       	    }
        } else {
   	        if ( ! retval ) retval = {};
       	    for ( var i=0; i<elem.childNodes.length; i++ ) {
           	    var key = elem.childNodes[i].nodeName;
               	if ( typeof(key) != "string" ) continue;
                var val = xml2Json( elem.childNodes[i] );
   	            if ( ! val ) continue;
       	        if ( typeof(cnt[key]) == "undefined" ) cnt[key] = 0;
           	    cnt[key] ++;
               	addNode( retval, key, cnt[key], val );
            }
   	    }
    }
   	return retval;
};

var isAdmin = function ( role ){if (role == 'admin'){return true;}else{ return false;}}
var isAnonymous = function ( role ){if (role == 'anonymous'){return true;}else{ return false;}}

var handleUserStatus = function (obj){
	if(obj instanceof Object && obj.MS_QueryResponse){
		if(obj.MS_QueryResponse.userinfo){
			returnObj = obj.MS_QueryResponse.userinfo;
		}
		if ( returnObj.role !== 'undefined' ){
			if(isAnonymous(returnObj.role) && returnObj.name === undefined){
				logged_in = "";
				show_login_status( "Anonymous" );
			}
			else{
				show_login_status( returnObj.name );
			}
		}
		/*else if ( returnObj.userid ){
			show_login_status( returnObj.userid );
		}
		else{ 
			logged_in = "";
			show_login_status( "Anonymous" );
		}*/
	}
	else{ 
		logged_in = "";
		show_login_status( "Anonymous" );
	}
}

var show_login_status = function( username ) 
{		
	var login_href = "https://pdalogin.ncbi.nlm.nih.gov/uls.cgi?url=";
	redirect_href = window.location.href;
	if ( /editusr.cgi/.test( redirect_href ) ){					
		redirect_href = window.location.protocol+'//'+window.location.host + ''+window.location.pathname;
		if( /nih.gov.*peptidome.*/.test( document.referrer ) ){		
			redirect_href = document.referrer ;			
		}
		redirect_href = redirect_href.replace(/editusr.cgi.*/,'');
		redirect_href = redirect_href.replace(/cgi\/$/,'');			
		//redirect_href = "http://www.ncbi.nlm.nih.gov/peptidome";			
	}
	var logout_href = "https://pdalogin.ncbi.nlm.nih.gov/uls.cgi?rss=&logoutBtn=1&urlParams=&urlLogout=" + redirect_href;
	login_link = '<a href="' + login_href + redirect_href + '">login</a>';

	var logout_link = '<a href="' + logout_href + '">logout</a>';
	var login_status = login_link;		
	
	//------------------------------------
	// Get login status from cookies
	//------------------------------------
	var pdalogin_id = get_userid_from_cookie();

	if ( username == "Anonymous" )
	{			 
		login_status = "Not logged in | " + login_link;
	}
	else if ( pdalogin_id && username )
	{
		login_status = 'User: <a href="'+editusr_url+'?mode=pedit&url='+redirect_href+'">' + username + '</a> | ' + logout_link ;

		logged_in = "true";
	}
	
	var submissions_div = Ext.get('submission-page');
	 
	// If user is logged in but has not completeded user info, 
	// redirect to user edit page		 
	if ( username != "Anonymous" && !returnObj.haveinfo ){
		 
		//if (!/editusr/.test( window.location.href ) && /submit\/guidelines/.test( window.location.href ) ) {location.href = editusr_url+'?mode=pedit&url='+redirect_href;}
		//if (!submissions_div) {
		if (!/editusr/.test( window.location.href ) ) {
				location.href = editusr_url+'?mode=pedit&url='+redirect_href;
		}
		//}
		else if(/submit\/$/.test( redirect_href ) && !/submit\/guidelines/.test( redirect_href )) {
			var t = Ext.get('editusrMsg');
			if (t){
				t.update('<p>You are successfully logged into NCBI, however Peptidome requires additional information before you may use our resource.  Please fill out the following form as completely as possible. Required fields are marked with an asterisk (<span class="required">*</span>).</p>');	
			}
			var nav_btn = Ext.get( 'navcontent' );
			if(nav_btn){
				Ext.get('navcontent').on('click',  Ext.emptyFn, null, {delegate: 'a',stopEvent: true});
				Ext.get('header').on('click',  Ext.emptyFn, null, {delegate: 'a',stopEvent: true});
				Ext.get('breadcrumbs').on('click',  Ext.emptyFn, null, {delegate: 'a',stopEvent: true});                
			}
			
			var cancel_btn = Ext.get('cancel-contact-subm');
			if(cancel_btn){						
				cancel_btn.on('click',function(){
					var explanation = "To use Peptidome, you must enter this information. If you choose not to do so, you may elect to log out.";
					// Prompt user:
					Ext.Msg.show({
						title: 'Alert',
						msg: explanation,
						width: 300,
						buttons: {ok:'Logout', cancel:'Cancel'},
						fn: function(btn, text) { if (btn == 'ok'){location.href = logout_href;}},   							 
						icon: Ext.MessageBox.WARNING
					});													
				},null, {stopEvent: true});
			}
		}
	}else {
		if (/editusr/.test( window.location.href ) ) {
			var cancel_btn = Ext.get('cancel-contact-subm');
			if(cancel_btn){					 
				cancel_btn.on('click',function(){
					location.href = redirect_href;							
				},null, {stopEvent: true});
			}
		}
	}		
	
	Ext.get( "login-status" ).update( login_status );
	if (submissions_div) {getFtpInfo();}
	/*
	var upload_div = Ext.get( "upload-form" ); 

	var login_msg = '<p id="subm_info">Zip or tar all the files described above into a single archive, and FTP the data to us.</p>' + 
						'<div class="border">Please ' + login_link + ' for FTP submission instructions.</div>';
	
	
	if( upload_div && (!logged_in || returnObj.haveinfo  != true) )
	{			
		
		
		//upload_div.update( login_msg );
	}
	else if( upload_div && logged_in && returnObj.haveinfo  == true )		
	{
		//getFtpInfo();
	}*/

};

var hideSubmissionForm = function(){
	var websubmission_div = Ext.get( "webSubmissionsForm" ); 
	msg = '<b>Please ' + login_link + ' to use web submissions.</b>';
	msg = "";
	var websubmission = Ext.get( "websubmissionWrapper" ); 
	if(websubmission){websubmission.update('');}
	return;
	
	
	if(websubmission_div){		
		var websubmissionP = Ext.get( "submissionP" );		
		if(websubmissionP){websubmissionP.update('');}
		websubmission_div.update(msg);
	}
}
var ftpInfoNotShown = function(obj){
	var ftptable_div = Ext.get( "ftptable" ); 
	var ftpurl_div = Ext.get( "ftpurl" );
	var verbage = '<b>Please ' + login_link + ' to view FTP credentials.</b>';
		
	if(logged_in && returnObj.haveinfo  != true){
		verbage = '<b>Please fill out <a href="'+editusr_url+'?mode=pedit&url='+redirect_href+'">your information</a> to view the FTP credentials.</b>';
	}
			
	if (ftpurl_div){ ftpurl_div.update(verbage);}			
	if (ftptable_div){ ftptable_div.update('<br><center>'+verbage+'</center><br>');}
	
};

var createFTPlink = function(obj){
	var ftpurl_div = Ext.get( "ftpurl" );
	if(ftpurl_div){			
		ftpurl_div.update('ftp://'+obj.username+':'+obj.password+'@'+obj.host);			
	}		
};

var createFTPtable = function(obj){
	var ftptable_div = Ext.get( "ftptable" ); 
	if(ftptable_div){
		var table = '<table summary="Peptidome FTP Instructions">'+
					'<tr><th scope="row">Host</th><td>'+obj.host+'</td></tr>'+
					'<tr><th scope="row">username</th><td>'+obj.username+'</td></tr>'+
					'<tr><th scope="row">password</th><td>'+obj.password+'</td>'+
					'</tr></table>';
		ftptable_div.update(table);			
	}		
};

var getFtpInfo = function(){
	Ext.Ajax.request (
	{
		url: queryms_url,			
		params: { cmd: "ftpinfo" },

		success: function ( result, request ) 
		{
			var obj = Ext.decode( result.responseText );
							
			var rObj = obj;
			if(obj.MS_QueryResponse.ftpinfo){
				rObj = obj.MS_QueryResponse.ftpinfo;
			}
				
			if ( rObj.username && rObj.username != 'unavailable' && obj.MS_QueryResponse.userinfo.role !== 'anonymous' )
			{					
				createFTPlink( rObj );
				createFTPtable( rObj );
				
				if(!isAdmin(obj.MS_QueryResponse.userinfo.role)){					 					 
					hideSubmissionForm();
				}										 		 
			}else {
				ftpInfoNotShown(rObj);
				hideSubmissionForm();
			}
		},
		failure: function() 
		{ 
			//show_login_status( "Anonymous" );
		}
	});
};

function readCookie( name ) 
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');

	for( var i = 0; i < ca.length; i++ ) 
	{
		var c = ca[ i ];

		while ( c.charAt( 0 ) == ' ' ) c = c.substring( 1, c.length );
		if ( c.indexOf( nameEQ ) == 0 ) return c.substring( nameEQ.length, c.length );
	}
	return null;
}

var get_userid_from_cookie = function ()    // Read cookie that NCBI PDA login sets
{
	return readCookie( "NcbiLsSessionPDA" );
};

Ext.grid.CheckColumn = function(config){
	Ext.apply(this, config);
	if(!this.id){
		this.id = Ext.id();
	}
	this.renderer = this.renderer.createDelegate(this);
};

var checkBoxSelectedItems = {};

Ext.grid.CheckColumn.prototype ={
	init : function(grid){
		this.grid = grid;

		this.selected = {}; // hash mapping record id to selected state
		this.grid.on('render', function(){
			var view = this.grid.getView();
			view.mainBody.on('mousedown', this.onMouseDown, this);
								
		}, this);
	},	
	onMouseDown : function(e, t){

		if(t.className && t.className.indexOf('x-grid3-cc-'+this.id) != -1){
			e.stopEvent();
			
			var index = this.grid.getView().findRowIndex(t);
			var record = this.grid.store.getAt(index);
			
			submitApprovals(record,this.dataIndex);
		}				
	},

	renderer : function(v, p, record,t){
		p.css += ' x-grid3-check-col-td'; 				 
		 
		if(record.get('acc') in checkBoxSelectedItems){ v = checkBoxSelectedItems[record.get('acc')]; record.data[this.dataIndex] = v; }
		else{ checkBoxSelectedItems[record.get('acc')] = record.data[this.dataIndex]; }	

		return '<div class="x-grid3-check-col'+(v?'-on':'')+' x-grid3-cc-'+this.id+'">&#160;</div>';
	}
};

var submitApprovals = function(record,dataIndex){
	var ids = [];
	var approveAllSub = false;
	var disapproveAllSub = false;
	
	var userResponse = '';
	var grid = '';//grid;
	 
	if(currentGridInView){
		grid = Ext.getCmp(currentGridInView);					
	}
	
	var acc = record.get('acc');
	if(!acc && record.json){ acc = record.json.acc }
	if(!acc){ acc = record.get('acc'); }
		
	var actionType = 'approve';
	if(record.get('approved')){actionType = 'disapprove';}
	
	var selections = '';//grid.getSelections();
	if(acc){selections = [acc];}
	 
	 
	var addSelectionToList = function(id,s){
		if(id){ ids.push({acc:id,approveAll:s});}	
	}
	
	var submitSelections = function() {				 
		
		if(ids[0]){
			var layout =  Ext.get( 'layout' );
			if(!layout) {layout = Ext.get('browse');}
			
			var mask = new Ext.LoadMask( layout );
			var params = {cmd: 'togglehold',acc:ids[0].acc};
			if(ids[0].approveAll){
				params.allSamples = '';
			}
			
			if(layout){mask.show();	}

			//----------------------------------------------
			// Approve/disapprove a Study/sample
			//----------------------------------------------
			Ext.Ajax.request(
			{
				url: query_url,
				params: params,
	
				success: function ( result, options ) 
				{
					var obj = Ext.decode( result.responseText );
					if(layout) {mask.hide();}
								
					if ( obj.MS_QueryResponse /*&& obj.MS_QueryResponse.length > 0*/ ) 
					{					
						checkBoxSelectedItems[record.get('acc')] = !record.data[dataIndex];
			
						record.set(dataIndex,  !record.data[dataIndex]);
						record.commit(); 
					 
						clearGrids('',record.get('acc'));
					}							
				},
				failure: function () 
				{ 
					if(layout) {mask.hide();}							
				}
			});
		}
	}
	
	function processSelection(arr,approveAllSubThis){
		if(!arr[0]){ submitSelections(); return;}

		var acc = arr.shift();
		 
		if(acc){					 
			
			if(/tab_admin_studies.*/.test(currentGridInView)){
				var msg = "Do you want to  <b>"+actionType+"</b> all samples for this study ("+acc+")?";
				// Prompt user:
				Ext.Msg.show({
					title: 'Alert',
					msg: msg,
					width: 350,
					buttons: {yes:'Yes'/*,ok:'Yes to all'*/, no :'No' /*,cancel: 'No to all'*/},
					fn: function(btn, text) { 
					
						userResponse = btn ;
						
						if(userResponse && userResponse === 'yes'){  // yes
							approveAllSubThis = true;
						}
						if(userResponse && userResponse === 'no'){						
							approveAllSubThis = false;
						}

						addSelectionToList(acc,approveAllSubThis);
						processSelection(arr,false);
					},   							 
					icon: Ext.MessageBox.WARNING
				});	
			}else{
				//addSelectionToList(acc,(approveAllSub)?true:false);
				addSelectionToList(acc,false);
				processSelection(arr,false);					
			}
		}	
	}
	
	if(selections[0]){
		var type = 'sample';
		
		if(/tab_admin_studies.*/.test(currentGridInView)){
			type = 'study';
		}
		
		if(type != 'study'){
			var msg = "Do you want to <b>"+actionType+"</b> this "+type+" ("+acc+")?";
			// Prompt user:
			Ext.Msg.show({
				title: 'Alert',
				msg: msg,
				width: 350,
				buttons: {yes:'Yes', no :'No' },
					fn: function(btn, text) { 
						userResponse = btn ;
						if(userResponse && userResponse === 'yes'){  // yes to all								
							processSelection(selections,false);
						}								
					},   							 
					icon: Ext.MessageBox.WARNING
			});	
		}else{
			processSelection(selections,false);
		}
	}						
}
function clearGrids (type,id){

	var grids = [
			 'tab_admin_samples_all_grid',
			 'tab_admin_studies_all_grid',
			 'tab_admin_samples_private_grid',
			 'tab_admin_studies_private_grid',
			 'tab_my_samples_all_grid',
			 'tab_my_studies_all_grid',
			 'tab_my_samples_private_grid',
			 'tab_my_studies_private_grid',
			 'tab_my_samples_public_grid',
			 'tab_my_studies_public_grid'/*,
			 'grid_studies',
			 'grid_samples'*/
			];
	if(id){grids.push('tab_'+id+'_grid');}
	for(i in grids){
		var gridAddr = grids[i];
	
		if(gridAddr && typeof(gridAddr) == 'function'){ continue;}	
		if(type && !gridAddr.match(type) ){continue;}
	
		if(currentGridInView != gridAddr){					
			var grid = Ext.getCmp(gridAddr);
			if(grid){
			grid.destroy();
				refreshList[gridAddr] = 'a';
			}
		}
	}
}

function includeJS(scriptFile) {
 	var headTag = document.getElementsByTagName('head').item(0);
 	var js = document.createElement('script');
 	js.setAttribute('language', 'javascript');
 	js.setAttribute('type', 'text/javascript');
 	js.setAttribute('src', scriptFile);
 	headTag.appendChild(js);
}

var xrefs_renderer = function( v, rec ){ 
	var html_str = []; 
	if(v){			
		for( key in v )
		{				
			if( key == 'remove' ){ continue; }
			var t = '';
			html_str[ key ] = "<table cellpadding='0' cellspacing='0' border='0'><tr>";
			if( typeof v[ key ].type !== undefined ){ t += '<b>'+v[ key ].type+'</b>';} 
			if( v[ key ].subtype && v[ key ].subtype != 'not defined' ){ t += ' ('+v[ key ].subtype+')';} 
			
			if( t ){ html_str[ key ] += "<td valign='top' id='specWidth'>" + t +': </td><td id="bottomAlign">';}
			else{  html_str[ key ] += "<td valign='top'>" ;}
			
			if( typeof v[ key ].target !== undefined){
				if( typeof v[ key ].url !== undefined){ 
					html_str[ key ] += ' <a title="' + v[ key ].target + '"></a><a href="' + v[ key ].url + '" target="_blank">' + v[ key ].target + '</a> ';
				} 
				else{ 
					html_str[key] += ' ' + v[ key ].target + '';
				} 
			}	
			html_str[key] += '</td></tr></table>';
		}
	}
	return html_str.join('<br>');
};		

var pubMedCitations = {};
var getPubmedCitation = function (arr,id){
	if(pubMedCitations[id]){ return pubMedCitations[id];}
	
	if(typeof arr == 'object'){	
		var ids = arr.join(',');
		
		Ext.Ajax.request({				
			url: '/projects/geo/tools/pmqproxy.cgi?'+ids,		 
			method: 'post',
			success: function ( result, request ){				
				var obj = result.responseText;
				var t = Ext.get('citations_'+id);
				if(t && typeof obj != 'undefined'){ 
					var text = '<h3><b>Publications</h3><div id="box">'+obj+'</div>';
					pubMedCitations[id] = text;
					t.update(text);
				}				
			},
			failure: function (){	
				var t = Ext.get('citations');
				if(t){ 
					var text = pubmed_renderer(arr);
					pubMedCitations[id] = text;
					t.update(text);
				}				 
			}
		});
	}
	return '';
}

var pubmed_renderer = function (obj){
	  var html = '';
	  if( checkIfExists(obj) ) { 
		  html += '<h3><b>Publications</h3><div id="box"> ';
		  var ids = '';
		  for (var i in obj){
			  var pubmed_id = obj[i];
			  if(typeof pubmed_id == 'function'){continue;}
			  ids += ' <a href="http://www.ncbi.nlm.nih.gov/sites/entrez?db=pubmed&cmd=search&term=' + pubmed_id + '" target="_new">'+pubmed_id+'</a>,';
			  html += '<p><b>PubMed:</b> <a href="http://www.ncbi.nlm.nih.gov/sites/entrez?db=pubmed&cmd=search&term=' + pubmed_id + '" target="_new">'+pubmed_id+'</a></p>';
		  }
		  html +='</div>';
		  if (ids){
			  ids = ids.replace(/\,$/,'');
			  html = "<h3>Publications</h3><div id='box'><p><b>PubMed:</b>" + ids+"</p></div>";
		  }
	  }
	  return html;			
  }