var gsdl = { //based on prototype
    Version: '1.00.000',

    Browser: {
        IE:     !!(window.attachEvent &&
            navigator.userAgent.indexOf('Opera') === -1),
        Opera:  navigator.userAgent.indexOf('Opera') > -1,
        WebKit: navigator.userAgent.indexOf('AppleWebKit/') > -1,
        Gecko:  navigator.userAgent.indexOf('Gecko') > -1 &&
        navigator.userAgent.indexOf('KHTML') === -1
    },

    BrowserFeatures: {
        XPath: !!document.evaluate,
        SelectorsAPI: !!document.querySelector,
        ElementExtensions: !!window.HTMLElement,
        SpecificElementExtensions:
        document.createElement('div')['__proto__'] &&
        document.createElement('div')['__proto__'] !==
        document.createElement('form')['__proto__']
    },
    emptyFunction: function() { }
};
gsdl.url = '';
gsdl.onPageLoad = null;
gsdl.serverURL = location.protocol + '//' + location.host;
gsdl.defaults = {
    args: {
        clmd: 50,
        o: 50,
        m: 0,
        s: 0,
        k: 1,
        t: 0
    }
};
gsdl.afterJQueryLoad = [];
if (typeof(Array.prototype.push) == 'undefined')
{
    Array.prototype.push = function(v) {
        this[this.length] = v;
    }
}

if (typeof(Array.prototype.indexOf) == 'undefined')
{
    Array.prototype.indexOf = function(obj) {
        var i;
        for(i = 0; i < this.length; ++i) {
            if (this[i] == obj) return i;
        }
        return -1;
    }
}

if (typeof(Array.prototype.remove) == 'undefined')
{
    Array.prototype.remove = function(obj) {
        var i;
        for(i = 0; i < this.length; ++i) {
            if (this[i] == obj) {
                this.splice(i, 1);
                return true;
            }
        }
        return false;
    }
}

if (typeof(Array.prototype.splice) == 'undefined')
{
    Array.prototype.splice = function(start, deleteCount) {
        var i;
        for(i = start + deleteCount; i < this.length; ++i) {
            this[i - deleteCount] = this[i];
        }
        this.length = this.length - deleteCount;
    }
}

if (typeof(Array.prototype.dequeue) == 'undefined')
{
    Array.prototype.dequeue = function() {
        var data = this[0];
        this.splice(0, 1);
        return data;
    }
}

if (typeof(String.prototype.trim) == 'undefined')
{
    String.prototype.trim = function() {
        var str = this.replace(/^\s\s*/, ''), ws = /\s/;
        var i = str.length;
        while (ws.test(str.charAt(--i))) {}
        return str.slice(0, i + 1);
    }
}

if (typeof(String.prototype.gsdl_clean) == 'undefined')
{
    String.prototype.gsdl_clean = function() {
        var str = this.replace(/^\s\s*/, ''), ws = /\s/;
        var i = str.length;
        while (ws.test(str.charAt(--i))) {}
        var rd = new RegExp('\\s{2,}', 'g');
        return str.slice(0, i + 1).replace(rd, ' ');
    }
}

if (typeof(String.prototype.rtrim) == 'undefined')
{
    String.prototype.rtrim = function(chars) {
        var r;
        if (typeof(chars) == 'undefined' || chars == null)
            r = /\s/;
        else
            r = new RegExp(chars.length == 1 ? chars : '[' + chars + ']');
        var i = this.length;
        while (r.test(this.charAt(--i))) {}
        return this.slice(0, i + 1);
    }
}

if (typeof(String.prototype.startsWith) == 'undefined')
{
    String.prototype.startsWith = function(prefix) {
        return this.indexOf(prefix) === 0;
    }
}

if (typeof(String.prototype.endsWith) == 'undefined')
{
    String.prototype.endsWith = function(suffix) {
        if (this.length < suffix.length)
            return false;
        return this.lastIndexOf(suffix) === this.length - suffix.length;
    }
}

var OID = {
    oidToSafeIdRegExp: new RegExp('\\.', 'g'),
    safeIdToOIDRegExp: new RegExp('_', 'g'),
    getTop: function(id, sep) {
        if (typeof(sep) == 'undefined' || sep == null) sep = '.';
        var pos = id.indexOf(sep);
        if (pos > 0)
            return id.substr(0, pos);
        return id;
    },
    getParents: function(id, sep) {
        if (typeof(sep) == 'undefined' || sep == null) sep = '.';
        // the array, start position, end position
        var a = [], sp = 0, ep = 0;
        while ((ep = id.indexOf(sep, sp)) > -1) {
            a.push(id.substring(0, ep));
            sp = ep + 1;
        }
        return a;
    },
    getParent: function(id, sep) {
        if (typeof(sep) == 'undefined' || sep == null) sep = '.';
        var pos = id.lastIndexOf(sep);
        if (pos > -1)
            return id.substr(0, pos);
        return '';
    },
    getLevel: function(id, sep) {
        if (typeof(sep) == 'undefined' || sep == null) sep = '.';
        var l = 1, p = 0;
        while ((p = id.indexOf(sep, p)) > -1) {
            ++l;
            ++p;
        }
        return l;
    },
    convertToSafeId: function(oid) {
        return oid.replace(OID.oidToSafeIdRegExp, '_');
    },
    convertFromSafeId: function(id) {
        return id.replace(OID.safeIdToOIDRegExp, '.');
    }
};

function changeSection(objSelect) {
    if (!objSelect) return;
    var index = objSelect.selectedIndex;
    var sectionID = objSelect.options[index].value;
    var weaID = 'HASH6731e5b341863c8b95d12c';
    if (sectionID.length) sectionID = '.' + sectionID;
    if (index > 0)
        gsdl_goto(gsdl.url + cgiarg.l + '/d/' + weaID + sectionID + '/');
}

function gsdlTrimFieldValue(objField) {
    if (objField != null && objField.value != null) {
        objField.value = objField.value.gsdl_clean();
    }
}

function openWindow (address) {
    open(fix_url2(address), '_blank', 'width=600,height=400,menubar=yes,location=yes,status=yes,toolbar=yes,resizable=yes,scrollbars=yes');
}

function openWindow1 (address) {
    open(fix_url2(address), '_blank', 'width=600,height=400,menubar=yes,location=no,status=yes,toolbar=no,resizable=yes,scrollbars=yes');
}

function openWindow2 (address, width, height) {
    if (typeof(width) == 'undefined' || width == null) width = 300;
    if (typeof(height) == 'undefined' || height == null) height = 200;
    open(fix_url2(address), '_blank', 'width='+width+',height='+height+',menubar=no,location=no,status=yes,toolbar=no,resizable=yes,scrollbars=yes');
}

function openWindow3 (address, width, height) {
    if (typeof(width) == 'undefined' || width == null) width = 300;
    if (typeof(height) == 'undefined' || height == null) height = 200;
    open(fix_url2(address), '_blank', 'width='+width+',height='+height+',menubar=yes,location=no,status=yes,toolbar=no,resizable=yes,scrollbars=yes');
}

function openExtLink(address) {
    open(address, '_blank', 'width=600,height=400,menubar=yes,location=yes,status=yes,toolbar=yes,resizable=yes,scrollbars=yes');
}

function openCourseWindow(address, width, height, title) {
    var offset = 25, posX, posY;
    if (screen.availHeight > height) height = screen.availHeight - 2*offset;
    if (screen.availWidth > width) width = screen.availWidth - 2*offset;
    posY = (screen.availHeight - height) / 2;
    posX = (screen.availWidth - width) / 2;
    open(address, '_blank', 'top='+posY+',left='+posX+',width='+width+',height='+height+',menubar=no,location=no,status=no,toolbar=no,resizable=yes,scrollbars=yes');
}

