//==============================================================================
// Just-traceroute javascript
// $Id: jt.js 20725 2011-02-07 16:21:13Z wmc $
//==============================================================================
var WMAPI = 'http://api.watchmouse.com/1.6/';
//var WMAPI = 'http://gab.watchmouse.com/api/';
// maximum checkpoint in use by user
var MAX_CP = 4;
// setup array of locations to deal with in trace
var locations = [];
// time2live from cookie
var TIME2LIVE = null;
// cookie json string
var JT = {'nkey':null,'nr':0,'max_cp':MAX_CP,'isHuman':false,'tprompt':[]};
if (window.location.hostname == 'www.just-trace.dev' || window.location.hostname == 'www.jt.dev') {
    DEBUG = true;
} else {
    DEBUG = false;
}
//------------------------------------------------------------------------------
// execute functions when DOM is loaded
$(document).ready(function()
{
	// hide no js warning
    $('.warning').hide();

    // set default text and replace SEO text
    $('#searchbtn a').text('Go!');
    
    // set input fields and add events
    $('#inputfield').focus().select();
    // when pressed enter in host input field
    $("#inputfield").keypress(function (e) {
      if (e.which == 13) {
        doTraceroute();
        return false;
      }
    });
    // and for captcha
    $("#txtCaptcha").keypress(function (e) {
      if (e.which == 13) {
        doTraceroute();
        return false;
      }
    });
    //$('.btn-geekmode a').text('Geekmode');
    //$('.btn-mapmode a').text('Mapmode');
    // remove clicks on tabs
    //$('.btn-geekmode a').attr('href','#').click(function(){return false;});
    //$('.btn-mapmode a').attr('href','#').click(function(){return false;});
    
    // move the h1 to the bottom in #footer
    var date = new Date();
    var h1 = $('h1').html()+' &copy; '+date.getFullYear();
    $('h1').empty();
    $('#footer').prepend('<h1>'+h1+'</h1>');
    
    // set global AJAX settings
    $.ajaxSetup({
        url     : 'proxy.php',
		global  : true,
		type    : 'GET',
		dataType: 'json',
		cache   : false
    });
    var cm = $('#current-mode');
    var l = $('.loader');
    $(document).ajaxStart(function(){
        cm.hide();
        l.show();        
    });
    $(document).ajaxStop(function(){
        l.hide();
        cm.show();
    });
    // get available cookie
    var ck = getCookie();
    // merge with default JT if not null
    if (ck != null) {
        JT = $.extend(JT, ck);
    }
    //alert(JT.isHuman);
    
    // get checkpoints. Are free and anonymous
    getCheckpoints();
    
    // check if host is in URLvar url = window.location;
    // and fill in the input field
    url =""+window.location;
    urlparts = url.split('/');
    checkhost = urlparts[3];
    if (checkhost != '' && checkhost.indexOf('?') == -1) {
        if (checkhost.indexOf('.') == -1) checkhost += '.com';
        $('#inputfield').val(checkhost);
        doTraceroute();
    }
});

//==============================================================================
// get chekpoints and add to ul.checkpoints
function getCheckpoints()
{
    // when no connection to internet:
    //setUpCp([{"loc":"br","host":"br.watchmouse.com","ip":"200.152.245.35","country":"br","city":"Porto Alegre","lat":"-30.031055","lng":"-51.218262"},{"loc":"n3","host":"gab.watchmouse.com","ip":"213.193.235.194","country":"nl","city":"Amsterdam3","lat":"52.349998","lng":"4.917000"},{"loc":"mb","host":"mb.watchmouse.com","ip":"122.100.4.43","country":"au","city":"Melbourne","lat":"-34.932999","lng":"138.600006"},{"loc":"nl","host":"dt.watchmouse.com","ip":"81.93.53.2","country":"nl","city":"Amsterdam","lat":"52.349998","lng":"4.917000"}]);
    // /*
    // make ajax call to api to get the checkpoints.
    $.ajax({
        url     : WMAPI+"cp_list.php",
        data    : 'type=trace&limit='+MAX_CP,
        dataType: 'jsonp',
        success : function(json) {
            // check on error
            if (json.code > 0) {
                //pageTracker._trackPageview("/jt/cp_list/failure-"+ json.code);                
                $('.warning').html('Error: '+json.error).show();
                setTimeout('$(\'.warning\').hide()', 3000);
                return;
            }
            else {
                setUpCp(json.result.checkpoints);
            }
        }
    });
    // */
}

