// An link switcher by <EL|magus@lepi.org>
// mostly a compilation of various sniplets of code created by 
// other talented people
// Last edit : 2006-05-11 @ 19:00
 
function setActiveLinks(title) {
var a;
var x = document.getElementsByTagName("a");
	for (var i=0;(a = x[i]);i++)	{
// check for <a href="#" title="lien">&#Hanzi;</a>
   if (a.title == "lien") {
              if (title == "frdic") changeNodeCN(a) ;
         else if (title == "xuezhongwen")   changeNodeXZW(a) ;
         else if (title == "mandarintools") changeNodeMT(a) ;
         else if (title == "wiktionary") changeNodeWK(a) ;
         else if (title == "etymology") changeNodeCE(a) ;
         else if (title == "ocrat") changeNodeO(a) ;
         else removeNode(a) ;
   }
   }

// give back the proper focus in the selection (from the cookie)
  var x = document.getElementsByTagName("select") ;
  if (x[0]) {
  for (i=0; (a = x[0].options[i]); i++) {
    if(a.value == title)   {
         a.selected = true;
    } else { a.selected = false; }
  }
  }

}

function removeNode(n) {
	n.href = "#" ; 
}

var hD="0123456789ABCDEF";
// decimal to hexadecimal
function d2h(d) {
  var h = hD.substr(d&15,1);
  while(d>15) {d>>=4;h=hD.substr(d&15,1)+h;}
  return h;
}

// decimal to hexadecimal
function h2d(h) {return parseInt(h,16);}