function openFixedWindow (address, width, height) {
    var posX, posY, nHeight, nWidth, offset = 10;
    nHeight = (screen.availHeight > height ? height :  screen.availHeight - 2*offset);
    nWidth = (screen.availWidth > width ? width : screen.availWidth - 2*offset);
    posY = (screen.availHeight - nHeight) / 2;
    posX = (screen.availWidth - nWidth) / 2;
    open(address, '_blank', 'top='+posY+',left='+posX+',width='+width+',height='+height+',menubar=no,location=no,status=no,toolbar=no,resizable=yes,scrollbars=no');
}

function resizeFixedWindow (width, height) {
    var posX, posY, nHeight, nWidth, offset = 10;
    nHeight = (screen.availHeight > height ? height :  screen.availHeight - 2*offset);
    nWidth = (screen.availWidth > width ? width : screen.availWidth - 2*offset);
    posY = (screen.availHeight - nHeight) / 2;
    posX = (screen.availWidth - nWidth) / 2;
    moveTo (posX, posY);
    resizeTo (nWidth, nHeight);
}

function openModalWindow (address, width, height) {
    if (isGecko) {
        window.open(address, '', 'chrome,modal');
    } else {
        var ret = window.showModalDialog(address, '', 'dialogWidth:'+width+'px;dialogHeight:'+height+'px;center:1;status:0;help:0');
        if (ret != null && typeof(ret) != 'undefined' && ret != '') {
            var idx = ret.indexOf(':');
            if (idx > -1) {
                var strAction = ret.substr(0, idx);
                if (strAction == 'reload') {
                    window.location.reload(true);
                } else if (strAction == 'add') {
                    var strURL = gsdlLocationAddParam(window.location, ret.substr(idx+1));
                    window.setTimeout("window.location = '" + strURL + "'", 400);
                } else if (strAction == 'new') {
                    openWindow(ret.substr(idx+1));
                } else if (strAction == 'addnew') {
                    openWindow(window.location.href + ret.substr(idx+1));
                } else if (strAction == 'go') {
                    window.setTimeout("window.location = '" + ret.substr(idx+1) + "'", 400);
                } else {
                    window.setTimeout("window.location = '" + ret + "'", 400);
                }
            }
        }
    }
}

function openPrintPreviewWindow(address, width, height) {
    if (typeof(width) == 'undefined' || width == null) width = 300;
    if (typeof(height) == 'undefined' || height == null) height = 200;
    var ampReg;
    if (IE4plus && !IE4) {
        ampReg = new RegExp('&', 'g');
        address = address.replace(ampReg, '&' + 'amp' + ';');
    } else {
        ampReg = new RegExp('&amp;', 'g');
        address = address.replace(ampReg, '&');
    }
    open(address, '_blank', 'width='+width+',height='+height+',menubar=yes,location=no,status=yes,toolbar=yes,resizable=yes,scrollbars=yes');
}

function openExportWindow(format, encoding, width, height) {
    if (typeof(format) == 'undefined' || format == null) format = 'zip';
    if (typeof(encoding) == 'undefined' || encoding == null) encoding = 'utf-8';
    if (typeof(width) == 'undefined' || width == null) width = 400;
    if (typeof(height) == 'undefined' || height == null) height = 200;
    var strURL = gsdl.url + cgiarg.l + '/p/exportmsg/d,' + OID.getTop(cgiarg.d) + ',xf,' + format + ',ew,' + encoding + '.html';
    openWindow2(strURL, width, height);
}

function openExportHelpWindow() {
    var strURL = gsdl.url + cgiarg.l + '/p/ExportContextHelp/';
    openWindow2(fix_url(strURL), 480,400);
}

//
// Browser Detection
//
isMac = (navigator.appVersion.indexOf('Mac')!=-1) ? true : false;
NS4 = (document.layers) ? true : false;
IEmac = ((document.all)&&(navigator.appVersion.indexOf('MSIE')!=-1)&&(isMac)) ? true : false;
IE4plus = ((document.all)&&(navigator.appVersion.indexOf('MSIE')!=-1)) ? true : false;
IE4 = ((document.all)&&(navigator.appVersion.indexOf('MSIE 4.')!=-1)) ? true : false;
IE5 = ((document.all)&&(navigator.appVersion.indexOf('MSIE 5.')!=-1)) ? true : false;
IE55 = ((document.all)&&(navigator.appVersion.indexOf('MSIE 5.5')!=-1)) ? true : false;
IE6 = ((document.all)&&(navigator.appVersion.indexOf('MSIE 6.')!=-1)) ? true : false;
IE7 = ((document.all)&&(navigator.appVersion.indexOf('MSIE 7.')!=-1)) ? true : false;
IE8 = ((document.all)&&(navigator.appVersion.indexOf('MSIE 8.')!=-1)) ? true : false;
IE9 = ((document.all)&&(navigator.appVersion.indexOf('MSIE 9.')!=-1)) ? true : false;
ver4 = (NS4 || IE4plus) ? true : false;
NS6 = (!document.layers) && (navigator.userAgent.indexOf('Netscape')!=-1)?true:false;
isGecko = (navigator.userAgent.indexOf(' Gecko/')!=-1)?true:false;
IE5plus = IE5 || IE6 || IE7 || IE8 || IE9;
IE55plus = IE55 || IE6 || IE7 || IE8 || IE9;
IE6plus = IE6 || IE7 || IE8 || IE9;
IEMajor = 0;

if (IE4plus)
{
    var start = navigator.appVersion.indexOf('MSIE');
    var end = navigator.appVersion.indexOf('.',start);
    IEMajor = parseInt(navigator.appVersion.substring(start+5,end));
    IE5plus = (IEMajor>=5) ? true : false;
    IE55plus = (IE55 || ((IEMajor>5) ? true : false));
}

if (NS4 || NS6) {
    gsdl.escape = escape;
} else {
    gsdl.escape = function(parString) {
        var str = '';
        for(var i = 0; i < parString.length; ++i) {
            if(parString.charCodeAt(i) < 0x80) {
                str += String.fromCharCode(parString.charCodeAt(i));
            }
            else if (parString.charCodeAt(i) < 0x0800) {
                str += String.fromCharCode(parString.charCodeAt(i)>> 6 | 0xC0);
                str += String.fromCharCode(parString.charCodeAt(i) & 0x3F | 0x80);
            }
            else if (parString.charCodeAt(i) < 0x10000) {
                str += String.fromCharCode(parString.charCodeAt(i)>> 12 | 0xE0);
                str += String.fromCharCode(parString.charCodeAt(i)>> 6 & 0x3F | 0x80);
                str += String.fromCharCode(parString.charCodeAt(i) & 0x3F | 0x80);
            }
            else {
                str += String.fromCharCode(parString.charCodeAt(i)>> 18 | 0xF0);
                str += String.fromCharCode(parString.charCodeAt(i)>> 12 & 0x3F | 0x80);
                str += String.fromCharCode(parString.charCodeAt(i)>> 6 & 0x3F | 0x80);
                str += String.fromCharCode(parString.charCodeAt(i) & 0x3F | 0x80);
            }
        }
        return escape(str);
    }
}