//------------------------------------------------------------------------------
// Fill in the checkpoint list and make the terminals
function setUpCp(cps)
{
    if (!cps) {
        $('.warning').html('We have difficulties with getting the locations. Please wait before trying again').show();
        return false;
    }
    $('ul.checkpoints').empty();
    //pageTracker._trackPageview("/jt/cp_list/success");
    var wmcp = {'checkpoints': cps};
    // extend JT
    JT = $.extend(JT, wmcp);
    var n = 1;
    $.each(wmcp.checkpoints, function(i, cp)
    {
        locations[n-1] = cp.loc;
        // set custom id's to handle and content divs
        $('#handle_'+n).attr('id','handle_'+cp.loc);
        $('#flex_'+n).attr('id','flex_'+cp.loc);
        $('#content_'+n).attr('id','content_'+cp.loc);
        //cp.country = getCountry(cp.country);
        // add checkpoint names to #checkpoints
        $('ul.checkpoints').append("<li>"+ cp.country_name+" ("+cp.loc+")</li>");
        
        // make default prompt for each terminal
        var p = '[geek@'+ cp.country_name.toLowerCase() +' ~]$ ';
        JT.tprompt[n-1] = {'loc':cp.loc,'s':p};
        // update terminal header
        $('#handle_'+cp.loc+' h2').html("Terminal "+ cp.country_name);
        // update terminal content
        $('#content_'+cp.loc).html("<span id=\"prompt_"+cp.loc+"\">"+ p +"<span class=\"cursor-blink\">_</span></span>\n");
        n++;
    });
    setCookie(JT);
}

//------------------------------------------------------------------------------
// on key up when filling in host and when API is returning traceroutes
function writeInAllTerminals(v)
{
    if (!v) return;
    $.each(JT.tprompt, function(n, o) {
        $('#prompt_'+o.loc).html(o.s + TRACE_STR +' '+escape(v.value)+'<span class="cursor_blink">_</span><br />');
    });
}

//------------------------------------------------------------------------------
var queueTimer = null;
var countTry = 0;
// check if user is human
function verifyisHuman(host)
{
    $('.warning').fadeOut();
    isHuman = false;
    // check if cookie is not expired
    if (JT && (JT.isHuman == true) && $.cookie('JTcheck')) {
        isHuman = true;
    } else if ($.cookie('JTcheck')) {
        JT = getCookie();
        if (JT.isHuman == true) {
            isHuman = true;
        }
    }
    
    if (!isHuman)
    {
        // verify the input text with the session security code
        var captchaCode = $('#txtCaptcha').val();
        if (captchaCode == '') {
            tb_remove();
            if (countTry > 0) {
                // refresh captcha img, so that after invalid captch confirmation, it doesn't use the same captcha
                var ts = new Date();
                $('#captchImg').attr('src', "img/captcha.jpg?c="+ts.getTime());
            }
            tb_show('Confirm that you are a human...', '#TB_inline?width=230&amp;height=80&amp;inlineId=captcha&amp;modal=true');
            $('#txtCaptcha').focus();
        }
        else {
            countTry++;
            $.ajax({
                type    : 'POST', // POST with jsonp? @@@@
                data    : 'vaction=check_captcha&security_code='+encodeURI(captchaCode),
                async   : false,
                success : function(ret) {
                    if (ret.code > 0) {
                        $('.warning').html(ret.msg).show();
                        tb_remove();
                        //pageTracker._trackPageview("/jt/captcha/failure");
                        queueTimer = setTimeout('doTraceroute("'+host+'")', 2000);
                        $('#txtCaptcha').val('');
                    } else {
                        tb_remove();
                        //pageTracker._trackPageview("/jt/captcha/success");
                        JT.isHuman = true;
                        isHuman = true;
                    }
                }
            });
        }
    }
        
    return isHuman;
}

//------------------------------------------------------------------------------
// Add visitor to waiting Q
function add2Queue()
{
    $.ajax({
        type    : 'POST',
        data    : 'vaction=add_queue',
        async   : false,
        success : function(ret) {
            if (ret.code > 0) {
                $('.warning').html(ret.msg).show();
                //pageTracker._trackPageview("/jt/add_queue/failure");
                if (ret.sleep > 0) {
                    queueTimer = setTimeout('doTraceroute()', (ret.sleep * 1000));
                } else {
                    queueTimer = setTimeout('$(\'.warning\').fadeOut()', 3000);
                }
            } else {
                //pageTracker._trackPageview("/jt/add_queue/success");
                JT.visitorid = ret.visitorid;
                return true;
            }
        }
    });
    return false;
}

