/**
 *
 *
 *
 *
 */

var requestEmail    = "IUCN Library <library@iucn.org>";
var recordsPerPage	= "50";
var reportForm		= "WebPanier";
var displayForm		= "WebAff";
var urlRecherche	= "/dbtw-wpd/commande/";
var tbname			= "iucn";
var cookiePanier	= "panier";
var cookieQte		= "quantite";
var domain			= null;
var ids				= new Array;
var qtes			= new Array;


//set expiration date 7 days ahead
var expiration = new Date();
expiration.setTime(expiration.getTime() + 604800000);


init();





/*
 * Initialisation des variables globales.
 */
function init() {
	var str = getCookie(cookiePanier);
	if(str) {
		 ids = str.split('/');
	}
	str = getCookie(cookieQte);
	if(str) {
		 qtes = str.split('/');
	}
}


      
function getCookie(name){
	var cname = name + "=";
	var dc = document.cookie;
	if (dc.length > 0) {
		begin = dc.indexOf(cname);
		if (begin != -1) {
			begin += cname.length;
			end = dc.indexOf(";", begin);
			if (end == -1) {
				end = dc.length;
			}
			return unescape(dc.substring(begin, end));
		}
	}
	return null;
}



function setCookie(name, value, expires, path, domain, secure) {
	document.cookie = name + "=" + escape(value) + 
		((expires == null) ? "" : "; expires=" + expires.toGMTString()) +
		((path == null) ? "" : "; path=" + path) +
		((domain == null) ? "" : "; domain=" + domain) +
		((secure == null) ? "" : "; secure");
}



function delCookie (name, path, domain) {
	if (getCookie(name)) {
	document.cookie = name + "=" +
		((path == null) ? "" : "; path=" + path) +
		((domain == null) ? "" : "; domain=" + domain) +
		"; expires=Thu, 01-Jan-70 00:00:01 GMT";
	}
}


/*
 * Synchronise les qtes du panier avec les boîtes de texte de 
 * la page Panier. Ces boîtes sont des <input type="text" name="qte1">
 */
function panierQteSynchro() {
	var f;
	var nom;
	
	f = document.forms["commande"];
	for (var i = 0; i < 500; i++) {
		nom = "qte"+(i+1);
		f[nom].value = qtes[i];
	}
	
	
}



/*
 * Ajoute l'ID d'un titre au pannier.
 */
function panierAjoute(id) {

	/*
	 * On contrôle que l'id ne se trouve pas déjà dans ids.
	 */
	for (var i = 0; i < ids.length; i++) {
		if (ids[i] == id) {
			alert("You have already selected this title.");
			return;
		}
	}
    alert("Item added");

	ids[ids.length] = id;
	qtes[qtes.length] = 1;
	
	cookieMaj();

	// MAJ du compteur du panier s'il y en a un sur la page
	if(ids.length > 0) {
		document.etatPanier.nbIds.value = ids.length;
	}
}



/*
 * On supprime un titre du panier.
 */
function panierSuppr(id) {
	var tmp_ids = new Array;
	var tmp_qtes = new Array;
	for (var i = 0; i < ids.length; i++) {
		if (ids[i] != id) {
			tmp_ids[tmp_ids.length] = ids[i];
			tmp_qtes[tmp_qtes.length] = qtes[i];
		}
	}
	ids = tmp_ids;
	qtes = tmp_qtes;
	cookieMaj();
	if (ids.length == 0) {
		// Dernier titre du panier, on revient à la recherche
		window.location.href = urlRecherche;
	} else {
		getRecords();
	}
}



function cookieMaj() {
	// Place les ids reliés par / dans une chaîne
	var str = ids.join('/');
	setCookie(cookiePanier, str, expiration, "/", null, null);
	str = qtes.join('/');
	setCookie(cookieQte, str, expiration, "/", null, null);
}



/*
 * Remise à zéro du panier.
 */
function panierRaz() {
	ids = new Array;
	cookieMaj();
	document.etatPanier.nbIds.value = 0;
}



/*
 * Affiche les info de téléchargement d'un titre
 */