function gsdlLocationAddParam(locationObj, strParams) {
    fix_location_hash(locationObj);
    var strArgs = locationObj.search.substr(1);

    var strNewURL = locationObj.protocol + '//' + locationObj.host;
    strNewURL += locationObj.pathname;
    if (strArgs.length) strArgs += '&';
    strArgs += strParams;

    strNewURL += '?' + strArgs;
    if (locationObj.hash.length) strNewURL += locationObj.hash;
	
 
    if (IE5plus) {
        var ampReg = new RegExp('&', 'g');
        strNewURL = strNewURL.replace(ampReg, '&' + 'amp' + ';');
    }
    return strNewURL;
}

function gsdl_goto(strURL) {
    var ampReg = new RegExp('&' + 'amp' + ';', 'g');
    strURL = strURL.replace(ampReg, '&');
    if (IE5plus) {
        var ampReg2 = new RegExp('&', 'g');
        strURL = strURL.replace(ampReg2, '&' + 'amp' + ';');
    }
    window.location = strURL;
    return false;
}

function gsdl_goto_ex(obj, strURL) {
    var ampReg = new RegExp('&' + 'amp' + ';', 'g');
    strURL = strURL.replace(ampReg, '&');
    if (IE5plus) {
        var ampReg2 = new RegExp('&', 'g');
        strURL = strURL.replace(ampReg2, '&' + 'amp' + ';');
    }
    obj.href = strURL;
    return false;
}

function fix_url(strURL) {
    var ampReg = new RegExp('&' + 'amp' + ';', 'g');
    strURL = strURL.replace(ampReg, '&');
    if (IE5plus) {
        var ampReg2 = new RegExp('&', 'g');
        strURL = strURL.replace(ampReg2, '&' + 'amp' + ';');
    }
    return strURL;
}

function fix_url2(strURL) {
    var ampReg = new RegExp('&' + 'amp' + ';', 'g');
    strURL = strURL.replace(ampReg, '&');
    return strURL;
}

function fix_location_hash (oLocationObj) {
    if (IE4 && oLocationObj.search != null) {
        var re = new RegExp ('#.*');
        var arrMatch = oLocationObj.search.match(re);

        if (arrMatch != null && arrMatch.length) {
            oLocationObj.hash = arrMatch[0];
            oLocationObj.search = oLocationObj.search.replace(re, '');
        }
    }
}

var gLocationObj = null;
function clearForm2() {
    clearForm1();
}
function clearForm1() {
    var objTemp = gsdlGetElement('checkall');
    if (objTemp != 'undefined' && objTemp != null) objTemp.checked = false;
	
    var date = new Date();
    if (cgiarg.a == 'q') {
        var queryForm = gsdlGetElement('QueryPostForm');
        g_gsdlPreferenceState.SetFormArgs(queryForm);
        gsdlInitValue(queryForm.uq, '' + date.getTime());
        gsdlInitValue(queryForm.qu, '' + gsdlNewQueryUniqueId());
        gsdlInitValue(queryForm.r, '1');
        gsdlInitValue(queryForm.qe, '0');
        gsdlInitValue(queryForm.q, '');
        gsdlInitValue(queryForm.fqv, '');
        gsdlInitValue(queryForm.fqf, '');

        queryForm.submit();
        return false;
    }
	
    if (!gsdlGetCookieBool('qe', false))
        return false;
    gsdlSetCookie('qe', '0');
    updateClearLink();
    clearHighlight();

    var strURL = gsdl.url + cgiarg.l + '/q/';
    var strVars = 'qcount=1&q=&fqv=&fqu=&fqf=&fqc=&fqk=&fqs=&r=1&qe=0&qu=' + gsdlNewQueryUniqueId() + '&uq=' + date.getTime();
    var request = null;
    if (!IE4 && !NS4) request = gsdlGetHttpRequest();
    if (request == null) {
        gsdlGetElement('dataFrame').src = strURL + '?' + strVars;
    } else {
        request.open('POST', strURL, false);
        request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        request.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
        request.send(strVars);
    }
    return false;
}

function gsdlInitValue(field, value) {
    var i;
    if (typeof(field.type) != 'undefined') {
        if (field.type == 'select-one') {
            for (i = 0; i < field.options.length; ++i) {
                if (value == field.options[i].value) {
                    field.options[i].selected = true;
                    break;
                }
            }
        } else if (field.type == 'checkbox' || field.type == 'radio') {
            if (value == field.value)
                field.checked = true;
        } else { // 'text', 'textarea', 'password', 'hidden'
            field.value = value;
        }
    } else if (typeof(field.length) != 'undefined') {
        var values = null;
        if (typeof(value) == 'string')
            values = value.split('||');
        if (values == null || values.length == 1) {
            for (i = 0; i < field.length; ++i) {
                gsdlInitValue(field[i], value);
            }
        } else {
            for (i = 0; i < field.length; ++i) {
                for (var j = 0; j < values.length; ++j) {
                    gsdlInitValue(field[i], values[j]);
                }
            }
        }
    }
}

function gsdlInitRadioValue(field, value) {
    for(var i = 0; i < field.length; ++i) {
        field[i].checked = (field[i].value == value);
    }
}

function gsdlGetValue(field) {
    if (typeof(field.type) != 'undefined') {
        if (field.type == 'select-one') {
            if (field.selectedIndex < 0)
                return '';
            else
                return field.options[field.selectedIndex].value;
        } else if (field.type == 'checkbox' || field.type == 'radio'){
            return field.checked ? field.value : '';
        } else {
            return field.value;
        }
    } else if (typeof(field.length) != 'undefined') {
        var value = '', v;
        for (var i = 0; i < field.length; ++i) {
            v = gsdlGetValue(field[i]);
            if (v.length > 0 && value.length > 0)
                value += '||';
            value += v;
        }
        return value;
    }
    return null;
}

function close_detach() {
    close();
}

var loadedbtn = [];
function gbutton(img, onimage) {
    if (img && img.src && (img.out == null || typeof(img.out) == typeof(void(0)))) {
        var s = img.src;
        img.out = new Image();
        img.out.src = s;
        img.over = new Image();
        img.over.src = onimage;
        loadedbtn[img.name] = img;
    }
}

function roll(imagename, over) {
    if (document.images) {
        var img = loadedbtn[imagename];
        if (typeof(img) != 'undefined' && img != null) {
            if (over) img.src = img.over.src;
            else img.src = img.out.src;
        }
    }
}

function newImage(arg) {
    if (document.images) {
        rslt = new Image();
        rslt.src = arg;
        return rslt;
    }
    return null;
}

function changeImages() {
    if (document.images && (preloadFlag == true)) {
        for (var i = 0; i < changeImages.arguments.length; i += 2) {
            document[changeImages.arguments[i]].src = changeImages.arguments[i+1];
        }
    }
}

var preloadFlag = false;
function preloadImages() {
    if (document.images) {
        preloadFlag = true;
    }
}

function display_prefs() {
    var win;
    var wndWidth = 375;
    var wndHeight = 80;
    var wndX = (screen.width-wndWidth)/2;
    var wndY = (screen.height-wndHeight)/2;
    var strFeatures = 'location=no,menubar=no,scrollbars=yes,status=no,toolbar=no,width='+wndWidth+',height='+wndHeight+',resizable=yes';
    if (NS4 || NS6) strFeatures += ',screenX='+parseInt(wndX)+',screenY='+parseInt(wndY);
    else if (IE4plus) strFeatures += ',left='+parseInt(wndX)+',top='+parseInt(wndY);

    var strURL = gsdl.url + cgiarg.l + '/p/subjectprefs/';
    win = open(fix_url(strURL), Math.round(Math.random()*10000), strFeatures);
}

