var ajaxObj = new XMLHTTP('mybic_server.php');
var flagObj = new Array();

var submittable = false;

// lets turn on debugging so we can see what we're sending and receiving
ajaxObj.debug=0;
	

function AJAX_submitInfo(fields) 
{ 
    var formVars = ajaxObj.getForm('bob');
    ajaxObj.call('action=AJAX_obtaintgaccession'+formVars,afterSubmit);
}
function AJAX_getAuthors(lid)
{
    ajaxObj.call('action=AJAX_obtaintgaccession&do=GetAuthors&LID=' + lid,afterGetAuthors);
}

function afterSubmit(resp)
{
    if(resp != '1')
    {
	alert('Error:' + resp);
    }
    else
    {
	window.location='thanks.php';
    }
}

function afterGetAuthors(resp)
{
    fields = getFields();
    target = fields['COLLEAGUE'];

    // Remove old options
    while(target.options.length > 1) { target.options[1] = null; }

    var counter = 2;
    // Add New Options
    for(var i=0;i<resp.length;i++)
    {
	var arr = resp[i];
	target.options[counter] = new Option(arr[1],arr[0]);
	counter++;
    }
}

function afterFillFields(resp)
{
    fields = getFields();
    str = '';
    for(key in resp)
    {
	str += key + ':' + resp[key] + "\n";
    }
    fields['NAME'].value = resp['name'];
    fields['MANAGER'].value = resp['manager'];
    fields['EMAIL'].value = resp['email'];
    fields['URL'].value = resp['url'];
    fields['PHONE'].value = resp['phone'];
    fields['FAX'].value = resp['fax'];
    fields['ADDRESS'].value = resp['address'];
    fields['CITY'].value = resp['city'];
    fields['STATE'].value = resp['state'];
    fields['ZIP'].value = resp['zip'];

    // Select boxes
    fields['COUNTRY'].selectedIndex = findSelctionIndex(resp['country'],fields['COUNTRY']);

    checkFields();
}


function findSelectionIndex(str,obj)
{
    for(key in obj.options)
    {
	if(obj.options[key].textContent == str) return(key);
    }
    return('0');
}
    
    
    