function downloadDisplay(id, orderNumber, pdfFile, pdfSize, htmlFile, price) {

    var html = "";
    html = 
        "<br><br><div id=\"MidMenu\">" +
        "<ul>";
    
    if (price == ' ' && pdfFile == ' ' && htmlFile == ' ') {

        html +=
            '<li>' +
            '<a href="mailto:' +
            requestEmail +
            '?subject=Request on availability of publication #' +
            id +
            '">Request</a><br />' +
            '<span class="MidDetail">' +
            'Request information on availability of this document' + 
            '</span>' +
            '</li>'; 

    } else {
        
        // 1er bloc
        html += "<li>";
        if (price == ' ') {
            html += '&nbsp;';
        } else {
            html +=
				"<img src=\"basket.gif\">" +
                "<a href=\"" +
				"http://www.earthprint.com/productfocus.php?id=IUCN" +
                orderNumber +
                "\">" +
                "<br>Order from Earthprint</a>";
        }
        html += "</li>";
        
        // 2ème bloc
        html += "<li>";
        if (pdfFile == ' ') {
            html += '&nbsp;';
        } else {
            html +=
                '<a target="_blank" href="downpdf.aspx?id=' + id + '&url=' + pdfFile + '"><img src="downpdf.gif"></a><br />' +
                '<span class="MidDetail">Download PDF File<br>(' +
                pdfSize + 
                ')</span>';
        }
        html +="</li>";
    
        // 3ème bloc
        html += "<li>";
        if (htmlFile == ' ') {
            html += '&nbsp;';
        } else {
            html +=
                '<a target="_blank" href="' +
                htmlFile +
                '">View HTML</a><br />';
        }
        html += "</li>";
    }
    
    html += "</ul></div>";
    
    document.writeln(html);
}




/**
 *  pageType
 *      0   Page de recherche
 *      1   Page de résultat
 *      2   Page d'affichage
 *     
 */
function navigDisplay(pageType, recordNumber, recordCount) {

    var html = 
        '<div id="ResultNavig">' +
        '<p>';
    if (pageType > 0) { 
        var htmlFirst = (pageType == 1 ? nextprev_First(): nextprevRecord_First());
        var htmlPrevious = (pageType == 1 ? nextprev_Previous(recordCount): nextprevRecord_Previous(recordCount));
        var htmlNext = (pageType == 1 ? nextprev_Next(recordCount): nextprevRecord_Next(recordCount));
        var htmlLast = (pageType == 1 ? nextprev_Last(recordCount): nextprevRecord_Last(recordCount));
        html = html +
            'Result: ' +
            recordNumber +
            ' / ' +
            recordCount +
            ' -- ' + 
            '<a href="/dbtw-wpd/commande/">New search</a> | ' +
            htmlFirst +
            ' | ' + 
            htmlPrevious +
            ' | ' + 
            htmlNext +
            ' | ' +
            htmlLast +
            '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
    }
    html = html +
        '</p>' +
        '</div>';
    //alert(html);
    document.writeln(html);
    document.etatPanier.nbIds.value = ids.length;

}


/*
 * Lance une requête pour retrouver les enregistrements
 * placés dans le pannier.
 */
function getRecords(){
    var url =
        "/dbtw-wpd/exec/dbtwpub.dll" +
        '?TN=' + tbname +
        '&QY=RID%3D' + ids.join('/') +
        "&RF=WebPanier&DF=WebPanier&MR=100&NP=255&RL=0&DL=0" +
        "&XC=/dbtw-wpd/exec/dbtwpub.dll&ID=&AC=QBE_QUERY";
    //alert(url);
    window.location.href = url;
}





/*
GLOBAL VARIABLES
*/

// global page url
var currentUrl = window.location.href;

if (currentUrl.indexOf("?") != -1)
{
	currentUrl = currentUrl.substr(0, currentUrl.indexOf("?")); //snip href minus query string
}

// global link text values
var npFirstText = "First";
var npPreviousText = "Previous";
var npNextText = "Next";
var npLastText = "Last";

//global show MR count in link text
var npShowMR = true;

//global css class names
var npLinkCss = "nextprev_link";
var npTextCss = "nextprev_text";