function display_docprefs() {
    var win;
    var wndWidth = 530;
    var wndHeight = 50;
    var wndX = (screen.width-wndWidth)/2;
    var wndY = (screen.height-wndHeight)/2;
    var strFeatures = 'location=no,menubar=no,scrollbars=yes,status=no,toolbar=no,width='+wndWidth+',height='+wndHeight+',resizable=yes';
    if (NS4 || NS6) strFeatures += ',screenX='+parseInt(wndX)+',screenY='+parseInt(wndY);
    else if (IE4plus) strFeatures += ',left='+parseInt(wndX)+',top='+parseInt(wndY);

    var strURL = gsdl.url + cgiarg.l + '/p/documentprefs/';
    win = open(fix_url(strURL), Math.round(Math.random()*10000), strFeatures);
}

function xInsDoc(parent, text, jn)
{
    var doc = insDoc(parent, gLnk('S', text, 'javascript:display_doc(\\\'' + jn + '\\\')'));
    doc.xID = jn;
}

function xInsFld(parent, text, jn)
{
    var fld = insFld(parent, gFld(text, 'javascript:display_doc(' + String.fromCharCode(34) + jn + String.fromCharCode(34) + ')'));
    fld.xID = jn;
    return fld;
}

function synchPage(linkID)
{
    if (foldersTree == 'undefined' || foldersTree == null)
    {
        window.setTimeout('synchPage("'+ linkID + '")', 400);
    }
    var folderObj;
    docObj = findObj(linkID);
    if (docObj != 'undefined')
    {
        docObj.forceOpeningOfAncestorFolders();

        if (typeof docObj.setState != 'undefined')
        { //is folder
            if (!docObj.isOpen)
                clickOnNodeObj(docObj);
        }
        highlightObjLink(docObj);

        //Scroll the tree window to show the selected node
        //Other code in these functions needs to be changed to work with
        //frameless pages, but this code should, I think, simply be removed
        if (typeof document.body != 'undefined') //scroll doesn work with NS4, for example
            document.body.scrollTop = docObj.navObj.offsetTop
    }
}

function createNamedElement(type, name) {
    var element = null;
    // Try the IE way; this fails on standards-compliant browsers
    try {
        element = document.createElement('<'+type+' name="'+name+'">');
    } catch (e) {
    }
    if (!element || element.nodeName != type.toUpperCase()) {
        // Non-IE browser; use canonical method to create named element
        element = document.createElement(type);
        element.name = name;
    }
    return element;
}

function setInnerText(elem, myText) {
    if(document.all){
        elem.innerText = myText;
    } else{
        elem.textContent = myText;
    }
}

function getInnerText(elem) {
    if(document.all){
        return elem.innerText;
    } else{
        return elem.textContent;
    }
}

function gsdlGetElement(strName, doc) {
    if (typeof(doc) == 'undefined' || doc == null)
        doc = document;
    var elem = null;
    if (doc.getElementById) {
        elem = doc.getElementById(strName);
    } else if (doc.all) {
        elem = doc.all[strName];
    } else {
        eval('elem = doc.' + strName);
    }
    return elem;
}

function gsdlGetArrayElement(strName, max) {
    var elem, a = [];
    if (typeof(max) == 'undefined' || max == null)
        max = 1000;
    for (var i = 1; i < max; ++i)
    {
        elem = gsdlGetElement(strName + i);
        if (elem == null)
            break;
        a.push(elem);
    }
    return a;
}

function gsdlGetElementsByTagName(tagName, element) {
    if (typeof(element) == 'undefined' || element == 'null')
        element = document;
    else if (typeof(element) == 'string')
        element = gsdlGetElement(element);
    if (typeof(element.getElementsByTagName) == 'undefined')
        return element.all.tags(tagName);
    else
        return element.getElementsByTagName(tagName);
}

function getElementsByClassName(oElm, strTagName, strClassName){
    var arrElements = null;
    if (strTagName == '*' && oElm.all)
        arrElements = oElm.all;
    else if (typeof(oElm.getElementsByTagName) == 'undefined')
        arrElements = oElm.all.tags(strTagName);
    else
        arrElements = oElm.getElementsByTagName(strTagName);
    var arrReturnElements = [];
    strClassName = strClassName.replace(/\-/g, "\\-");
    var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
    var oElement;
    for(var i = 0; i < arrElements.length; ++i) {
        oElement = arrElements[i];
        if (oRegExp.test(oElement.className)) {
            arrReturnElements.push(oElement);
        }
    }
    return (arrReturnElements)
}

function gsdlGetTop(element) {
    var vtop = 0;
    while (element != null) {
        vtop += element.offsetTop;
        element = element.offsetParent;
    }
    return vtop;
}

function gsdlGetLeft(element) {
    var vleft = 0;
    while (element != null) {
        vleft += element.offsetLeft;
        element = element.offsetParent;
    }
    return vleft;
}

function ChangeImageSource(strId, strSRC)
{
    var objImage = GetImageObject(strId);
    if (objImage != null)
        objImage.src = strSRC;
}

function GetImageObject (strId)
{
    var objImage = null;
    if (document.getElementById)
    {
        objImage = document.getElementById(strId);
    }
    else if (document.all)
    {
        objImage = document.all.item(strId);
    }
    else
    {
        objImage = document.images[strId];
        if (!objImage) objImage = eval('document.' + strId );
    }
    return objImage;
}

function GetObject(strId) {
    var objLayer = null;

    if (document.getElementById) {
        objLayer = document.getElementById(strId);
    } else if (document.all) {
        objLayer = document.all.item(strId);
    } else {
        objLayer = eval('document.' + strId );
    }
    return objLayer;
}

/* MoveObjectTo():
	moves the objLayer object to (nLeft,nTop) absolute coordinates ...
 */
function MoveObjectTo(objLayer, nLeft, nTop) {
    if (document.getElementById || document.all) {
        objLayer.style.left = nLeft + 'px';
        objLayer.style.top = nTop + 'px';
    } else {
        objLayer.left = nLeft;
        objLayer.top = nTop;
    }
}

/* GetObjectInfo():
	returns an array containing : 0-left, 1-top, 2-width, 3-height ...
 */
function GetObjectInfo(objLayer) {
    var arrInfo = new Array();
    var TempTop, TempHeight;
    if (document.getElementById || document.all) {
        arrInfo[0] = objLayer.offsetLeft;
        TempTop = objLayer.offsetTop;
        TempHeight = objLayer.offsetHeight;
        arrInfo[1] = TempTop + TempHeight;
        arrInfo[2] = objLayer.offsetWidth;
        arrInfo[3] = objLayer.offsetHeight;
    } else {
        arrInfo[0] = objLayer.pageX;
        arrInfo[1] = objLayer.pageY + 14;
    }
    return arrInfo;
}

function ShowObject(objLayer, bShow) {
    if (! objLayer) return false;
    var bVisible, bOldVisible;

    // get current state ...
    if (document.getElementById || document.all)
        bOldVisible = (objLayer.style.visibility == 'visible');
    else
        bOldVisible = (objLayer.visibility == 'show');

    // see if the object should be visible or hidden ...
    if (typeof(bShow) == 'undefined' || bShow == null) {
        bVisible = ! bOldVisible;
    } else {
        bVisible = bShow;
    }

    // set new state ...
    if (document.getElementById || document.all)
        objLayer.style.visibility = (bVisible ? 'visible' : 'hidden');
    else
        objLayer.visibility = (bVisible ? 'show' : 'hide');
    return bOldVisible;
}