function notBlank(caller)
{
    img = getIMG(caller);
    if(caller.value != '')
    {
	s = new String(caller.value);
	s = s.replace(/'/g,"&apos;");
	s = s.replace(/"/g,"&quot;");
	caller.value=s;
	
	imageGreen(img);
	return(true);
    }
    else
    {
	imageRed(img);
	return(false);
    }
}

function getIMG(caller)
{
    current = caller;
    var row;
    while(current)
    {
	if(current.nodeName=='TR')
	{
	    row=current;
	    break;
	}
	current=current.parentNode;
    }
	
    var othertd;
    for(i=0;i<row.childNodes.length;i++)
    {
	if(row.childNodes[i].nodeName=='TD')
	{
	    othertd = row.childNodes[i];
	    break;
	}
    }

    for(i=0;i<othertd.childNodes.length;i++)
    {
	if(othertd.childNodes[i].nodeName=='IMG')
	{
	    img = othertd.childNodes[i];
	    break;
	}
    }
    return(img);
}
	    
function imageRed(img)
{
	img.src='/images/RedX.png';
}
function imageGreen(img)
{
	img.src='/images/GreenCheck.png';
}

function getFields()
{
    frm = document.forms['bob'];
    var arr = new Array();
    for(i=0;i<frm.elements.length;i++)
    {
	if(frm.elements[i].name)
	{
	    var a = frm.elements[i].name;
	    if(arr[a])
	    {
		var target = arr[a];
		if(isArray(arr[a]))
		{
		    var b = target;
		    b.push = frm.elements[i];
		    arr[a] = b;
		}
		else
		{
		    var b = new Array();
		    b[0]=target;
		    b[1]=frm.elements[i];
		    arr[a] = b;
		}
	    }
	    else
	    {
		arr[a] = frm.elements[i];
	    }
	}
    }
    return(arr);
}

function checkFields()
{
    fields = getFields();
    var good = true;
    messages = new Array();
    if(!notBlank(	fields['COLLEAGUE']))	{ good = false; messages.push("Primary Author"); }
    else		{ ajaxObj.call('action=AJAX_obtaintgaccession&do=GetEMAIL&AID='+fields['COLLEAGUE'].value,afterfillEMAIL); }
    if(!checkAuthors(	fields['AUTHORS[]']))	{ good = false; messages.push("Other Authors");}
    if(!notBlank(	fields['TITLE']))	{ good = false; messages.push("Title");}
    if(!notBlank(	fields['JOURNAL']))	{ good = false; messages.push("Journal"); }
//    else  		{ ajaxObj.call('action=AJAX_publication&do=GetURL&JID='+fields['JOURNAL'].value,afterfillURL); }
    if(!notBlank(	fields['ABSTRACT']))	{ good = false; messages.push("Abstract"); }
    if(!checkKeyword())				{ good = false; messages.push("Keyword"); }
//    if(!notBlank(	fields['KEYWORD[]'][1]))	{ good = false; messages.push("Keyword"); }
    img=getIMG(fields['FILE_NAME_MAP']);
    if(fields['FILE_NAME_MAP'].value == '')	{ good = false; messages.push("File"); imageRed(img); }
    else					{ imageGreen(img); }
    img=getIMG(fields['ORGANIZATION']);
    if(fields['ORGANIZATION'].value == '')	{ good = false; messages.push("Organization"); imageRed(img); }
    else					{ imageGreen(img); }
    if(!notBlank(	fields['EMAIL']))	{ good = false; messages.push("Author's Email"); }
    if(good){ return fields; }
    return new Array(false,messages);
}

function checkKeyword()
{
    var i = 1;
    var j = getCounter();  // getCounter is from obtaintga.php
    fields = getFields();
    fields['KEYWORDCOUNT'].value = j;
//    alert(fields['KEYWORDCOUNT'].value);
    var k = 0;
    var id = "";
    var name = "";
    
    while(i <= j)
    {
        id = 'KEYID' + i;
        name = 'KEYNAME'  + i;
	if(fields[id].value != '')
	{
	    if(fields[id].value == 'other')
	    {
		if(fields[name].value != '' && fields[name].value != "Click Here to Insert Keyword")
		    k++;
	    	fields[name].readOnly = false;
	    	fields[name].className = 'SelectSpecies';
		if(fields[name].value == '')
		    fields[name].value = 'Click Here to Insert Keyword';
	    }
	    else
	    {
		if(fields[name].value == "Click Here to Insert Keyword")
		    fields[name].value = '';
	        fields[name].readOnly = true;
	        fields[name].className = 'SelectSpecies_ReadOnly';
		k++;
	    }
//	    alert(id + "=" + fields[id].value);
//	    alert(name + "=" + fields[name].value);
	}
	else
	{
	    fields[name].readOnly = true;
	    fields[name].className = 'SelectSpecies_ReadOnly';
	}
	i += 1;
    }
    imgcaller = document.getElementById('KEYIMG');
    img = getIMG(imgcaller);
//    alert("count value = " + k);
    if(k >= 2)
    {
	imageGreen(img);
	return true;
    }
    else
    {
	imageRed(img);
	return false;
    }
}

function afterCHECK(resp)
{
    if(resp[0] != -1)
    {
	alert(resp[1]);
    }
    else
    {
	alert("error" + resp[1]);
    }
}

function afterfillEMAIL(email)
{
    fields = getFields();
    if(email == false)
    {
	fields['EMAIL'].value = '';
	if(confirm("ERROR:  Email has been flagged or no email present for Primary Author.  Please click OK to be redirected to update Primary Author's email address."))
	{
	    window.location = "http://dendrome.ucdavis.edu/treegenes/directory/colleague_detail.php?id=" + fields['COLLEAGUE'].value;
//	    window.open('http://dendrome.ucdavis.edu/treegenes/directory/colleague_detail.php?' + fields['COLLEAGUE'].value,'test','width=600,height=800');
	}
    }
    else
    {
	fields['EMAIL'].value = email;
    }
    
}

function checkAuthors(fields)
{
    nodes = fields[0].parentNode.childNodes;
    var AuthorExp = /^\w+, .+$/;
    var notBlank = /\S/;
    msg = '';
    for(key in nodes) 
    { 
	if(nodes[key].value != undefined)
	{
	    if(notBlank.exec(nodes[key].value))
	    {
		res = AuthorExp.exec(nodes[key].value);
		if(!res) {return false;}
		s = new String(nodes[key].value);
		s = s.replace(/'/g,"&apos;");
		s = s.replace(/"/g,"&quot;");
		nodes[key].value=s;
	    }
	}
    }
    return true;
}

function checkNumber(em)
{   
    var emailExp = /^\d+$/;
    res = emailExp.exec(em.value);

    img = getIMG(em);
    if(res)
    {   
	imageGreen(img);
	return true;
    }

    imageRed(img);
    return false;
}

function isArray(obj) {
    if (obj.constructor.toString().indexOf("Array") == -1)
	return false;
    else
	return true;
}

function submitInfo()
{
    var fields = checkFields();
    if(fields[0] == false)
    {
	msg = 'One or more of the fields are not fileld out properly:';
	errors = fields[1];
	for(key in errors)	{ msg += "\n" + errors[key]; }
	alert(msg);
	return;
    }
    fields['FILE'].value = fields['FILE_NAME_MAP'].value;
    document.bob.submit();
    return;
}

function afterCheckData(res)
{
    if(res[0] == false)
    {
	alert(res[1]);
	return false;
    }
}

function fillFields(cix)
{
    AJAX_FillFields(cix);
}

function addNewLine(caller)
{
    var targetNode;
    for(i=0;i<caller.parentNode.childNodes.length;i++)
    {
	if(caller.parentNode.childNodes[i].nodeName=='INPUT' || caller.parentNode.childNodes[i].nodeName=='SELECT')
	{
	    targetNode = caller.parentNode.childNodes[i];
	}
    }
    if(targetNode.value != '')
    {
	var cloned = clone(targetNode,caller.parentNode);
	caller.parentNode.appendChild(caller);
	return(cloned);
    }
    else
    {
	alert('You may not add another item until you have filled out the current one.');
    }
}

function clone(target,container)
{
    var clone = target.cloneNode(true);
    container.appendChild(clone);
    clone.value='';
    return(clone);
}

	
