var lastWizardPageVisited;
function _tools_getQueryVariable(variable) {
    var query = decodeURIComponent(window.location.search.substring(1)),
    vars = query.split("&"),
    i,pair;
    for (i=0;i<vars.length;i++) {
        pair = vars[i].split("=");
        if (pair[0] === variable) {
            //            if (pair[1] === 'Enter+search+term+or+accession+number') {
            if (pair[1] === '+Term+|+accession+|+service+name') {
                return '';
            }
            else {
                return decodeURIComponent(pair[1]);
            }
        }
    }
    return '';
}
function setIndexViewTab (){
    var tab = _tools_getQueryVariable("tab")!=='' ? _tools_getQueryVariable("tab") : '',
    subtab = _tools_getQueryVariable("subtab")!=='' ? _tools_getQueryVariable("subtab") : '',
    anchor = _tools_getQueryVariable("anchor")!=='' ? _tools_getQueryVariable("anchor") : '';
    if (tab !== '' || subtab !== '') {
        setTabActive(tab, subtab);
    }
    if(anchor !== ''){
        focusOnDiv(anchor);
    }
}
function setWizardContent(state) {
    //alert("Setting wizard content to:\n"+state);
    var wizardTab;
    window.setLastWizardPageVisited(state);
    if (window.wizardTab === undefined) {
        wizardTab = window.mainTabView.getTab(1);
        wizardTab.fireEvent('setLastWizardPage');
    } else {
        window.wizardTab.fireEvent('setLastWizardPage');
    }
    wizardTab.fireEvent('setLastWizardPage');
    //alert("I'm here");

    recordLinkUse('Wizard_Links', 'Link_Select', state+".html");

}
function setLastWizardPageVisited(lastIn) {
    window.lastWizardPageVisited = lastIn;
}
function getLastWizardPageVisited() {
    if(window.lastWizardPageVisited !== undefined){
        return window.lastWizardPageVisited;
    } else {
        return '0';
    }
}
function checkPDBCode(pdbIn) {
    ////////////////////////////////////////////////////////////////////////////
    var req = false,
    pdbCode = new RegExp("^[0-9]{1}[0-9A-Za-z]{3}$");
    if (!pdbCode.test(pdbIn)) {
        alert("PDB accession codes are of the form 1xyz.");
    } else {
        // For Safari, Firefox, and other non-MS browsers
        if (window.XMLHttpRequest) {
            try {
                req = new XMLHttpRequest();
            } catch (exception) {

                req = false;
            }
        } else if (window.ActiveXObject) {
            // For Internet Explorer on Windows
            try {
                req = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (exception1) {
                try {
                    req = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (exception2) {
                    req = false;
                }
            }
        }
        ////////////////////////////////////////////////////////////////////////////

        if (req) {
            // Synchronous request, wait till we have it all
            req.open('GET', '/pdbe-srv/view/entry/'+pdbIn+'/exists', false);
            req.send(null);

            if (req.responseText === 'yes') {
                return true;
            } else {
                alert("'"+pdbIn+"' has not yet been assigned.");
                return false;
            }

        } else {
            alert("Sorry, your browser does not support " +
                "XMLHTTPRequest (We cannot validate the PDB " +
                "accession number you provided). This page requires " +
                "Internet Explorer 5 or better for Windows, " +
                "or Firefox for any system, or Safari. Other " +
                "compatible browsers may also exist.");
        }
    }
    return false;
}
function getSearchServiceResults(searchTerm, target) {
    if (searchTerm.value === '') {
        if (target === 'summary') {
            window.open('/pdbe-srv/view/search?search_type=advanced', 'summary');
            return false;
        }
        else if (target === 'pisa') {
            window.open('/msd-srv/prot_int/pistart.html', 'pisa');
            return false;
        }
        else if (target === 'ssm') {
            window.open('/msd-srv/ssm', 'ssm');
            return false;
        }
        else if (target === 'motif') {
            window.open('/pdbe-site/PDBeMotif', 'motif');
            return false;
        } else {
            alert("Unfortunately no search term was provided.");
            return false;
        }
        return false;
    }
    if (target === 'motifLigandInteraction') {
        window.open('/pdbe-site/pdbemotif/?tab=simplesearch&ligandcode='+searchTerm.value, 'motif');
        return false;
    }
    if (target === 'emdbsummary') {
        window.open('/pdbe-srv/emsearch/atlas/'+searchTerm.value+'_summary.html', 'emdbsummary');
        return false;
    }
    if (checkPDBCode(searchTerm.value)) {
        if (target === 'summary') {
            window.open('/pdbe-srv/view/entry/'+searchTerm.value+'/summary', 'summary');
        }
        else if (target === 'pisa') {
            window.open('/msd-srv/pisa/cgi-bin/piserver?qa='+searchTerm.value, 'pisa');
        }
        else if (target === 'ssm') {
            window.open('/msd-srv/ssm/cgi-bin/ssmserver?q='+searchTerm.value, 'ssm');
        }
        else if (target === 'motif') {
            window.open('/pdbe-site/pdbemotif/?tab=sequence&pdb='+searchTerm.value, 'motif');
        }
        else if (target === 'downloadPDB') {
            window.open('ftp://ftp.ebi.ac.uk/pub/databases/msd/pdb_uncompressed/pdb'+searchTerm.value+'.ent', 'downloadPDB');
        }
        else if (target === 'downloadData') {
            window.open('/pdbe-srv/view/entry/'+searchTerm.value+'/downloads.html', 'downloadPDB');
        } else {
            return false;
        }
    }
    return false;
}
function validate_email(field,alerttxt)
{
    var apos=field.value.indexOf("@"),
    dotpos=field.value.lastIndexOf(".");
    if (apos<1||dotpos-apos<2)
    {
        alert(alerttxt);
        return false;
    }
    else {
        return true;
    }
}
function validate_required(field,alerttxt)
{

    if (field.value===null||field.value==="")
    {
        alert(alerttxt);
        return false;
    }
    else
    {
        return true;
    }
}
function validateForm(formIn) {
    if (validate_required(formIn.name,"Name should be filled out.")===false)
    {
        formIn.name.focus();
        return false;
    }
    if (validate_required(formIn.email,"Email must be filled out!")===false || validate_email(formIn.email,"Not a valid e-mail address!")===false)
    {
        formIn.email.focus();
        return false;
    }
    if (validate_required(formIn.subject,"Subject should be filled out.")===false)
    {
        formIn.subject.focus();
        return false;
    }
    if (validate_required(formIn.body,"Message body should be filled out.")===false)
    {
        formIn.body.focus();
        return false;
    }
    try {
        formIn.refererLocation.value = getQueryVariable("referer");
    } catch (exception) {}

    return true;
}
function submitForm(formIn) {
    if (validate_required(formIn.name,"Name should be filled out.")===false)
    {
        formIn.name.focus();
        return false;
    }
    if (validate_required(formIn.email,"Email must be filled out!")===false || validate_email(formIn.email,"Not a valid e-mail address!")===false)
    {
        formIn.email.focus();
        return false;
    }
    if (validate_required(formIn.subject,"Subject should be filled out.")===false)
    {
        formIn.subject.focus();
        return false;
    }
    if (validate_required(formIn.body,"Message body should be filled out.")===false)
    {
        formIn.body.focus();
        return false;
    }
    return true;
}
function sequenceSearch(formIn, searchType) {
    var display = '',
    urlRoot = '',
    seqToSearch,
    eValue,
    ECNum,
    targetWindow,i;
    //alert(searchType);
    /////////////////////////
    for (i = 0; i < formIn.displayStyle.length; i++) {
        if (formIn.displayStyle[i].checked) {
            display = formIn.displayStyle[i].value;
        }
    }
    //alert("Display: "+display+", SearchType: "+searchType)
    if (searchType === 'sequence') {
        if (validate_required(formIn.sequence,"A sequence must be provided!")===false)
        {
            formIn.sequence.focus();
            return false;
        } else {
            seqToSearch = formIn.sequence.value.replace(/^>.*$/m, '');
        }
        if (validate_required(formIn.evalue,"A valid E-value must be provided!")===false)
        {
            formIn.evalue.focus();
            return false;
        } else {
            eValue = formIn.evalue.value;
        }
    }
    if (searchType === 'EC') {
        if (validate_required(formIn.EC,"An EC number should be provided for searching!")===false)
        {
            formIn.EC.focus();
            return false;
        } else {
            ECNum = formIn.EC.value;
        }
    }
    ///////////////////////////
    if (display==='tabular'){
        //        alert("Opening pdbeView results");
        if (searchType === 'sequence'){
            urlRoot = "/pdbe-srv/view/search?search_type=advanced";
            urlRoot += "&sequence="+seqToSearch+"&evalue="+eValue.toLowerCase();
        }
        if (searchType === 'EC') {
            urlRoot = "/pdbe-srv/view/search?search_type=advanced";
            urlRoot += "&EC_number="+ECNum;
        }
        targetWindow = 'pdbeViewResults';
    }
    if(display==='browser'){
        if (searchType === 'sequence'){
            urlRoot = "/pdbe-srv/PDBeXplore/sequence/?";
            urlRoot += "seq="+seqToSearch+"&eVal="+eValue;
        }
        if (searchType === 'EC') {
            urlRoot = "/pdbe-srv/PDBeXplore/enzyme/?";
            urlRoot += "&ec="+ECNum;
        }
        targetWindow = 'PDBeXploreResults';
    }
    window.open(urlRoot, targetWindow);
    return false;
}
function getFeatureArticleNumber(increment) {
    if (increment === null) {
        increment = 1;
    }
    if (window.featureArticleNumber === null ||this.featureArticleNumber === undefined){
        window.featureArticleNumber = 0;
    } else {
        window.featureArticleNumber+=increment;
    }
    //alert(window.featureArticleNumber);
    return (window.featureArticleNumber < 0 ) ? window.featureArticleNumber*-1: window.featureArticleNumber;
}

function hide(div_id) {
    document.getElementById(div_id).style.display = "none";
}

function show(div_id, anchor) {

    if ( document.getElementById(div_id).style.display == "block"){
        document.getElementById(div_id).style.display = "none";
    }
    else if ( document.getElementById(div_id).style.display == "none"){
        document.getElementById(div_id).style.display = "block"
    }
    if (anchor.innerHTML== "Hide"){
        anchor.innerHTML = "See SQL";
    }
    else if (anchor.innerHTML == "See SQL"){
        anchor.innerHTML = "Hide";
    }
}