function cancelEvent(e) {
    if(!e) e = window.event;
    if(!e) e = window.Event;
    if(e) {
        if (typeof(e.cancelBubble) != 'undefined')
            e.cancelBubble = true;
        if (typeof(e.returnValue) != 'undefined')
            e.returnValue = false;
        if (typeof(e.stopPropagation) != 'undefined' && e.stopPropagation)
            e.stopPropagation();
    }
    return false;
}

var nHideCountryAssociationsTimer = 0;
function DisplayCountryAssociations(nId) {
	cancelEvent();
	if (nHideCountryAssociationsTimer != 0)
		window.clearTimeout(nHideCountryAssociationsTimer);
	var objSpan, objLayer;
	var arrInfo = [];
	var isvisible = false;
	
	objSpan = GetObject(nId);
	objLayer = GetObject('ca_' + nId);

	if (objSpan && objLayer) {
		arrInfo = GetObjectInfo(objSpan);
		if (IE4)
			MoveObjectTo(objLayer, nId == 'mesh' ? arrInfo[0] : -2, nId == 'mesh' ? arrInfo[1] - 2: arrInfo[1] + 6);
		else if (IE5 && !IE55)
			MoveObjectTo(objLayer, nId == 'mesh' ? arrInfo[0] : -2, nId == 'mesh' ? arrInfo[1] - 2: arrInfo[1] + 19);
		else
			MoveObjectTo(objLayer, nId == 'mesh' ? arrInfo[0] : -2, nId == 'mesh' ? arrInfo[1] - 2: arrInfo[1] + 9);

		isvisible = !ShowObject(objLayer);
		if (isvisible) {
			g_aRegisteredLayerHide.Hide();
		}
	} else {
		alert ('Unknown object ' + nId + ' !');
	}
	if (isvisible) {
		g_aRegisteredLayerHide.Register(DisplayCountryAssociations, nId);
	} else {
		g_aRegisteredLayerHide.UnRegister(DisplayCountryAssociations, nId);
	}
}

function StartHideCountryAssociations(nId) {
    if (nHideCountryAssociationsTimer != 0)
        window.clearTimeout(nHideCountryAssociationsTimer);
    nHideCountryAssociationsTimer = window.setTimeout("HideCountryAssociations('" + nId + "')", 1000);
}

function HideCountryAssociations(nId) {
    if (nHideCountryAssociationsTimer != 0)
        window.clearTimeout(nHideCountryAssociationsTimer);
    nHideCountryAssociationsTimer = 0;
    g_aRegisteredLayerHide.Hide();
}

function CancelHideCountryAssociations(nId) {
    if (nHideCountryAssociationsTimer != 0)
        window.clearTimeout(nHideCountryAssociationsTimer);
}

function RegisteredLayersHide() {
    this.functions = new Array();
    this.parameters = new Array();
    this.Register = RegisteredLayersHide_Register;
    this.UnRegister = RegisteredLayersHide_UnRegister;
    this.Hide = RegisteredLayersHide_Hide;
}

function RegisteredLayersHide_Register(func, param) {
    this.functions.push(func);
    this.parameters.push(param);
}

function RegisteredLayersHide_UnRegister(func, param) {
    var i;
    for(i = 0; i < this.functions.length; ++i) {
        if (this.functions[i] == func && this.parameters[i] == param) {
            this.functions.splice(i, 1);
            this.parameters.splice(i, 1);
            break;
        }
    }
}

function RegisteredLayersHide_Hide() {
    while (this.functions.length) {
        this.functions[0](this.parameters[0]);
    }
}

var g_aRegisteredLayerHide = new RegisteredLayersHide();

function __coverErrorInit__() {
    var strImg = httpCollectionImage + '/blankcover\\.gif';
    var re = new RegExp('\\/', 'g');
    strImg = strImg.replace(re,'\\/');
    g_imgRegExp = new RegExp(strImg + '$', 'i');
}

var g_imgRegExp = 0;
function CoverError() {
    if (g_imgRegExp != 0 && this.src.search(g_imgRegExp) < 0)
        this.src = httpCollectionImage + '/blankcover.gif';
}

function onDocumentLoad() {
    var book = gsdlGetElement('gsdlbookcover');
    if (book != null) book.onError= CoverError;
    if (cgiarg.a == 'cl') {
        gsdlSetCookie('cl', cgiarg.cl);
        CheckToogleRows();
    } else if(cgiarg.a == 'd' || cgiarg.a == 'm') {
        gDocumentTOC = DocumentTree.create('docToc', false, true);
        if (gDocumentTOC != null) {
            gDocumentTOC.installHandlers();
        } else {
            DocumentTree.installDocumentHandlers();
        }
        if (IE55plus) {
            var obj = gsdlGetElement('courseBuilderAddBtn');
            if (obj != null)
                obj.style.display = '';
        }
        if (gsdlGetCookieBool('qe', false)/* && gsdlGetCookieBool('hl', false)*/) {
            loadHighlightData();
        }
    }
}

function closeDocument() {
    var strCL = gsdlGetCookie('cl', '');
    if (strCL.length == 0) {
        gsdl_goto(gsdl.url + cgiarg.l + '/');
    } else if (strCL == 'search') {
        gsdl_goto(gsdl.url + cgiarg.l + '/q/');
    } else {
        gsdl_goto(gsdl.url + cgiarg.l + '/cl/' + strCL + '/');
    }

}

function expand_warning(strOID) {
    if (strOID == null) strOID = cgiarg.d;
    if (confirm(texts.expand_warning)) {
        gsdl_goto_ex(location, gsdlCGI + '/' + cgiarg.l + '/d/' + strOID + '/gt,2,gc,1.html');
    }
}

function onClassifierInit() {
    gsdlSetCookie('cl', cgiarg.cl);
    var hash = location.hash;
    if (hash.length > 5 && hash.substr(0,3) == '#hl') {
        var OID = hash.substr(3);
        var tdElement = gsdlGetElement('td' + OID);
        if (typeof(tdElement) == 'undefined' || tdElement == null)
            return;
        var elementpar = getElementsByClassName(tdElement, 'a', 'clcloselink');

        for(var i = 0; i < elementpar.length; ++i) {
            elementpar[i].className = 'hlclopenlink1';
        }

        if (tdElement.scrollIntoView) {
            tdElement.scrollIntoView(true);
        }
    }
}

function PositionBox(nId) {
    var objSpan, objLayer;
    var arrInfo = new Array();
    var arrInfoLayer =  new Array();
    var isvisible = false;

    objSpan = GetObject(nId + 'Bookmark');
    objLayer = GetObject(nId + 'Box');

    if (objSpan && objLayer) {
        arrInfo = GetObjectInfo(objSpan);
        arrInfoLayer = GetObjectInfo(objLayer);
        if (IE4 || IE5)
            MoveObjectTo(objLayer, arrInfo[0] + 100, arrInfo[1] + 5);
        else
            MoveObjectTo(objLayer, arrInfo[0] - arrInfoLayer[2]/2, arrInfo[1] - 25);
        isvisible = !ShowObject(objLayer);
        if (isvisible) {
            g_aRegisteredLayerHide.Hide();
        }
    } else {
        alert ('Unknown object ' + nId + ' !');
    }
    if (IE55plus) {
        var modalFrame = GetObject('overLayer');
        modalFrame.style.top = objLayer.style.top;
        modalFrame.style.left = objLayer.style.left;
        modalFrame.style.width = arrInfoLayer[2];
        modalFrame.style.height = arrInfoLayer[3];
        modalFrame.style.zIndex = objLayer.style.zIndex + 1;
        modalFrame.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)';
        modalFrame.style.display = isvisible ? 'block' : 'none';
    }
    if (nId == 'description' && !IE55plus && IE4plus) {
        var problematicSelect = GetObject('orgselect');
        problematicSelect.style.display = isvisible ? 'none' : 'block';
    }
    if (isvisible) {
        g_aRegisteredLayerHide.Register(PositionBox, nId);
    }else {
        g_aRegisteredLayerHide.UnRegister(PositionBox, nId);
    }
}