//------------------------------------------------------------------------------
// do a call to proxy to initiate the traceroute
var pollTimer = null;
var done = [];
var trace = [];

function doTraceroute()
{
    // clear queue time out when needed
    if (queueTimer) clearTimeout(queueTimer);
    // hide any warning
    $('.warning').fadeOut();
    // hide the options button
    $('#options').hide();
    $('.btn-options').hide();

    // check if host is not empty
    validHost = false;
    host = $('#inputfield').val();
    host = host.replace(new RegExp("^http(s)?://", "g"), '');
    host = host.replace(new RegExp(" +$", "g"), '');
    host = host.replace(new RegExp("^ +", "g"), '');
    $('#inputfield').val(host);
    var ipfilter = /^([0-9][0-9]{0,2})+\.([0-9][0-9]{0,2})+\.([0-9][0-9]{0,2})+\.([0-9][0-9]{0,2})+$/;
    if (ipfilter.test(host)) {
        validHost = true;
    } else if (/^([a-z0-9][a-z0-9-]*[a-z0-9]\.)+[a-z]{2,}$/i.test(host)) {
        validHost = true;
    }
    
    if (!validHost) {
        $('.warning').html('This is not a valid IP or hostname. Try again').show();
        queueTimer = setTimeout('$(\'.warning\').fadeOut()', 3000);
        return false;
    }
    
    $('#more-checkpoints a').attr('href','/about.php?h='+encodeURI(host));
    $('#current-mode a').attr('href','/about.php?h='+encodeURI(host));
    $('.btn-geekmode a').attr('href','/about.php?h='+encodeURI(host));
    
    // always check if client is human
    if (verifyisHuman(host)) {
        // disable the input field and submit button
        $('#searchbtn a').attr('disabled','disabled')
            .removeAttr('href')
            .removeAttr('onclick')
            .addClass('inactive')
            .unbind('click');
        $('#inputfield').unbind();
        
        add2Queue();
        
        // set queue
        $.ajax({
            type    : 'POST', // POST with jsonp? @@@@
            data    : 'vaction=check_queue',
            async   : false,
            success : function(ret) {
                if (ret.code > 0) {
                    $('.warning').html(ret.msg).show();
                    pageTracker._trackPageview("/jt/queue/full");
                    // set time interval to check again
                    if (ret.sleep > 0) {
                        queueTimer = setTimeout('doTraceroute()', (ret.sleep * 1000));
                    } else {
                        queueTimer = setTimeout('$(\'.warning\').fadeOut()', 3000);
                    }
                } else {
                    //$.log(JT);
                    //pageTracker._trackPageview("/jt/queue/ok");
                    //pageTracker._trackPageview("/jt/traceroute/start");
                    pageTracker._trackPageview("/traceroute/"+c);
                    // append iframe in footer
                    cp = new Array();
                    for (i in JT.checkpoints) {
                        cp[i] = JT.checkpoints[i].loc;
                        done[i] = JT.checkpoints[i].loc;
                    }
                    // reset trace
                    trace = [];
                    // reset email div
                    $('#email').remove();
                    // set source of iframe
                    var cps = cp.join(',');
                    if ($('#ifrm').is('iframe')) {
                        $('#ifrm').attr('src', 'proxy.php?vaction=do_tr&host='+ encodeURI(host)+'&cp='+ encodeURI(cps));
                    } else {
                        $('#footer').append('<iframe id="ifrm" src="proxy.php?vaction=do_tr&host='+ encodeURI(host)+
                                            '&cp='+ encodeURI(cps) +'"></iframe>');
                    }
                                            
                    // empty terminal and plac prompt + traceroute
                    //$.log(JT.tprompt);
                    $.each(JT.tprompt, function(n, o) {
                        $('#content_'+o.loc).empty();
                        $('#content_'+o.loc).html('<span id="prompt_'+o.loc+'">'+o.s +'traceroute '+host+'</span><br />');
                        flex = document.getElementById('flex_'+o.loc);
                        if (flex && flex.scrollUpdate) {
                            flex.scrollUpdate();
                        }
                    });
                    pollTimer = setTimeout('doTerminal()', 500);
                }
            }
        });
    }
}

