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;
ajaxObj.abort_timeout = 10000;

	

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

 function afterSubmit(resp)

{   
    if(resp == '1')
    {
	window.location='thanks.php';
	  
    }
    else if(resp=='-1')
     {
        alert('Error:' + resp);
       //window.open();
     
     }
    else 
    {
	 var showPaper=window.confirm("We have this paper already. Do you want to view it? (Please enable popup window for this page to view the paper.)");
	 if(showPaper)   
	   window.open("http://dendrome.ucdavis.edu/treegenes/literature/literature_detail.php?id="+resp, "", "width=screen.width, height=screen.height, resizable, scrollbars, toolbar, menubar, status");
	
    }
}

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"); }
    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['VOLUME']))	{ good = false; messages.push("Volume"); }
    if(!checkNumber(	fields['FROM_PG']))	{ good = false; messages.push("From page"); }
    if(!checkNumber(	fields['TO_PG']))	{ good = false; messages.push("To page"); }
    if(!checkNumber(	fields['YEAR']))	{ good = false; messages.push("Year"); }
    if(!notBlank(	fields['ABSTRACT']))	{ good = false; messages.push("Abstract"); }
    if(!notBlank(	fields['KEYWORD[]'][1]))	{ good = false; messages.push("Keyword"); }
    if(good){ return fields; }
    return new Array(false,messages);
}

function afterfillURL(url)
{
    fields = getFields();
    fields['URL'].value = url;
}

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(type)
{
    if(type=='delete')
    {
	fields=getFields();
//	AJAX_DeleteOrganization(fields['CIX'].value);
    }
    else
    {
	var fields = checkFields();
	if(fields[0] == false)
	{
	    msg = 'One or more of the fields are not filled out properly:';
	    errors = fields[1];
	    for(key in errors) { msg += "\n" + errors[key]; }
	    alert(msg);
	}
	else
	{
	    if(type=='add')
	    {
		AJAX_submitInfo(fields);
	    }
	    if(type=='modify')
	    {
		AJAX_submitInfo(fields);
	    }
	}
    }
}

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);
}

	