function HideDescriptionBox(nId) {
    g_aRegisteredLayerHide.Hide();
}

function gsdlGetEventTrigger(e) {
    if (! e)
        e = event;
    return e.target || e.srcElement;
}

function checkClick(evt) {
    var obj = gsdlGetEventTrigger(evt);
    if (obj.id != 'ca_mesh' && obj.id != 'meshLink' && obj.id != 'descriptionLink' && obj.id != 'descriptionImage')
        HideDescriptionBox('ca_mesh');
}

function CheckToogleRows() {
    var name, elem, hide, i, j, tbl, result, vStyle;
    var defaults = new Array(true, true, true, false, false);
    var names = new Array('mst', 'msa', 'msp', 'reg', 'cou');
    for(i = 0 ; i< names.length; i++) {
        name = names[i];
        hide = !gsdlGetCookieBool(name, defaults[i]);
		
        tbl = gsdlGetElement('myTable');
        result = getElementsByClassName(tbl, 'tr', 'toggleRow' + name);
        vStyle = (hide)? 'none':'';
        for(j = 0; j < result.length; j++){
            result[j].style.display = vStyle;
        }
        elem = gsdlGetElement(name);
        if (elem != null)
            elem.innerHTML = texts[name + (hide ? '_show' : '_hide')];
    }
}

function ShowAllRows(show, tableId, tag) {
    var i = 0, elem, name;
    var names = new Array('mst', 'msa', 'msp', 'reg', 'cou');
	
    for(i=0 ; i< names.length; i++) {
        name = names[i];
        gsdlSetCookie(name, show ? 1 : 0);
        elem = gsdlGetElement(name);
        elem.innerHTML = texts[name + (show ? '_hide' : '_show')];
    }
	
    tbl = gsdlGetElement(tableId);
    var result = getElementsByClassName(tbl, 'tr', 'allRow');
    var vStyle = show ? '': 'none';
    for(i=0 ; i< result.length; i++){
        result[i].style.display = vStyle;
    }
}

function ToggleRows(name, tableId, tag){
    var hide = false;
    i = 0;
    hide = gsdlGetCookieBool(name, (name == 'reg' || name == 'cou') ? false : true);
    gsdlSetCookie(name, hide ? 0 : 1);
    tbl = gsdlGetElement(tableId);
    var result = getElementsByClassName(tbl, 'tr', 'toggleRow' + name);
    var vStyle = (hide)? 'none':'';
    for(i=0 ; i< result.length; i++){
        result[i].style.display = vStyle;
    }
    tag.innerHTML = texts[name + (hide ? '_show' : '_hide')];
}

function displayRow(){
    var row = document.getElementById('captionRow');
    if (row.style.display == '') row.style.display = 'none';
    else row.style.display = '';
}

function DisplayBlock(nId) {
    if (nHideCountryAssociationsTimer != 0)
        window.clearTimeout(nHideCountryAssociationsTimer);
    var objSpan, objLayer;
    var arrInfo;
    var isvisible = false;
	
    objSpan = GetObject(nId);
    objLayer = GetObject('ca_' + nId);

    if (objSpan && objLayer) {
        arrInfo = GetObjectInfo(objSpan);
        var arrInfo2 = GetObjectInfo(objLayer);
        //alert(objSpan.id + ' ' + arrInfo);
        if (IE55)
            MoveObjectTo(objLayer, arrInfo[1] + 203, arrInfo[1] - 98);
        else if (IE5)
            MoveObjectTo(objLayer, arrInfo[1] + 508, arrInfo[1] + 197);
        else if (IE4)
            MoveObjectTo(objLayer, arrInfo[1] + 495, arrInfo[1] + 162);
        else
            MoveObjectTo(objLayer, arrInfo[0] - arrInfo2[2] + 1, arrInfo[1] + 2);
        isvisible = !ShowObject(objLayer);
        if (isvisible) {
            g_aRegisteredLayerHide.Hide();
        }
    } else {
        alert ('Unknown object ' + nId + ' !');
    }
    if (isvisible) {
        g_aRegisteredLayerHide.Register(DisplayBlock, nId);
    } else {
        g_aRegisteredLayerHide.UnRegister(DisplayBlock, nId);
    }
}

function updateClearLink() {
    var clearFormBtn = gsdlGetElement('clearFormBtn');
    if (clearFormBtn == null) return;
    var bHasQuery = gsdlGetCookieBool('qe', false);
    clearFormBtn.className = 'clearmenu' + (bHasQuery ? '' : 'inactiv');
    clearFormBtn.disabled = !bHasQuery;
    clearFormBtn.src = httpCollectionImage + '/' + (cgiarg.l == 'en' ? '' : cgiarg.l) + '/clear' + (bHasQuery ? '' : 'inactiv') + '.gif';
}

function clearHighlight() {
    if (cgiarg.a != 'd') return;
    var documentContent = gsdlGetElement('documentContent');
    if (documentContent == null) return;
    var elements = getElementsByClassName(documentContent, 'span', 'hl');
    if (elements == null && elements.length == 0) return;
    for(var i = 0; i < elements.length; ++i) {
        elements[i].className = 'hlnone';
    }
}

function gsdlGetHttpRequest() {
    var obj = null;
    if (window.XMLHttpRequest) {
        obj = new XMLHttpRequest();
        if (obj.overrideMimeType)
            obj.overrideMimeType('text/xml');
    } else if (window.ActiveXObject) {
        try {
            obj = new ActiveXObject('Msxml2.XMLHTTP');
        } catch (e) {
            try {
                obj = new ActiveXObject('Microsoft.XMLHTTP');
            } catch (e) {
            }
        }
    }
    return obj;
}

function Ajax(url, options) {
    this.options = {
        object:       null,
        method:       'post',
        asynchronous: true,
        contentType:  'application/x-www-form-urlencoded',
        encoding:     'UTF-8',
        parameters:   '',
        evalJSON:     true,
        headers:      null,
        onException:  null,
        onComplete:   null,
        onSuccess:    null,
        onFailure:    null
    };
    for (var name in options) {
        this.options[name] = options[name];
    }
    this.url = url;
    this.transport = gsdlGetHttpRequest();

    this.execute();
}

Ajax.prototype.dispatchException = function(e) {
    if (this.options.onException != null) {
        if (this.options.object != null)
            this.options.object[this.options.onException](this, e);
        else
            this.options.onException(this, e);
    } else {
        alert(e.toString());
    }
}

Ajax.prototype.success = function() {
    var status = this.getStatus();
    return !status || (status >= 200 && status < 300);
}

Ajax.prototype.getStatus = function() {
    try {
        return this.transport.status || 0;
    } catch (e) {
        return 0
    }
}

Ajax.prototype.getHeader = function(name, defaultValue) {
    try {
        return this.transport.getResponseHeader(name) || defaultValue;
    } catch (e) {
        return defaultValue;
    }
}

Ajax.prototype.responseIsJSON = function() {
    var status = this.getStatus();
    return !status || (status >= 200 && status < 300);
}