//------------------------------------------------------------------------------
// Get the contents from the iframe with 'loc' and put that in the designated terminal
function doTerminal()
{
    if (!$('.loader').is(':visible')) {
        toggleLoader('show');
    }
    // clear old timer
    if (pollTimer) clearTimeout(pollTimer);
    var txt = '';
    // get iframe object
    var ifrm = document.getElementById('ifrm');
    // if iframe body already exists get the value
    if (txt = extractIFrameBody(ifrm)) 
    {
        // if text is surrounded by <pre> tag, get only the inner html
        if ($(txt).is('pre')) {
            txt = $(txt).html();
        }
        
        // get the partial content and split the lines
        var lines = txt.split('|');
        // parse through all the lines
        $.each(lines, function(i,line) 
        {
            var s = '';
            line = trim(line);
            if (line != '') {
                eval("var json = "+ line);
                if (typeof json != 'undefined' && typeof json == 'object' && json.hop != '')
                {
                    if (json.code && json.code > 0) {
                        $('.warning').html('Traceroute error ('+json.code+'): '+json.msg).show();
                        return;
                    }
                    // get the location and put them in the right terminal
                    var loc = json.loc;
                    if ($.inArray(loc, done) != -1)
                    {
                        var terminal = document.getElementById('content_'+loc);
                        if (!trace[loc]) trace[loc] = [];
                        // if done
                        if (json.done) {
                            var ndx = $.inArray(loc, done);
                            done.splice(ndx,1);
                            $('#prompt_'+ loc +'span.cursor_blink').remove();
                            $('#prompt_'+ loc).removeAttr('id');
                            for(i in JT.tprompt) {
                                if (JT.tprompt[i].loc == loc) {
                                    var s = JT.tprompt[i].s;
                                }
                            }
                            s = '<br /><span id="prompt_'+ loc +'">'+ s +'<span class="cursor_blink">_</span></span>'; 
                        }
                        // get line
                        else if (!trace[loc][i]) {
                            s = json.hop;
                            trace[loc][i] = s;
                        }
                        
                        if (s != '') {
                            terminal.innerHTML += s + '<br/>';
                            var flex = document.getElementById('flex_'+loc);
                            if (flex && flex.scrollUpdate) {
                                flex.scrollUpdate();
                                flex.contentScroll(false,"100px",true);
                            }
                        }
                    }
                }
            }
        });
    }
    if (done.length == 0) {
        if (pollTimer) clearTimeout(pollTimer);
        $.each(locations, function(n, loc) {
            var flex = document.getElementById('flex_'+loc);
            if (flex.scrollUpdate) {
                flex.scrollUpdate();
                flex.contentScroll(false,"10px",true);
            }
        });
        return endTrace();
    } 
    else {
        pollTimer = setTimeout('doTerminal()',700);
    }
}

//------------------------------------------------------------------------------
// when call is fully complete. (All traces are comleted)
// reset every var that has to be reset
function endTrace()
{
    // add anothr trace ro nr
    JT.nr++;    
    // reset done array
    done = [];
    pageTracker._trackPageview("/jt/traceroute/end"); 
    // enable the input field and submit button
    $('#searchbtn a').attr('href', '#')
            .removeAttr('disabled')
            .removeClass('inactive')
            .click(function(){
        doTraceroute();
        return false;
    });
    $("#inputfield").keypress(function (e) {
      if (e.which == 13) {
        doTraceroute();
        return false;
      }
    });
    
    toggleLoader('hide');
    var host = $('#inputfield').text();
    // make mail div and button
    $('#current-mode').html('<a onclick="javascript: pageTracker._trackPageview(\'/outgoing/watchmouse.com/result/jt_monitor_after\');" href="http://www.watchmouse.com/register.php?vtype=trial&m=23494&c='+c+'jt_monitor_after&vurlreg='+ encodeURI(host) +'">'+
                              'Do you want to monitor your server periodically?</a>');
    $('#current-mode a').css({'color':'#FF6600'});
    // send trace to database
    // and remove from queue
    var postBody = '';
    for (loc in trace) {
        postBody += "loc["+loc+"]="+trace[loc].join("|")+"&";
        
    }
    $.post('proxy.php', {'vaction':'remove_queue',
                         'trace':encodeURI(postBody),
                         'host':encodeURI(host)}
    );
    host = $('#inputfield').val();
    $('.btn-options').show();
    $('#options').slideDown('slow');
    $('#options-bar').html('What do you want to do with the results? '+
        '<a class="clipboard" title="Copy traceroute to clipboard" href="javascript:void(0);">copy to my clipboard</a>'+
        ' or <a href="#" title="Forward these traceroute results to your techie or host" onclick="mailTrace(\''+host+'\')">email me/to other techie</a>'
        );
    
    var clip = '';
    $.each(JT.checkpoints, function(i, cp) {
        clip += '* ' + cp.country_name + ":\n";
        $.each(trace[cp.loc], function(i, v) {
            if (v && v.length > 2) {
               clip += v + "\n";
            }
        });
        clip += "\n";
    });

    $.clipboardReady(function() {
        $(".clipboard").click(function(){
            $.clipboard(clip);
            $('.warning').html('Copied to your clipboard. You can now paste it in every app you want').show();
            setTimeout('$(\'.warning\').fadeOut()', 2000);
            return false;
        });
    }, { swfpath: "/js/jquery.clipboard.swf" });

    return true;
}