// Character (utf-8 encoded) to Entities
function C2E (str) {
    str = str.replace(/&/g, '&#38;');
    str = str.replace(/'/g, '&#39;');
    str = str.replace(/"/g, '&#34;');
    str = str.replace(/\\/g, '&#92;');
    var acc = '';
    for (var i = 0; i < str.length; i++) {
        if (str.charCodeAt(i) > 31 && str.charCodeAt(i) < 127) acc += str.charAt(i) 
        else acc += '&#' + str.charCodeAt(i) + ';';
    }
    return acc;
}

// Entities (&#xxxx;) to Character (UTF-8)
function E2C (str) {
    str = str.replace(/(&#[0-9]+;)/g, '\n$1\n');
    str = str.replace(/\n\n/g, '\n');
    spl = str.split('\n');
    for (var i = 0; i < spl.length; i++) {
        if (spl[i].charAt(0) == '&') {
            spl[i] = spl[i].replace(/&#([0-9]+);/g, '$1');
            spl[i] = String.fromCharCode(spl[i]);
        }
    } 
    str = spl.join('');
    return str;
}

// converts a UTF-8 decimal entity to the hexa code ex: &#23376; -> 5B50 (corresponds to &#x5B50; ) - used for Ocrat mirror
function tohex(u) {
        t = new String(C2E(u)); 
        re = /(&#|;)/g ;  
        t = C2E(u).replace(re, ""); // strips &# or ; in encoded string
        return d2h(t) ;
}


// modify the address to point towards Ocrat mirror
function changeNodeO(n) {
        n.href = "http://lost-theory.org/ocrat/chargif/char/unicode.py?codepoint=" +
      tohex(n.firstChild.nodeValue) ;
//   n.firstChild.nodeValue += ' (cn)' ;
}

// modify the address to point towards frdic.com
function changeNodeCN(n) {
	n.href = encodeURI("http://www.frdic.com/SearchDic.aspx?word=" +
      n.firstChild.nodeValue) ;
}

// modify the address to point towards ChineseEtymology.org
function changeNodeCE(n) {
        n.href = encodeURI("http://www.chineseetymology.org/CharacterASP/CharacterEtymology.aspx?characterInput=" +
      n.firstChild.nodeValue + "&submitButton1=Etymology"); 
}   

// modify the address to point towards XueZhongWen.net
function changeNodeXZW(n) {
	n.href = encodeURI("http://www.xuezhongwen.net/chindict/chindict.php?page=worddictbasic&wdqb=" +
      n.firstChild.nodeValue + "&wdrst=0&go=Search") ;
}

// modify the address to point towards MandarinTools.com
function changeNodeMT(n) {
	n.href = encodeURI("http://www.mandarintools.com/cgi-bin/wordlook.pl?word=" +
      n.firstChild.nodeValue + "&searchtype=chinese&where=whole&audio=on") ;
}

// modify the address to point towards Wiktionary
function changeNodeWK(n) {
        n.href = encodeURI("http://fr.wiktionary.org/wiki/" +
                   n.firstChild.nodeValue ) ;
}
              

function getSelectedLinks() {
// returns the selected option of the <select>...
var a ;
  if (a = document.getElementsByTagName("select")[0]) {
   if (a.options) return a.options[a.selectedIndex].value;
   else return a.options[0].value;
   }
   else return null ;
}


function createCookie(name,value,days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }
  else expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}

    /*  Encoding and decoding of Unicode character strings as
        UTF-8 byte streams.  */
        
    //  UNICODE_TO_UTF8  --  Encode Unicode argument string as UTF-8 return value

    function unicode_to_utf8(s) {
        var utf8 = "";
        
        for (var n = 0; n < s.length; n++) {
            var c = s.charCodeAt(n);

            if (c <= 0x7F) {
                //  0x00 - 0x7F:  Emit as single byte, unchanged
                utf8 += String.fromCharCode(c);
            } else if ((c >= 0x80) && (c <= 0x7FF)) {
                //  0x80 - 0x7FF:  Output as two byte code, 0xC0 in first byte
                //                                          0x80 in second byte
                utf8 += String.fromCharCode((c >> 6) | 0xC0);
                utf8 += String.fromCharCode((c & 0x3F) | 0x80);
            } else {
                // 0x800 - 0xFFFF:  Output as three bytes, 0xE0 in first byte
                //                                         0x80 in second byte
                //                                         0x80 in third byte
                utf8 += String.fromCharCode((c >> 12) | 0xE0);
                utf8 += String.fromCharCode(((c >> 6) & 0x3F) | 0x80);
                utf8 += String.fromCharCode((c & 0x3F) | 0x80);
            }
        }
        return utf8;
    }

    //  UTF8_TO_UNICODE  --  Decode UTF-8 argument into Unicode string return value

    function utf8_to_unicode(utf8) {
        var s = "", i = 0, b1, b2, b2;

        while (i < utf8.length) {
            b1 = utf8.charCodeAt(i);
            if (b1 < 0x80) {        // One byte code: 0x00 0x7F
                s += String.fromCharCode(b1);
                i++;
            } else if((b1 >= 0xC0) && (b1 < 0xE0)) {    // Two byte code: 0x80 - 0x7FF
                b2 = utf8.charCodeAt(i + 1);
                s += String.fromCharCode(((b1 & 0x1F) << 6) | (b2 & 0x3F));
                i += 2;
            } else {                // Three byte code: 0x800 - 0xFFFF
                b2 = utf8.charCodeAt(i + 1);
                b3 = utf8.charCodeAt(i + 2);
                s += String.fromCharCode(((b1 & 0xF) << 12) |
                                         ((b2 & 0x3F) << 6) |
                                         (b3 & 0x3F));
                i += 3;
            }
        }
        return s;
    }

    /*  ENCODE_UTF8  --  Encode string as UTF8 only if it contains
                         a character of 0x9D (Unicode OPERATING
                         SYSTEM COMMAND) or a character greater
                         than 0xFF.  This permits all strings
                         consisting exclusively of 8 bit
                         graphic characters to be encoded as
                         themselves.  We choose 0x9D as the sentinel
                         character as opposed to one of the more
                         logical PRIVATE USE characters because 0x9D
                         is not overloaded by the regrettable
                         "Windows-1252" character set.  Now such characters
                         don't belong in JavaScript strings, but you never
                         know what somebody is going to paste into a
                         text box, so this choice keeps Windows-encoded
                         strings from bloating to UTF-8 encoding.  */
                         
    function encode_utf8(s) {
        var i, necessary = false;
        
        for (i = 0; i < s.length; i++) {
            if ((s.charCodeAt(i) == 0x9D) ||
                (s.charCodeAt(i) > 0xFF)) {
                necessary = true;
                break;
            }
        }
        if (!necessary) {
            return s;
        }
        return String.fromCharCode(0x9D) + unicode_to_utf8(s);
    }
    
    /*  DECODE_UTF8  --  Decode a string encoded with encode_utf8
                         above.  If the string begins with the
                         sentinel character 0x9D (OPERATING
                         SYSTEM COMMAND), then we decode the
                         balance as a UTF-8 stream.  Otherwise,
                         the string is output unchanged, as
                         it's guaranteed to contain only 8 bit
                         characters excluding 0x9D.  */
                         
    function decode_utf8(s) {
        if ((s.length > 0) && (s.charCodeAt(0) == 0x9D)) {
            return utf8_to_unicode(s.substring(1));
        }
        return s;
    }


window.onload = function(e) {
 var cookie = readCookie("zhlinks");
 var title = cookie ? cookie : getSelectedLinks();
 setActiveLinks(title);
}

window.onunload = function(e) {
 var title = getSelectedLinks();
 createCookie("zhlinks", title, 365);
}

var cookie = readCookie("zhlinks");
var title = cookie ? cookie : getSelectedLinks();
setActiveLinks(title);