Ajax.prototype.execute = function() {
    try {
        this.transport.open(this.options.method, this.url, true);
        this.transport.setRequestHeader('Content-Type', this.options.contentType +
            (this.options.encoding && this.options.encoding.length > 0 ? '; charset=' + this.options.encoding : ''));
        this.transport.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
        if (this.options.headers != null) {
            for (var name in this.options.headers) {
                this.transport.setRequestHeader(name, this.options.headers[name]);
            }
        }
    } catch (e) {
        this.dispatchException(e);
    }
    var thisObject = this;
    this.transport.onreadystatechange = function() {
        if (thisObject.transport.readyState == 4) {
            try {
                var data = null;
                if (thisObject.success()) {
                    var contentType = thisObject.getHeader('Content-type', 'text/plain').toLowerCase();
                    if (contentType.indexOf('application/json') == 0) {
                        eval('data = ' + thisObject.transport.responseText);
                    } else if (contentType.match(/^\s*(text|application)\/(x-)?(java|ecma)script(;.*)?\s*$/i)) {
                        eval(thisObject.transport.responseText);
                    } else if (contentType.indexOf('text/xml') == 0) {
                        data = thisObject.transport.responseXML;
                    } else {
                        data = thisObject.transport.responseText;
                    }
                }
                if (thisObject.options.onComplete != null) {
                    if (thisObject.options.object != null)
                        thisObject.options.object[thisObject.options.onComplete](thisObject, data);
                    else
                        thisObject.options.onComplete(thisObject, data);
                }
                if (thisObject.success()) {
                    if (thisObject.options.onSuccess != null) {
                        if (thisObject.options.object != null)
                            thisObject.options.object[thisObject.options.onSuccess](thisObject, data);
                        else
                            thisObject.options.onSuccess(thisObject, data);
                    }
                } else {
                    if (thisObject.options.onFailure != null) {
                        if (thisObject.options.object != null)
                            thisObject.options.object[thisObject.options.onFailure](thisObject);
                        else
                            thisObject.options.onFailure(thisObject);
                    }
                }
            } catch (e) {
                thisObject.dispatchException(e);
            }
        }
    }
    this.transport.send(this.options.parameters.length > 0 ? this.options.parameters : null);
}

function globalPageInit() {
    if (gsdlCGI.length > 0 && gsdlCGI.substr(0, 1) != '/')
        gsdlCGI = '/' + gsdlCGI;
    gsdl.url = gsdlCGI + '/';

    updateClearLink();
    var pageCLMD = getPageCLMD();
    var cookieCLMD = gsdlGetCookieInt('clmd', gsdl.defaults.args.clmd);
    if (cgiarg.a == 'cl') {
        if (cookieCLMD != pageCLMD) {
            var r = /\/clmd,[0-9]+(,clr,[0-9]+)?(,cldc,[0-9]+)?/;
            var url = window.location.href;
            if (r.test(window.location.href)) {
                url = url.replace(r, '/clmd,' + cookieCLMD);
            } else {
                var args = '', pos;
                if ((pos = url.indexOf('?')) > -1) {
                    args = url.substr(pos);
                    url = url.substr(0, pos);
                }
                url += 'clmd,' + cookieCLMD + '.html';
            }
            window.location.href = url;
            return;
        }
    } else if (cookieCLMD != pageCLMD) {
        gsdlUpdateLinksForCLMD();
    }
    __coverErrorInit__();
    if (typeof(initQuickSearch) == 'function')
        initQuickSearch();
    if (typeof(g_gsdlPreferenceState) != 'undefined' && g_gsdlPreferenceState != null)
        g_gsdlPreferenceState.Initialize();
    if (cgiarg.a == 'p' && cgiarg.p == 'about') {
        gsdlSetCookie('cl', '');
        onLoadPageAbout();
    } else if (cgiarg.a == 'd' || cgiarg.a == 'm') {
        onDocumentLoad();
    } else if (cgiarg.a == 'cl') {
        onDocumentLoad();
        onClassifierInit();
    } else if (cgiarg.a == 'q') {
        gsdlSetCookie('cl', 'search');
        query_initialize();
    }
    if (gsdl.onPageLoad != null) gsdl.onPageLoad();
    gsdlBindPageEvents();
}

function gsdlBindPageEvents() {
    document.onclick = checkClick;
    var obj = gsdlGetElement('descriptionLink');
    if (obj != null) obj.onclick = function(e) {
        DisplayCountryAssociations('description');
        return cancelEvent(e);
    }
    obj = gsdlGetElement('meshLink');
    if (obj != null) {
        if (cgiarg.a == 'd' || cgiarg.a == 'm')
            obj.onclick = function(e) {
                DisplayCountryAssociations('mesh');
                return cancelEvent(e);
            }
        else
            obj.onclick = function(e) {
                DisplayBlock('mesh');
                return cancelEvent(e);
            }
    }
}

function getPageCLMD() {
    var pageCLMD = gsdl.defaults.args.clmd;
    var r = /\/clmd,([0-9]+)/;
    var a = r.exec(window.location.href);
    if (a != null && a.length > 1) {
        pageCLMD = parseInt(a[1], 10);
    }
    return pageCLMD;
}

function getLocalizedImagesURL() {
    if (cgiarg.l == 'en')
        return httpCollectionImage;
    return httpCollectionImage + '/' + cgiarg.l;
}

function gsdlGetQueryUniqueId() {
    return gsdlGetCookieInt('qu', 0);
}

function gsdlNewQueryUniqueId() {
    var queryUniqueId = 1 + gsdlGetCookieInt('qu', 0);
    if (queryUniqueId == 2147483646) queryUniqueId = 1;
    gsdlSetCookie('qu', queryUniqueId);
    return queryUniqueId;
}

var g_hCookies = {
    'init': false
};

function gsdlGetCookie(name, defaultValue) {
    if (!g_hCookies.init)
        gsdlParseCookies();
    var value = g_hCookies['__' + name];
    if (typeof(value) == 'undefined') {
        if (typeof(defaultValue) == 'undefined' || defaultValue == null)
            return null;
        return '' + defaultValue;
    } else {
        return value;
    }
}

function gsdlGetCookieInt(name, defaultValue) {
    if (!g_hCookies.init)
        gsdlParseCookies();
    var value = g_hCookies['__' + name];
    if (typeof(value) == 'undefined') {
        if (typeof(defaultValue) == 'undefined' || defaultValue == null)
            return null;
        if (typeof(defaultValue) == 'number')
            return defaultValue;
        if (typeof(defaultValue) == 'boolean')
            return defaultValue ? 1 : 0;
        return parseInt('' + defaultValue, 10);
    } else {
        return parseInt(value, 10);
    }
}

function gsdlGetCookieBool(name, defaultValue) {
    if (!g_hCookies.init)
        gsdlParseCookies();
    var value = g_hCookies['__' + name];
    if (typeof(value) == 'undefined' || value == null) {
        if (typeof(defaultValue) == 'undefined' || defaultValue == null)
            return null;
        if (typeof(defaultValue) == 'number')
            return defaultValue != 0;
        if (typeof(defaultValue) == 'boolean')
            return defaultValue;
        defaultValue = '' + defaultValue;
        return (defaultValue == 'yes' || defaultValue == '1' || defaultValue == 'true');
    } else {
        return (value == 'yes' || value == '1' || value == 'true');
    }
}

function gsdlSetCookie(name, value) {
    if (!g_hCookies.init)
        gsdlParseCookies();
    if (value == null) {
        g_hCookies['__' + name] = value;
    } else {
        if (typeof(value) == 'boolean')
            value = value ? '1' : '0';
        else
            value = '' + value;
        g_hCookies['__' + name] = value;
    }
    gsdlBuildCookies();
}

