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_organization'+formVars,afterSubmit);
}
function AJAX_checkCode(code)
{
    ajaxObj.call('action=AJAX_organization&do=CheckCode&CODE=' + code,afterCheckCode);
}
function AJAX_GetPapers(aid)
{
    ajaxObj.call('action=AJAX_supplemental&do=GetPapers&AID=' + aid,afterGetPapers);
}

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

function afterCheckCode(resp)
{
    submittable = false;
    fields = getFields();
    codeObj = fields['CODE'];
    img = getIMG(codeObj);
    if(resp)
    {
	imageGreen(img);
	submittable = true;
	checkFields2();
	return;
    }
    checkFields2();
    imageRed(img);
}

function AJAX_DeleteOrganization(gid)
{
    alert(gid);
}

function AJAX_FillFields(cix)
{
    ajaxObj.call('action=AJAX_organization&do=FillFields&CIX=' + cix,afterFillFields);
}

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 afterGetPapers(resp)
{
    fields = getFields();
    target = fields['PAPER'];

    // 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++;
    }
    checkFields();
} 

function populateExpander(expander,inparr)
{
    var result = '';
    var target = '';
    var next = '';
    for(key in inparr)
    {
	target = next;
	if(next == '') { target = expander[1]; }
	
	target.value = inparr[key];
	for(i=0;i<target.parentNode.childNodes.length;i++)
	{
	    if(target.parentNode.childNodes[i].nodeName=='SPAN')
	    { result = target.parentNode.childNodes[i];  break; }
	}
	next = addNewLine(result);
    }
}

function findSelectionIndex(str,obj)
{
    for(key in obj.options)
    {
	if(obj.options[key].textContent == str) return(key);
    }
    return('0');
}
    
function chooseAuthor()    
{
    fields = getFields();
    aid = fields['AUTHOR'].value;

    AJAX_GetPapers(aid);
}


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

function checkEmail(em)
{
    var emailExp = /\S+@\S+\.\S+/;
    var emailExp2 = /["<"|">"]/;
    res = emailExp.exec(em.value);
    res2 = emailExp2.exec(em.value);
    
    img = getIMG(em);
    if(res && !res2)
    {
	imageGreen(img);
	return true;
    }

    imageRed(img);
    return false;
}
function checkPhone(ph)
{
    var phExp = /^\d+$/;
    res = phExp.exec(ph.value);

    img = getIMG(ph);
    if(res)
    {
	imageGreen(img);
	return true;
    }
    imageRed(img);
    return false;
}

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 deactivateSection(label)
{
    document.getElementById(label).style.display='none';
}
function activateSection(label)
{
    document.getElementById(label).style.display='block';
}
function turnOnSection(label)
{
    deactivateSection('GBHeader');
    deactivateSection('FileHeader');
    deactivateSection('CmapHeader');
    
    activateSection(label);
}
	
	

function checkFields()
{
    fields = getFields();
    messages = new Array();
    var good = true;
    if(!notBlank(fields['AUTHOR'])){ good = false; messages.push("Author");}
    if(!notBlank(fields['PAPER'])){ good = false; messages.push("Paper");}
    if(!notBlank(fields['TYPE'])){ good = false; messages.push("Supplement Type");}

    switch(fields['TYPE'].value)
    {
	case 'File':
	    turnOnSection('FileHeader');
	    if(!notBlank(fields['FILE_NAME']))	{ good = false; messages.push("File");}
	    if(!notBlank(fields['DESCRIPTION'])){ good = false; messages.push("Description");}
	    if(!notBlank(fields['RECORDS']))	{ good = false; messages.push("Number of Records");}
	    break;
	case 'Genbank Accession':
	    turnOnSection('GBHeader');
	    if(!notBlank(fields['ACCESSION']))	{ good = false; messages.push("Accession Number");}
	    break;
	case 'Genetic Map':
	    turnOnSection('CmapHeader');
	    if(!notBlank(fields['FILE_NAME_MAP'])) { good = false; messages.push("File");}
	    if(!notBlank(fields['ORGANIZATION'])) { good = false; messages.push("Organization");}
	    break;
	default:
	    turnOnSection('blank');
	    good = false;
	    break;
    }
    
    if(good){ return fields; }
    return new Array(false,messages);
}

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

function submitInfo(type)
{
    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);
	return;
    }
    document.bob.submit();
    return;

    if(type=='delete')
    {
	fields=getFields();
	AJAX_DeleteOrganization(fields['CIX'].value);
    }
    else
    {
	var fields = checkFields2();
	if(!fields)
	{
	    alert('One or more of the fields are not filled out properly');
	}
	else
	{
	    if(type=='add')
	    {
		AJAX_submitInfo(fields);
	    }
	    if(type=='modify')
	    {
		AJAX_submitInfo(fields);
	    }
	}
    }
}

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