/*
Rewind() determines where to relocate the page.
If in multi-record mode then back to BU.
If in single-record mode, then back to multi-record block.
*/
function Rewind(mode)
{
	if (mode == "fullrecord")
	{
		back_to_block();		
	}
	else if (mode == "remember")
	{
		//alert("remember mode");
		var rewindUrl = FindBU();
		if (rewindUrl != null)
		{		
			if (rewindUrl.indexOf("?") != -1)	
			{
				rewindUrl = rewindUrl.substr(0, rewindUrl.indexOf("?")); //snip query string from end	
			}
			window.location.href = rewindUrl + "?remember=true";
		}
		else
		{
			alert("Base URL cannot be found");
		}
	}
	else if (mode == null)
	{
		//alert("forget mode");
		var rewindUrl = FindBU();
		if (rewindUrl != null)
		{		
			if (rewindUrl.indexOf("?") != -1)	
			{
				rewindUrl = rewindUrl.substr(0, rewindUrl.indexOf("?")); //snip query string from end	
			}
			window.location.href = rewindUrl;
		}
		else
		{
			alert("Base URL cannot be found");
		}
	}
}

/*
FindBU() is a helper function which parses dbtw_params for the BU name/value pair, 
stripping out the resulting URL.
*/

function FindBU()
{
	var params = window.dbtw_params;
	params = unescape(params);
	var buMatch = params.match(/BU=(.*?)\x26/);
	var baseUrl = buMatch[0];
	if (baseUrl != null)
	{
		baseUrl = baseUrl.substr(3, baseUrl.length); //remove BU=
		if (baseUrl.indexOf("&") == (baseUrl.length-1))
		{
			baseUrl = baseUrl.substr(0, baseUrl.length-1); //snip '&' char from end
			
		}	
	}
	return baseUrl;
}

/*
Next/previous BLOCK section 
Use in reports where multiple records shown at a time
*/

function nextprev_First()
{
	var params = window.dbtw_params;
	var first_write = npFirstText;
	var first_link = "";
	var first_params = "";
	
	// find the record number
	var rns = params.match(/RN=(\d+)/);
	var rn = parseInt(rns[1]);

	// MR is records at a time
	var mrs = params.match(/MR=(\d+)/);
	var mr = parseInt(mrs[1]);
	
	// determine whether a link should be made
	if (rn == 0)
	{
		first_link += "<span class='" + npTextCss + "'>"+first_write;
		first_link += "</span>";
	}
	else
	{
		var first_params = params.replace((/RN=(\d+)/), "RN=" + mr);
		first_link += "<a href='" + currentUrl;
		first_link +=  "?AC=PREV_BLOCK" + first_params;
		first_link += "' class='" + npLinkCss + "'>"; 
		first_link += first_write;
		first_link += "</a>";
	}
	return first_link;

}

function nextprev_Previous()
{
	var params = window.dbtw_params;
	var prev_write = npPreviousText;
	var prev_link = "";		

	// find the record number
	var rns = params.match(/RN=(\d+)/);
	var rn = parseInt(rns[1]);

	// MR is records at a time
	var mrs = params.match(/MR=(\d+)/);
	var mr = parseInt(mrs[1]);
	
	//comparison number for prev block
	var prev_total = (rn - mr);
	
	// determine if a link should be made
	if (prev_total >= 0)
	{
		prev_link += "<a href='" +  currentUrl;
		prev_link +=  "?AC=PREV_BLOCK" + params;
		prev_link += "' class='" + npLinkCss + "'>";
		prev_link += prev_write;
		if (npShowMR == true) {prev_link += " " + mr;}
		prev_link += "</a>";
	}
	else
	{
		prev_link += "<span class='" + npTextCss + "'>"+prev_write;
		if (npShowMR == true) {prev_link += " " + mr;}
		prev_link += "</span>";
	}

	return prev_link;

} //end fxn

function nextprev_Next(record_count)
{
	var params = window.dbtw_params;
	var next_write = npNextText;
	var next_link = "";
	var rc = parseInt(record_count);		

	// find the record number
	var rns = params.match(/RN=(\d+)/);
	var rn = parseInt(rns[1]);

	// MR is records at a time
	var mrs = params.match(/MR=(\d+)/);
	var mr = parseInt(mrs[1]);
	
	//comparison number for next block
	var next_total = (rc - mr - rn);

	// determine if a link should be made
	if (next_total > 0)
	{
		next_link += "<a href='" + currentUrl;
		next_link +=  "?AC=NEXT_BLOCK" + params;
		next_link += "' class='" + npLinkCss + "'>";
		next_link += next_write;
		if (npShowMR == true) {next_link += " " + mr;}
		next_link += "</a>";	
	}
	else
	{
		next_link += "<span class='" + npTextCss + "'>"+next_write;
		if (npShowMR == true) {next_link += " " + mr;}
		next_link += "</span>";	
	}
	
	return next_link;

} //end fxn