//------------------------------------------------------------------------------
function mailTrace(host)
{
    // append email div to the footer
    if (!$('#email').is('div')) {
        $('#footer').append('<div id="email" class="thickbox" style="display:none"><h2>Send these results to a friend/company</h2>'+
                        '<div class="email_inner"><form name="dummy" onsubmit="return false"><input tabindex="1" size="40" type="text" name="from" id="from" value="<from>" class="inputfld">'+
                        '<div class="small">(Note: We will NEVER sell or rent email addresses)</div>'+
                        '<input tabindex="2" size="40" type="text" name="to" id="to" value="<to>" class="inputfld"><br />'+
                        '<div class="small">(Separate multiple email addresses with a comma)</div><br />'+
                        '<textarea tabindex="3" rows="4" cols="60" name="prepend" id="prepend">Hi,\n'+
                        'I just did an online traceroute to "'+host+'" from 4 locations, and this was the result:\n</textarea><br />'+
                        '<div id="tracetxt"></div><br />'+
                        '<textarea tabindex="4" rows="3" cols="60" name="append" id="append">Regards,\n\n</textarea><br />'+
                        '<div id="sign">\n<br />\n-- <br />\njust-traceroute, Online traceroute from 4+ locations: <a href="http://just-traceroute.com">http://just-traceroute.com</a>. <br />\n'+
                        'Also check out our blog: <a href="http://just-traceroute.com/blog/">http://just-traceroute.com/blog/</a></div>'+
                        '<div align="right"><input tabindex="6" type="button" value="close" class="closebtn" onclick="tb_remove();">&nbsp;&nbsp;'+
                        '<input tabindex="5" type="submit" value="send" class="submitbtn" onclick="sendMailTrace(\''+host+'\')"></div>'+
                        '</form></div></div>');
        var val='';
        for (i in JT.checkpoints) {
            var cp = JT.checkpoints[i];
            var cntry = cp.country_name;
            var loc = cp.loc;
            val += '<b>'+cntry+":</b><br />\n";
            for (k in trace[loc]) {
                if (trace[loc][k] != '') val += trace[loc][k]+"<br />\n";
            }
            val += "<br />\n";
        }
        $('#tracetxt').html(val);
        $('#from').click(function(){
            if (this.value == '<from>') {
                this.value = '';
            }
        });
        $('#from').blur(function(){
            if (this.value == '') {
                this.value = '<from>';
            }
        });
        $('#to').click(function(){
            if (this.value == '<to>') {
                this.value = '';
            }
        });
        $('#to').blur(function(){
            if (this.value == '') {
                this.value = '<to>';
            }
        });
    }
    tb_show('Email me this traceroute', '#TB_inline?width=390&amp;height=520&amp;inlineId=email&amp;modal=true');
}