//GSDL-ARGS=bo|0/pr|6/sid|XQAWEJ3I2130706433X00000664X4804A896
function gsdlParseCookies() {
    g_hCookies.init = true;
    if (document.cookie == null || document.cookie.length == 0)
        return;
    var i, aCookies, gsdlArgs = null, name, value, nPos;
    aCookies = document.cookie.split(';');
    for(i = 0; i < aCookies.length; ++i) {
        aCookies[i] = aCookies[i].trim();
        if (aCookies[i].indexOf('GSDL-ARGS=') == 0) {
            gsdlArgs = aCookies[i].substr(10).trim();
            break;
        }
    }
    if (gsdlArgs == null || gsdlArgs.length == 0)
        return;
    aCookies = gsdlArgs.split('/');
    for(i = 0; i < aCookies.length; ++i) {
        aCookies[i] = aCookies[i].trim();
        nPos = aCookies[i].indexOf('|');
        if (nPos > -1) {
            name  = unescape(aCookies[i].substr(0, nPos)).trim();
            value = unescape(aCookies[i].substr(nPos + 1)).trim();
            g_hCookies['__' + name] = value;
        }
    }
}

function gsdlBuildCookies() {
    if (!g_hCookies.init)
        return;
    var i, aCookies, gsdlArgs = '', strArg, strCookie = '', value;
    for (strArg in g_hCookies) {
        if (strArg.length > 2 && strArg.substr(0, 2) == '__') {
            value = g_hCookies[strArg];
            if (value != null && value.length > 0) {
                if (gsdlArgs.length > 0) gsdlArgs += '/';
                gsdlArgs += escape(strArg.substr(2)) + '|' + escape(value);
            }
        }
    }
    strCookie += 'GSDL-ARGS=';
    if (gsdlArgs.length > 0) {
        strCookie += gsdlArgs;
    } else {
        strCookie += 'deleted';
    }
    strCookie += ';path=';
    if (gsdlCGI.length == 0) {
        strCookie += '/';
    } else {
        strCookie += gsdlCGI;
    }
    if (gsdlArgs.length > 0) {
        strCookie += ';expires=Fri, 31-Dec-2099 23:59:59 GMT';
    } else {
        strCookie += ';expires=Thu, 21-Dec-1978 10:01:02 GMT';
    }
    document.cookie = strCookie;
}

function gsdlUpdateLinksForCLMD(value) {
    if (typeof(value) == 'undefined' || value == null)
        value = gsdlGetCookieInt('clmd', gsdl.defaults.args.clmd);
    var re = new RegExp('x');
    re.compile('\\/clmd,[0-9]+(,clr,[0-9]+)?(,cldc,[0-9]+)?');
    var np = '/clmd,' + value;
    for (var i = 0; i < document.links.length; ++i) {
        document.links[i].href = document.links[i].href.replace(re, np);
    }
}

////////////////////////////////////////////////////////////////////////////////
// For about page
////////////////////////////////////////////////////////////////////////////////
var gBookCoverTimeout;
var coverlinkindex = -1;
function onLoadPageAbout() {
    var book = getBookElement();
    if (book != null) book.onError= CoverError;
    set_book();
}

var gBookCoverImage=null;
function setBookCoverImage(oImg) {
    if (!gBookCoverImage) {
        gBookCoverImage=oImg;
    }
}

function GoToBookCover() {
    gsdl_goto(thislink);
}

function getBookElement() {
    var elem = null;
    if (document.getElementById) {
        elem = document.getElementById('book');
    } else if (document.all) {
        elem = document.all['book'];
    } else {
        elem = document.images['book'];
        if (!elem) elem = document.book;
    }
    return elem;
}

var thislink = '';
function set_book() {
    if (typeof(books) == 'undefined' || books.length < 1) return;
    if (!gBookCoverImage) {
        gBookCoverImage = getBookElement();
        if (!gBookCoverImage) {
            return;
        }
    }
    var date = new Date();
    var t = ((date.getTime() % 9301) + (Math.round(Math.random() * 49297))) % books.length;
    if (t >= books.length) t = books.length - 1;
    var thisbook = httpCollectionAssocImage + '/' + hrefs[t] + '/cover.jpg';
    thislink  = httpCollectionAssocImage + '/' + hrefs[t] + '/' + hrefs[t] + '.pdf';

    var oBookLinkElem = null;
    if (document.getElementById) {
        oBookLinkElem = document.getElementById('coverlink');
    } else if (document.all) {
        oBookLinkElem = document.all['coverlink'];
    } else {
        if (coverlinkindex != -1)
            oBookLinkElem = document.links[coverlinkindex];
    }
    if (!oBookLinkElem) {
    // we failed to find the object
    } else if (oBookLinkElem.href) {
        gBookCoverImage.src = thisbook;
        oBookLinkElem.href = fix_url2(thislink);
        window.clearTimeout(gBookCoverTimeout);
        gBookCoverTimeout = window.setTimeout(set_book, 5000);
    }
}

function gsdlGetBody() {
    // Sense the difference between Strict and Quirks mode
    return (document.compatMode != 'BackCompat'? document.documentElement : document.body);
}

function FloatTopDiv(id) {
    this.marginX = 5;
    this.marginY = (cgiarg.l == 'es' ? '585' : '560');
    this.sleep = false;
    this.fblObj = gsdlGetElement(id);
    if (this.fblObj != null) {
        this.fblObj.sP = function(x, y) {
            this.style.left = x + 'px';
            this.style.top= y + 'px';
        };
        this.fblObj.x = this.marginX;
        this.fblObj.y = this.marginY;
        if (IE4 || IE5 || IE6) {
            if (!FloatTopDiv.WatchDogInstalled) {
                FloatTopDiv.WatchDogInstalled = true;
                if (IE6)
                    gsdlGetBody().onscroll = FloatTopDiv.watchDog;
                else {
                    document.body.onscroll = FloatTopDiv.watchDog;
                    window.onscroll = FloatTopDiv.watchDog;
                }
            }
        } else {
            this.fblObj.style.position = 'fixed';
        }
        this.fblObj.style.display = 'none';
    }
}

FloatTopDiv.WatchDogInstalled = false;
FloatTopDiv.WatchList = [];

FloatTopDiv.watchDog = function() {
    if (FloatTopDiv.WatchList.length > 0) {
        for(var i = 0; i < FloatTopDiv.WatchList.length; ++i) {
            FloatTopDiv.WatchList[i].onScroll();
        }
    }
};

FloatTopDiv.prototype.onScroll = function() {
    if (this.sleep || this.fblObj == null)
        return;
    //var pY = document.body.scrollTop;
    if (IE6) {
        this.fblObj.y = gsdlGetBody().scrollTop + this.marginY;
        this.fblObj.sP(this.fblObj.x, this.fblObj.y);
    }
    else {
        this.fblObj.y = document.body.scrollTop + this.marginY;
        this.fblObj.sP(this.fblObj.x, this.fblObj.y);
    }
};

FloatTopDiv.prototype.start = function() {
    this.sleep = false;
    if (this.fblObj != null) {
        if (FloatTopDiv.WatchList.indexOf(this) == -1)
            FloatTopDiv.WatchList.push(this);
        this.onScroll();
        this.fblObj.style.display = 'block';
    }
	//document.body.style.cursor = 'wait';
};

FloatTopDiv.prototype.stop = function() {
    this.sleep = true;
    if (this.fblObj != null) {
        FloatTopDiv.WatchList.remove(this);
        this.fblObj.style.display = 'none';
    }
	//document.body.style.cursor = 'default';
};

window.onload = globalPageInit;