function nextprev_Last(record_count)
{
	var params = window.dbtw_params;
	var last_write = npLastText;
	var last_link = "";
	var last_params = "";
	var rc = parseInt(record_count);

	// find the record number
	var rns = params.match(/RN=(\d+)/);
	var rn = parseInt(rns[1]);

	// MR is records at a time
	var mrs = params.match(/MR=(\d+)/);
	var mr = parseInt(mrs[1]);
	
	//comparison number for next block
	var last_total = (rc - mr - rn);
		
	// determine if a link should be made
	if (last_total <= 0)
	{
		last_link = "<span class='" + npTextCss + "'>"+last_write;
		last_link += "</span>";
	}
	else
	{
		var last_RN = (Math.floor((rc / mr)) - 1) * mr;
		var last_params = params.replace((/RN=(\d+)/), "RN=" + last_RN);
		
		last_link += "<a href='" + currentUrl;
		last_link +=  "?AC=NEXT_BLOCK" + last_params;
		last_link += "' class='" + npLinkCss + "'>";
		last_link += last_write;
		last_link +="</a>";
	}
	
	return last_link;
}



/*
 * Next/previous RECORD section
 * Use in full display where one record shown at a time
 */
function nextprevRecord_First()
{
	var params = window.dbtw_params;
	var first_write = npFirstText;
	var first_link = "";

	// find the record number
	var rns = params.match(/RN=(\d+)/);
	var rn = parseInt(rns[1]);

	
	// determine if a link should be made
	if (rn > 0)
	{
		var first_params = params.replace((/RN=(\d+)/), "RN=1");
		first_link += "<a href='" + currentUrl;
		first_link +=  "?AC=PREV_RECORD" + first_params;
		first_link += "' class='" + npLinkCss + "'>";
		first_link += first_write + "</a>";
	}
	else
	{
		first_link = "<span class='" + npTextCss + "'>"+first_write+"</span>";	
	}

	return first_link;

} 


function nextprevRecord_Previous()
{
	var params = window.dbtw_params;
	var prev_write = npPreviousText;
	var prev_link = "";

	// find the record number
	var rns = params.match(/RN=(\d+)/);
	var rn = parseInt(rns[1]);

	// determine if a link should be made
	if (rn > 0)
	{
		prev_link += "<a href='" +  currentUrl;
		prev_link +=  "?AC=PREV_RECORD" + params;
		prev_link += "' class='" + npLinkCss + "'>";
		prev_link += prev_write + "</a>";
	}
	else
	{
		prev_link = "<span class='" + npTextCss + "'>"+prev_write+"</span>";	
	}

	return prev_link;

}


function nextprevRecord_Next(record_count)
{
	var params = window.dbtw_params;
	var next_write = npNextText;
	var next_link = "";
	var rc = parseInt(record_count);

	// find the record number
	var rns = params.match(/RN=(\d+)/);
	var rn = parseInt(rns[1]);
	
	// determine if a link should be made
	if (rn+1 < rc)
	{
		next_link += "<a href='" + currentUrl;
		next_link +=  "?AC=NEXT_RECORD" + params;
		next_link += "' class='" + npLinkCss + "'>";
		next_link += next_write + "</a>";
	}
	else
	{
		next_link = "<span class='" + npTextCss + "'>"+next_write+"</span>";	
	}

	return next_link;

} 


function nextprevRecord_Last(record_count)
{
	var params = window.dbtw_params;
	var last_write = npLastText;
	var last_link = "";
	var rc = parseInt(record_count);

	// find the record number
	var rns = params.match(/RN=(\d+)/);
	var rn = parseInt(rns[1]);
	
	// determine if a link should be made
	if (rn+1 < rc)
	{
		var last_params = params.replace((/RN=(\d+)/), "RN=" + (rc-2));
		last_link += "<a href='" + currentUrl;
		last_link +=  "?AC=NEXT_RECORD" + last_params;
		last_link += "' class='" + npLinkCss + "'>";
		last_link += last_write + "</a>";
	}
	else
	{
		last_link = "<span class='" + npTextCss + "'>"+last_write+"</span>";	
	}

	return last_link;

} 