//------------------------------------------------------------------------------
function sendMailTrace(host)
{
    $('.warning').css('background-color','#f60');
    tb_remove();
    var from = $('#from').val();
    var to = $('#to').val();
    // check from and to fields
    if (from == '<from>' || to == '<to>') {
        $('.warning').html('You must fill in the From email and To email field of the form').show();
        setTimeout('$(\'.warning\').fadeOut()', 2500);
        setTimeout('tb_show(\'Email me this traceroute\', \'#TB_inline?width=390&amp;height=520&amp;inlineId=email&amp;modal=true\')', 3000);
        return;
    }    
    var prepend = $('#prepend').val();
    var append = stripslashes($('#append').val());
    append += $('#sign').html();
    var sTracetxt = '';
    var cntry = new Array();
    for (i in JT.checkpoints) {
        var cp = JT.checkpoints[i];
        cntry[i] = cp.country_name;
        sTracetxt += trace[cp.loc].join('|')+',';
    }
    var ua = navigator.userAgent;
    var countries = cntry.join(',');
    $.post('proxy.php', {'vaction':'send_mail',
                         'from':encodeURI(from),
                         'to':encodeURI(to),
                         'prepend':encodeURI(prepend),
                         'append':encodeURI(append),
                         'country':encodeURI(countries),
                         'trace':encodeURI(sTracetxt),
                         'host':encodeURI(host),
                         'ua':encodeURI(ua)},
            function(json) {
                if (json.code == 0) {
                    // set warning to green background
                    $('.warning').css('background-color','#80FF00');
                }
                $('.warning').html(json.msg).show();
                setTimeout('$(\'.warning\').fadeOut()', 3000);
            }
    );    
}
//------------------------------------------------------------------------------
function getTraceText() {
    
    return sTracetxt;
}
//------------------------------------------------------------------------------
function extractIFrameBody(ifrm)
{
    var doc = null;
    if (ifrm.contentDocument) { // For NS6
        doc = ifrm.contentDocument; 
    } else if (ifrm.contentWindow) { // For IE5.5 and IE6
        doc = ifrm.contentWindow.document;
    } else if (ifrm.document) { // For IE5
        doc = ifrm.document;
    } else {
        return null;
    }
    if (doc.body) {
        return doc.body.innerHTML;
    } else {
        return null;
    }
}
//------------------------------------------------------------------------------
function setCookie(json) {
    // stringify the object
    var v = JSON.stringify(json);
    // check if cookie was already set.
    // if yes then get expire date
    if (ck = getCookie()) {
        if (ck.ts) {
            date = new Date(ck.ts * 1000);
            //alert(date.toUTCString());
            TIME2LIVE = ck.time2live;
        }
    }
    if (!TIME2LIVE) {
        var date = new Date();
        date.setTime(date.getTime() + (1 * 3600 * 1000));
    }
    // set cookie
    $.cookie('JTcheck', v, {'expires':date});
}
//------------------------------------------------------------------------------
// get cookie 'JTcheck' and returns json object
function getCookie() {
    var json = null;
    if (ck = $.cookie('JTcheck')) {
        json = JSON.parse(ck);
        if (typeof json == 'undefined') {
            json = null;
        }
    }
    return json;
}
//------------------------------------------------------------------------------
function toggleLoader(vis) {
    var cm = $('#current-mode');
    var l = $('.loader');
    
    if (vis == 'show') {
        cm.hide();
        l.show();
    } else if (vis == 'hide') {
        l.hide();
        cm.show();
    } else {
        if (l.is(':visible')) {
            l.hide();
            cm.show();
        } else {
            cm.hide();
            l.show();
        }
    }
}
//------------------------------------------------------------------------------
// trim functions
function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}
//------------------------------------------------------------------------------
function getCountry(isocode) {
    
    if (!isocode) return false;
    
    var wm_country = new Array();
    wm_country['ad'] = 'Andorra'; wm_country['ae'] = 'United Arab Emirates'; wm_country['ag'] = 'Antigua'; wm_country['ai'] = 'Anguilla'; wm_country['al'] = 'Albania'; wm_country['am'] = 'Armenia'; wm_country['an'] = 'Netherlands Antilles'; wm_country['ao'] = 'Angola'; wm_country['ar'] = 'Argentina'; wm_country['as'] = 'American Samoa'; wm_country['at'] = 'Austria'; wm_country['au'] = 'Australia'; wm_country['aw'] = 'Aruba'; wm_country['az'] = 'Azerbaijan'; wm_country['bb'] = 'Barbados'; wm_country['bd'] = 'Bangladesh'; wm_country['be'] = 'Belgium'; wm_country['bf'] = 'Burkina Faso'; wm_country['bg'] = 'Bulgaria'; wm_country['bh'] = 'Bahrain'; wm_country['bi'] = 'Burundi'; wm_country['bj'] = 'Benin'; wm_country['bm'] = 'Bermuda'; wm_country['bn'] = 'Brunei'; wm_country['bo'] = 'Bolivia'; wm_country['br'] = 'Brazil'; wm_country['bs'] = 'Bahamas'; wm_country['bt'] = 'Bhutan'; wm_country['bw'] = 'Botswana'; wm_country['by'] = 'Belarus'; wm_country['bz'] = 'Belize'; wm_country['ca'] = 'Canada'; wm_country['cd'] = 'Congo, The Republic of'; wm_country['cf'] = 'Central African Republic'; wm_country['cg'] = 'Congo - Brazzaville'; wm_country['ch'] = 'Switzerland'; wm_country['ci'] = 'Ivory Coast'; wm_country['ck'] = 'Cook Islands'; wm_country['cl'] = 'Chile'; wm_country['cm'] = 'Cameroon'; wm_country['cn'] = 'China'; wm_country['co'] = 'Colombia'; wm_country['cr'] = 'Costa Rica'; wm_country['cs'] = 'Channel Islands'; wm_country['cv'] = 'Cape Verde'; wm_country['cy'] = 'Cyprus'; wm_country['cz'] = 'Czech Republic'; wm_country['de'] = 'Germany'; wm_country['dj'] = 'Djibouti'; wm_country['dk'] = 'Denmark'; wm_country['dm'] = 'Dominica'; wm_country['do'] = 'Dominican Republic'; wm_country['dz'] = 'Algeria'; wm_country['ec'] = 'Ecuador'; wm_country['ee'] = 'Estonia'; wm_country['eg'] = 'Egypt'; wm_country['er'] = 'Eritrea'; wm_country['es'] = 'Spain'; wm_country['et'] = 'Ethiopia'; wm_country['fi'] = 'Finland'; wm_country['fj'] = 'Fiji'; wm_country['fm'] = 'Micronesia'; wm_country['fo'] = 'Faroe Islands'; wm_country['fr'] = 'France'; wm_country['ga'] = 'Gabon'; wm_country['gb'] = 'United Kingdom'; wm_country['gd'] = 'Grenada'; wm_country['ge'] = 'Georgia'; wm_country['gf'] = 'French Guiana'; wm_country['gh'] = 'Ghana'; wm_country['gi'] = 'Gibraltar'; wm_country['gl'] = 'Greenland'; wm_country['gm'] = 'Gambia'; wm_country['gn'] = 'Guinea'; wm_country['gp'] = 'Guadeloupe'; wm_country['gq'] = 'Equatorial Guinea'; wm_country['gr'] = 'Greece'; wm_country['gs'] = 'St. Barthelemy'; wm_country['gt'] = 'Guatemala'; wm_country['gu'] = 'Guam'; wm_country['gw'] = 'Guinea Bissau'; wm_country['gy'] = 'Guyana'; wm_country['hk'] = 'Hong Kong'; wm_country['hn'] = 'Honduras'; wm_country['hr'] = 'Croatia'; wm_country['ht'] = 'Haiti'; wm_country['hu'] = 'Hungary'; wm_country['id'] = 'Indonesia'; wm_country['ie'] = 'Ireland'; wm_country['il'] = 'Israel'; wm_country['in'] = 'India'; wm_country['iq'] = 'Iraq'; wm_country['ir'] = 'Iran'; wm_country['is'] = 'Iceland'; wm_country['it'] = 'Italy'; wm_country['jm'] = 'Jamaica'; wm_country['jo'] = 'Jordan'; wm_country['jp'] = 'Japan'; wm_country['ke'] = 'Kenya'; wm_country['kg'] = 'Kyrgyzstan'; wm_country['kh'] = 'Cambodia'; wm_country['kn'] = 'St. Kitts and Nevis'; wm_country['kr'] = 'South Korea'; wm_country['kw'] = 'Kuwait'; wm_country['ky'] = 'Cayman Islands'; wm_country['kz'] = 'Kazakhstan'; wm_country['la'] = 'Laos'; wm_country['lb'] = 'Lebanon'; wm_country['lc'] = 'St. Lucia'; wm_country['li'] = 'Liechtenstein'; wm_country['lk'] = 'Sri Lanka'; wm_country['lr'] = 'Liberia'; wm_country['ls'] = 'Lesotho'; wm_country['lt'] = 'Lithuania'; wm_country['lu'] = 'Luxembourg'; wm_country['lv'] = 'Latvia'; wm_country['ly'] = 'Libya'; wm_country['ma'] = 'Morocco'; wm_country['mc'] = 'Monaco'; wm_country['md'] = 'Moldova'; wm_country['mg'] = 'Madagascar'; wm_country['mh'] = 'Marshall Islands'; wm_country['mk'] = 'Macedonia'; wm_country['ml'] = 'Mali'; wm_country['mm'] = 'Myanmar/Burma'; wm_country['mn'] = 'Mongolia'; wm_country['mo'] = 'Macau'; wm_country['mp'] = 'Saipan'; wm_country['mq'] = 'Martinique'; wm_country['mr'] = 'Mauritania'; wm_country['ms'] = 'Montserrat'; wm_country['mt'] = 'Malta'; wm_country['mu'] = 'Mauritius'; wm_country['mw'] = 'Malawi'; wm_country['mx'] = 'Mexico'; wm_country['my'] = 'Malaysia'; wm_country['mz'] = 'Mozambique'; wm_country['na'] = 'Namibia'; wm_country['nc'] = 'New Caledonia'; wm_country['ne'] = 'Niger'; wm_country['ng'] = 'Nigeria'; wm_country['ni'] = 'Nicaragua'; wm_country['nl'] = 'Netherlands'; wm_country['no'] = 'Norway'; wm_country['np'] = 'Nepal'; wm_country['nz'] = 'New Zealand'; wm_country['om'] = 'Oman'; wm_country['pa'] = 'Panama'; wm_country['pe'] = 'Peru'; wm_country['pf'] = 'French Polynesia'; wm_country['pg'] = 'Papua New Guinea'; wm_country['ph'] = 'Philippines'; wm_country['pk'] = 'Pakistan'; wm_country['pl'] = 'Poland'; wm_country['pr'] = 'Puerto Rico'; wm_country['ps'] = 'Palestinian Territory'; wm_country['pt'] = 'Portugal'; wm_country['pw'] = 'Palau'; wm_country['py'] = 'Paraguay'; wm_country['qa'] = 'Qatar'; wm_country['re'] = 'Reunion'; wm_country['ro'] = 'Romania'; wm_country['ru'] = 'Russia'; wm_country['rw'] = 'Rwanda'; wm_country['sa'] = 'Saudi Arabia'; wm_country['sc'] = 'Seychelles'; wm_country['sd'] = 'Sudan'; wm_country['se'] = 'Sweden'; wm_country['sg'] = 'Singapore'; wm_country['si'] = 'Slovenia'; wm_country['sk'] = 'Slovak Republic'; wm_country['sl'] = 'Sierra Leone'; wm_country['sm'] = 'San Marino'; wm_country['sn'] = 'Senegal'; wm_country['so'] = 'Somalia'; wm_country['sr'] = 'Suriname'; wm_country['sv'] = 'El Salvador'; wm_country['sy'] = 'Syria'; wm_country['sz'] = 'Swaziland'; wm_country['tc'] = 'Turks and Caicos Islands'; wm_country['td'] = 'Chad'; wm_country['tg'] = 'Togo'; wm_country['th'] = 'Thailand'; wm_country['tm'] = 'Turkmenistan'; wm_country['tn'] = 'Tunisia'; wm_country['tr'] = 'Turkey'; wm_country['tt'] = 'Trinidad and Tobago'; wm_country['tw'] = 'Taiwan'; wm_country['tz'] = 'Tanzania'; wm_country['ua'] = 'Ukraine'; wm_country['ug'] = 'Uganda'; wm_country['us'] = 'U.S.A.'; wm_country['uy'] = 'Uruguay'; wm_country['uz'] = 'Uzbekistan'; wm_country['va'] = 'Vatican City'; wm_country['vc'] = 'St. Vincent'; wm_country['ve'] = 'Venezuela'; wm_country['vg'] = 'British Virgin Islands'; wm_country['vi'] = 'U.S. Virgin Islands'; wm_country['vn'] = 'Vietnam'; wm_country['vu'] = 'Vanuatu'; wm_country['wf'] = 'Wallis & Futuna'; wm_country['ye'] = 'Yemen'; wm_country['za'] = 'South Africa'; wm_country['zm'] = 'Zambia'; wm_country['zw'] = 'Zimbabwe';
    return wm_country[isocode];
}
function blank(){};
function addslashes(str) {
    str=str.replace(/\'/g,'\\\'');
    str=str.replace(/\"/g,'\\"');
    str=str.replace(/\\/g,'\\\\');
    str=str.replace(/\\0/g,'\\0');
    return str;
}
function stripslashes(str) {
    str=str.replace(/\\'/g,'\'');
    str=str.replace(/\\"/g,'"');
    str=str.replace(/\\\\/g,'\\');
    str=str.replace(/\\0/g,'\0');
    return str;
}
// EOF