/*
 This back_to_block method written by Terry McBride tttmcbride@yahoo.com
 This method takes you from a display of an expanded record back to  the list 
 from the position that the current expanded record would be in.
*/

function back_to_block() 
{
	var params = window.dbtw_params;

	// find the record number
	var rns = params.match(/RN=(\d+)/);
	var rn = parseInt(rns[1]);

	// MR is records at a time
	var mrs = params.match(/MR=(\d+)/);
	var mr = parseInt(mrs[1]);

	// find the lower multiple of mr and add another mr to it to fool PREV_BLOCK
	var remainder = (rn % mr);
	var start = (rn - remainder + mr); 

	var i = params.indexOf("RN=") + 3;
	var j = params.indexOf("&", i);

	var url = currentUrl + "?AC=PREV_BLOCK" + params.substring (0, i) + start + params.substring(j, params.length);

	window.location.href = url; 

}


function back_to_block_cookie(Textbase) 
{
	var params = window.dbtw_params;

	// find the record number
	var rns = params.match(/RN=(\d+)/);
	var rn = parseInt(rns[1]);

	// MR is records at a time
	var mrs = params.match(/MR=(\d+)/);
	var mr = parseInt(mrs[1]);

	// find the lower multiple of mr and add another mr to it to fool PREV_BLOCK
	var remainder = (rn % mr);
	var start = (rn - remainder + mr); 

	var i = params.indexOf("RN=") + 3;
	var j = params.indexOf("&", i);

	var url = currentUrl + "?AC=PREV_BLOCK" + params.substring (0, i) + start + params.substring(j, params.length);
	
	document.cookie = Textbase + "_DbtwLastResult=" + url + "; path=/";
	
}


function back_to_record_cookie(Textbase, RecordNumber)
{
	var params = window.dbtw_params;
	var rn = parseInt(RecordNumber) - 1;
	var i = params.indexOf("RN=") + 3;
	var j = params.indexOf("&", i);
	
	// reconstruct the link with only the RN value replaced
	var url = currentUrl + "?AC=GET_RECORD" + params.substring (0, i) + rn + params.substring(j, params.length);
	document.cookie = Textbase+ "_DbtwFullRecord=" + url + "; path=/";
}

function record_count_cookie(Textbase, RecordCount)
{
	document.cookie = Textbase + "_RecordCount=" + RecordCount + "; path=/";
}





function nextprev_record(record_count)
{
	var params = window.dbtw_params;
	var next_write = "";
	var next_link = "";
	var prev_write = "";
	var prev_link = "";
	var nextprev_link = "";
	var rc = parseInt(record_count);

	// find the record number
	var rns = params.match(/RN=(\d+)/);
	var rn = parseInt(rns[1]);

	
	// determine if a "Previous Record" link should be made
	if (rn > 0)
	{
		prev_write = "Previous Record";

		//prev_link = "<form>";
		prev_link += "<a class='NavBar_Links' href='" + currentUrl;
		//prev_link += "<input type='button' value='" + prev_write + "' onClick='dbtw_prev(\"";
		prev_link +=  "?AC=PREV_RECORD" + params;
		prev_link += "\")' >";
		prev_link += prev_write + "</a>&nbsp;";
		//prev_link += "</form>";
	}
	
	// determine if a "Next Record" link should be made
	if (rn+1 < rc)
	{
		next_write = "Next Record";

		//next_link = "<form>";
		next_link += "<a class='NavBar_Links' href='" + currentUrl;
		//next_link += "<input type='button' value='" + next_write + "' onClick='dbtw_next(\"";
		next_link +=  "?AC=NEXT_RECORD" + params;
		next_link += "\")' >";
		next_link += next_write + "</a>";
		//next_link += "</form>";
	}

	// build the final string to write into HTML
	if (next_link == "" && prev_link == "")
	{
		nextprev_link = "";	
	}
	else if (next_link != "" && prev_link == "")
	{
		nextprev_link += next_link;
	}
	else if (next_link == "" && prev_link != "")
	{
		nextprev_link += prev_link;	
	}
	else
	{ 
		nextprev_link += prev_link + "|&nbsp;" + next_link;		
	}

		
	return nextprev_link;

} 

