/*
 * GLOBAL VAIRABLES DEFINITION
 */
var _g_service_data = null;
var _g_user_data = null;
var _g_contact_data = null;

/*
 * MAIN FUNCTION, PROGRAM ENTRENCE
 */
document.observe('dom:loaded',function(){
    // INIT GLOBAL
    _initGlobal();
    // EVERY PAGE MAY HAVE ONE INIT FUNCTION TO INIT PAGE DISPALY
    if(typeof _initPage != "undefined" && Object.isFunction(_initPage) ){
        _initPage();
    }
    
});

Object.extend(String.prototype, {
    templateDecode: function() {
        var decoded = this.replace(/#%7B([a-zA-Z0-9_-]+)%7D/gi, "#{$1}");
        return decoded;
    }
});

function _initGlobal(){
    // LOAD SERVICE/USER DATA FIRST, SUB HEADER NEED THESE DATA
    if(typeof _service_data != "undefined"){
        _service_data = Base64.decode(_service_data).evalJSON();
        if(_service_data.RETURN){
            _g_service_data = _service_data;
        }
        _service_data = null;
    }
    if(typeof _user_data != "undefined"){
        _user_data = Base64.decode(_user_data).evalJSON();
        if(_user_data.RETURN){
            _g_user_data = _user_data.user_data;
        }
        _user_data = null;
    }
    
    
    // LOAD HEADER
    HeaderFooter.setHeaderData();
    HeaderFooter.setHeaderSelection();
    
    correctPNG();
    //testpage();
}

function testpage(){
    var sString = $('divtest').innerHTML.templateDecode();
    alert(sString);
    
    var show = {xxx: '/images/xixi.png'};
    sString=sString.interpolate(show);
    
    alert(sString);
}

// PRE_DEFINED PAGE INIT FUNCTION FOR EVERY PAGE.
//function _initPage(){
//	alert("initPage");
//	return null;
//}

/**
 * HEADER FOOTER FUNCTIONS
 */
var HeaderFooter = {
    // HIGLLIGHT MENU IF THE URL MATCHES
    setHeaderSelection: function(){
        
        // GET CURRENT PAGE STRING FROM URL
        var currentPage = document.location.pathname;
        var lastIdx = currentPage.lastIndexOf('/')+1;
        currentPage = currentPage.substring(lastIdx).strip();
        // IF ROOT
        if(currentPage.length<2){
            currentPage = "index.html";
        }
        // GET MATCHED ELEMENT
        if($('header')!=null && $('header').select('li')!=null){
	        var aSelectedPage = $('header').select('li');
	        for(var i=0;i<aSelectedPage.size();i++){
	            var tmp = aSelectedPage[i];
	            if(tmp.innerHTML.include(currentPage)){
	                // SET ID=CURRENT, WILL HIGH LIGHT MENU
	                tmp.setAttribute('id', 'current');
	            }else{
	                // REMOVE ALL OTHER ID, IF PRE-SET
	                tmp.removeAttribute('id');
	            }
	        }
        }
        
        // V2
        if(currentPage.include("sms.html")||currentPage.include("im.html")){
        	currentPage = "index.html";
        }
        var query = window.location.search.substring(1);
        if($('header_er')!=null && $('header_er').select('li')!=null){
	        var aSelectedPage = $('header_er').select('li');
	        for(var i=0;i<aSelectedPage.size();i++){
	            var tmp = aSelectedPage[i];
	            /*if(currentPage.include("login_signup.html")){
	            	if(query.include("signup") && tmp.innerHTML.include("Sign Up")){
	            		tmp.setAttribute('id', 'current');
	            	}else if(!query.include("signup") && tmp.innerHTML.include("Login")){
	            		tmp.setAttribute('id', 'current');
	            	}else{
	            		tmp.removeAttribute('id');
	            	}
	            }else*/
	            if(tmp.innerHTML.include(currentPage)){
	                // SET ID=CURRENT, WILL HIGH LIGHT MENU
	                tmp.setAttribute('id', 'current');
	            }else{
	                // REMOVE ALL OTHER ID, IF PRE-SET
	                tmp.removeAttribute('id');
	            }
	        }
        }
    },

    // SET DATA IN SUB MENU HTML TEMPLATE 
    setHeaderData: function(){
        //var html = $('header').innerHTML;
    
        // LOGIN SUB MENU
        if(_g_user_data){
            var sBalanceType = "Referral Credits:";
            var iBalance = 0;
            var sVMcount = "0/0";
            var sFullname = _g_user_data.firstname + " " + _g_user_data.lastname;
        
            if(_g_user_data.purchase_credits<=0){
                sBalanceType = "Referral Credits:";
                iBalance = _g_user_data.free_credits;
            }else{
                sBalanceType = "Purchased Credits:";
                iBalance = _g_user_data.purchase_credits;
            }
            if($('header_fullname')!=null){
            	$('header_fullname').update(sFullname);
            }
            if($('header_balance_type')!=null){
            	$('header_balance_type').update(sBalanceType);
            }
            if($('header_balance')!=null){
            	$('header_balance').update(iBalance);
            }
            //$('header_notice').update("Notice: Text to Call - SMS to 61429883430");
        }else{
            // LOGOUT SUB MENU
            if($('header_notice')!=null){
            	$('header_notice').update(_g_service_data.total_user+" users | "+_g_service_data.total_country+" countries");
            }
        }		
    }
}




/**
 *
 *  Base64 encode / decode
 *  http://www.webtoolkit.info/
 *
 **/

var Base64 = {
    
    // private property
    _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
    
    // public method for encoding
    encode : function (input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;
        
        input = Base64._utf8_encode(input);
        
        while (i < input.length) {
            
            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);
            
            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;
            
            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }
        
            output = output +
                this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
                this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
        
        }
    
        return output;
    },

    // public method for decoding
    decode : function (input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;
    
        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
    
        while (i < input.length) {
        
            enc1 = this._keyStr.indexOf(input.charAt(i++));
            enc2 = this._keyStr.indexOf(input.charAt(i++));
            enc3 = this._keyStr.indexOf(input.charAt(i++));
            enc4 = this._keyStr.indexOf(input.charAt(i++));
        
            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;
        
            output = output + String.fromCharCode(chr1);
        
            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }
        
        }
    
        output = Base64._utf8_decode(output);
    
        return output;
    
    },

    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";
    
        for (var n = 0; n < string.length; n++) {
        
            var c = string.charCodeAt(n);
        
            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }
        
        }
    
        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;
    
        while ( i < utftext.length ) {
        
            c = utftext.charCodeAt(i);
        
            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }
        
        }
    
        return string;
    }

}


/*****************************************************************************/
/************ tokiva card *********/
/*****************************************************************************/
/*
 * self card
 * personal card
 */    
function showSelfCard(page,position){
    var user = _g_user_data;
    
    var card_div = $('tokiva_card_div').innerHTML.templateDecode();
    
    var myTemplate = new Template(card_div);
    
    var personal_name = user.name;
    var personal_photo = '<img id="user_photo_path" src="'+user.photo_path_large+'" class="photo_large"/>';
    if(page == 'home'){
        var personal_link = 'Personal&nbsp;|&nbsp;<a onclick="showSelfBusinessCard(\''+page+'\')" class="handcursor">Business</a>';
        var personal_option = '<div><a href="profile.html"><u>Edit</u></a>&nbsp;&nbsp;</div>';
        var personal_card_bg_img = '';
        
    }else if(page == 'profile'){
        var personal_link = 'Personal&nbsp;|&nbsp;<a onclick="showBusinessInfoPage(\''+page+'\');" class="handcursor">Business</a>';
        //var personal_option = '<span style="width:30px;height:17px; _height:17px; border:0px; background: url(images/card_call_left.png) no-repeat; padding-right:16px; margin-right:20px;">Call</span>';  
        //var personal_card_bg_img = '<img src="images/card_call_right.png" width="20" height="17" />';
        var personal_option = '';  
        var personal_card_bg_img = '';
    }
    var personal_faceimage = '<img src="images/tokiva_face.png" width="16" height="16" />';
    var personal_screenName = '<a href="http://www.tokiva.com/'+user.screen_name+'">'+user.screen_name+'</a>';
    var personal_socialNetworkImage = user.social_network_image;
    if(user.social_network){
        var personal_socialNetworkName = '<a href="'+user.social_network_link+'" target="_blank">'+user.social_network+'</a>';
    }
    var personal_imImage = user.im_image;
    var personal_imAccount = user.im_account;
    var personal_personalMsg = user.personal_msg;
    var personal_countryFlag = '<img src="countryflags/'+user.phone_country_iso_a2+'.png"/>';
    var personal_localTime = user.local_time;


    var show = {personal_card_name:personal_name,personal_card_link:personal_link,personal_card_photo:personal_photo,personal_card_faceimage:personal_faceimage,
        personal_card_screenName:personal_screenName,personal_card_socialNetworkImage:personal_socialNetworkImage,personal_card_socialNetworkName:personal_socialNetworkName,
        personal_card_imImage:personal_imImage,personal_card_imAccount:personal_imAccount,personal_card_personalMsg:personal_personalMsg,personal_card_countryFlag:personal_countryFlag,
        personal_card_localTime:personal_localTime,personal_card_option:personal_option,personal_card_bg_img:personal_card_bg_img};
    var table = myTemplate.evaluate(show);

    $(position).update(table);
}
/*
 * business card
 */        
function showSelfBusinessCard(page){
    var user = _g_user_data;
    
    var card_div = $('tokiva_business_card_div').innerHTML;
    var myTemplate = new Template(card_div);
    
    var business_name = user.name;
    var business_photo = '<img id="business_photo_path" src="'+user.business_photo+'" class="photo_large"/>';
    if(page == 'home'){
        var business_link = '<a onclick="closeCard(\''+page+'\')" class="handcursor">Personal</a>&nbsp;|&nbsp;Business';
        var business_option = '<div><a href="profile.html?business=1"><u>Edit</u></a>&nbsp;&nbsp;</div>';
        var business_card_bg_img = '';
    }else if(page == 'profile'){
        var business_link = '<a onclick="showSelfCard(\'profile\',\'show_tokiva_card\');changeShowHide(\'personalInfoForm\',\'businessInfoForm\');" class="handcursor">Personal</a>&nbsp;|&nbsp;Business';
//        var business_option = '<div style="width:30px;height:17px; _height:17px; border:0px; background: url(images/card_call_left.png) no-repeat; padding-right:16px; margin-right:20px;">Call</div>';  
//        var business_card_bg_img = '<img src="images/card_call_right.png" width="20" height="17" />';
        var business_option = '';  
        var business_card_bg_img = '';
    }
    var business_title = user.title;
    var business_company = user.company;
    if(user.website){
        var business_website = '<a href="'+user.websiteLink+'" target="_blank">'+user.website+'</a>';
    }
    var business_addressline1 = user.address_line1;
    var business_addressline2 = user.address_line2;
    var business_state = user.state;
    var business_country = user.country_name;
    var business_postalcode = user.postal_code;
    var business_city = user.city;
    if(user.address){
        var business_addressmap = '<a href="'+user.map_address+'" target="_blank">Map this address</a>';
    }
    var business_countryFlag = '<img src="countryflags/'+user.phone_country_iso_a2+'.png"/>';
    var business_localTime = user.local_time;


    var show = {business_card_name:business_name,business_card_link:business_link,business_card_photo:business_photo,business_card_title:business_title,
        business_card_company:business_company,business_card_website:business_website,business_card_addressline1:business_addressline1,business_card_addressline2:business_addressline2,
        business_card_state:business_state,business_card_country:business_country,business_card_postalcode:business_postalcode,business_card_city:business_city,
        business_card_addressmap:business_addressmap,business_card_countryFlag:business_countryFlag,business_card_localTime:business_localTime,business_card_option:business_option,business_card_bg_img:business_card_bg_img};
    var table = myTemplate.evaluate(show);

    $('show_tokiva_card').update(table);
}

/*
 * Tokiva card class
 */
var TokivaCard = Class.create({
    initialize: function(user){
        this.user = user;
    },
    showPersonalCard: function(page,templete,location){
        var user = this.user;
        var card_div = $(templete).innerHTML.templateDecode();
            
        var myTemplate = new Template(card_div);
        var personal_name = user.name;
        var personal_photo = '<img id="user_photo_path" src="'+user.photo_path_large+'" class="photo_large"/>';
        var personal_link = null;
        var personal_option = null;
        var personal_card_bg_img = null;
        
        if(page == 'home'){
            personal_link = 'Personal&nbsp;|&nbsp;<a onclick="showSelfBusinessCard(\''+page+'\')" class="handcursor">Business</a>';
            personal_option = '<div><a href="profile.html"><u>Edit</u></a>&nbsp;&nbsp;</div>';
            personal_card_bg_img = '';
        }else if(page == 'profile'){
            personal_link = 'Personal&nbsp;|&nbsp;<a onclick="showBusinessInfoPage(\''+page+'\');" class="handcursor">Business</a>';
            //var personal_option = '<span style="width:30px;height:17px; _height:17px; border:0px; background: url(images/card_call_left.png) no-repeat; padding-right:16px; margin-right:20px;">Call</span>';  
            //var personal_card_bg_img = '<img src="images/card_call_right.png" width="20" height="17" />';
            personal_option = '';  
            personal_card_bg_img = '';
        }else if(page == 'tokivalink'){
            personal_link = 'Personal&nbsp;|&nbsp;<a onclick="changeShowHide(\'business_card\',\'personal_card\');" class="handcursor">Business</a>';
            var personal_option = 'Call';
            var personal_card_bg_img = '';
        }
        var personal_faceimage = '<img src="images/tokiva_face.png" width="16" height="16" />';
        var personal_screenName = '<a href="http://www.tokiva.com/'+user.screen_name+'">'+user.screen_name+'</a>';
        var personal_socialNetworkImage = user.social_network_image;
        if(user.social_network){
            var personal_socialNetworkName = '<a href="'+user.social_network_link+'" target="_blank">'+user.social_network+'</a>';
        }
        var personal_imImage = user.im_image;
        var personal_imAccount = user.im_account;
        var personal_personalMsg = user.personal_msg;
        var personal_countryFlag = '<img src="countryflags/'+user.phone_country_iso_a2+'.png"/>';
        var personal_localTime = user.local_time;
		
		
        var show = {personal_card_name:personal_name,personal_card_link:personal_link,personal_card_photo:personal_photo,personal_card_faceimage:personal_faceimage,
            personal_card_screenName:personal_screenName,personal_card_socialNetworkImage:personal_socialNetworkImage,personal_card_socialNetworkName:personal_socialNetworkName,
            personal_card_imImage:personal_imImage,personal_card_imAccount:personal_imAccount,personal_card_personalMsg:personal_personalMsg,personal_card_countryFlag:personal_countryFlag,
            personal_card_localTime:personal_localTime,personal_card_option:personal_option,personal_card_bg_img:personal_card_bg_img};
        var table = myTemplate.evaluate(show);
		
        $(location).update(table);
    },
    showBusinessCard: function(page,templete,location){
        var user = this.user;
        
        var card_div = $(templete).innerHTML;
        var myTemplate = new Template(card_div);
    	
        var business_name = user.name;
        var business_photo = '<img id="business_photo_path" src="'+user.business_photo+'" class="photo_large"/>';
        if(page == 'home'){
            var business_link = '<a onclick="closeCard(\''+page+'\')" class="handcursor">Personal</a>&nbsp;|&nbsp;Business';
            var business_option = '<div><a href="profile.html?business=1"><u>Edit</u></a>&nbsp;&nbsp;</div>';
            var business_card_bg_img = '';
        }else if(page == 'profile'){
            var business_link = '<a onclick="showSelfCard(\'profile\',\'show_tokiva_card\');changeShowHide(\'personalInfoForm\',\'businessInfoForm\');" class="handcursor">Personal</a>&nbsp;|&nbsp;Business';
            var business_option = '<div style="width:30px;height:17px; _height:17px; border:0px; background: url(images/card_call_left.png) no-repeat; padding-right:16px; margin-right:20px;">Call</div>';  
            var business_card_bg_img = '<img src="images/card_call_right.png" width="20" height="17" />';
        }else if(page = "tokivalink"){
            var business_link = '<a onclick="changeShowHide(\'personal_card\',\'business_card\');" class="handcursor">Personal</a>&nbsp;|&nbsp;Business';
            var business_option = 'Call';  
            var business_card_bg_img = '';
        }
        var business_title = user.title;
        var business_company = user.company;
        if(user.website){
            var business_website = '<a href="'+user.websiteLink+'" target="_blank">'+user.website+'</a>';
        }
        var business_addressline1 = user.address_line1;
        var business_addressline2 = user.address_line2;
        var business_state = user.state;
        var business_country = user.country_name;
        var business_postalcode = user.postal_code;
        var business_city = user.city;
        if(user.address){
            var business_addressmap = '<a href="'+user.map_address+'" target="_blank">Map this address</a>';
        }
        var business_countryFlag = '<img src="countryflags/'+user.phone_country_iso_a2+'.png"/>';
        var business_localTime = user.local_time;
		
		   		
        var show = {business_card_name:business_name,business_card_link:business_link,business_card_photo:business_photo,business_card_title:business_title,
            business_card_company:business_company,business_card_website:business_website,business_card_addressline1:business_addressline1,business_card_addressline2:business_addressline2,
            business_card_state:business_state,business_card_country:business_country,business_card_postalcode:business_postalcode,business_card_city:business_city,
            business_card_addressmap:business_addressmap,business_card_countryFlag:business_countryFlag,business_card_localTime:business_localTime,business_card_option:business_option,business_card_bg_img:business_card_bg_img};
        var table = myTemplate.evaluate(show);
		    	
        $(location).update(table);
    }
});

/******************************************************************************/
/**************** COUNTRY CODE **********************/
/******************************************************************************/

var CountryCode = null; 
var CountryName = null;
var unknown_country = "unknown_country";
var TopCountryCodeText = '';
var CountryCodeText= '';



function loadCountryCode(){
    
    
    //   var CountryCode = null, CountryName = null;
    //  var unknow_country = "";
    
    TopCountryCodeText = "1, US/Canada/Caribbean;\
    86,China						;\
    852,Hong Kong                  ;\
    63,Philippines                 ;\
    52,Mexico                      ;\
    44,UK                          ;\
    33,France                      ;\
    39,Italy                       ;\
    49,Germany                     ;\
    34,Spain                       ;\
    61,Australia                   ;\
    27,South Africa                ;\
    972,Israel                     ;\
    91,India                       ;\
    965,Kuwait                     ;\
    971,UAE                        ;\
    966,Saudi Arabia               ;\
    92,Pakistan                    ;\
    968,Oman                       ";
    
    CountryCodeText="93,Afghanistan                 ;\
    355,Albania                    ;\
    213,Algeria                    ;\
    376,Andorra                    ;\
    244,Angola                     ;\
    672,Antarctica                 ;\
    54,Argentina                   ;\
    374,Armenia                    ;\
    297,Aruba                      ;\
    247,Ascension Islands          ;\
    61,Australia                   ;\
    43,Austria                     ;\
    994,Azerbaijan                 ;\
    973,Bahrain                    ;\
    880,Bangladesh                 ;\
    375,Belarus                    ;\
    32,Belgium                     ;\
    501,Belize                     ;\
    229,Benin                      ;\
    975,Bhutan                     ;\
    591,Bolivia                    ;\
    387,Bosnia                     ;\
    267,Botswana                   ;\
    55,Brazil                      ;\
    673,Brunei                     ;\
    359,Bulgaria                   ;\
    226,Burkina Faso               ;\
    257,Burundi                    ;\
    855,Cambodia                   ;\
    237,Cameroon                   ;\
    238,Cape Verde Island          ;\
    236,Central Africa Republic    ;\
    235,Chad Republic              ;\
    56,Chile                       ;\
    86,China                       ;\
    57,Colombia                    ;\
    269,Comoros                    ;\
    242,Congo                      ;\
    682,Cook Island                ;\
    506,Costa Rica                 ;\
    385,Croatia                    ;\
    53,Cuba                        ;\
    599,Curacao                    ;\
    357,Cyprus                     ;\
    420,Czech Republic             ;\
    45,Denmark                     ;\
    246,Diego Garcia               ;\
    253,Djibouti                   ;\
    243,DP Congo                   ;\
    670,East Timor                 ;\
    593,Ecuador                    ;\
    20,Egypt                       ;\
    503,El Salvador                ;\
    240,Equatorial Guinea          ;\
    291,Eritrea                    ;\
    372,Estonia                    ;\
    251,Ethiopia                   ;\
    298,Faeroe Islands             ;\
    500,Falkland Islands           ;\
    679,Fiji Islands               ;\
    358,Finland                    ;\
    33,France                      ;\
    596,French Antilles            ;\
    594,French Guiana              ;\
    689,French Polynesia           ;\
    241,Gabon                      ;\
    220,Gambia                     ;\
    995,Georgia                    ;\
    49,Germany                     ;\
    233,Ghana                      ;\
    350,Gibraltar                  ;\
    881,GMSS                       ;\
    30,Greece                      ;\
    299,Greenland                  ;\
    590,Guadeloupe                 ;\
    502,Guatemala                  ;\
    224,Guinea                     ;\
    245,Guinea Bissau              ;\
    592,Guyana                     ;\
    509,Haiti                      ;\
    504,Honduras                   ;\
    852,Hong Kong                  ;\
    36,Hungary                     ;\
    354,Iceland                    ;\
    91,India                       ;\
    62,Indonesia                   ;\
    870,Inmarsat                   ;\
    98,Iran                        ;\
    964,Iraq                       ;\
    353,Ireland                    ;\
    972,Israel                     ;\
    39,Italy                       ;\
    225,Ivory Coast                ;\
    81,Japan                       ;\
    962,Jordan                     ;\
    254,Kenya                      ;\
    686,Kiribati                   ;\
    965,Kuwait                     ;\
    996,Kyrgyz Republic            ;\
    856,Laos                       ;\
    371,Latvia                     ;\
    961,Lebanon                    ;\
    266,Lesotho                    ;\
    231,Liberia                    ;\
    218,Libya                      ;\
    423,Liechtenstein              ;\
    370,Lithuania                  ;\
    352,Luxembourg                 ;\
    853,Macao                      ;\
    389,Macedonia                  ;\
    261,Madagascar                 ;\
    265,Malawi                     ;\
    60,Malaysia                    ;\
    960,Maldives                   ;\
    223,Mali Republic              ;\
    356,Malta                      ;\
    692,Marshall Islands           ;\
    222,Mauritania                 ;\
    230,Mauritius                  ;\
    52,Mexico                      ;\
    691,Micronesia                 ;\
    373,Moldova                    ;\
    377,Monaco                     ;\
    976,Mongolia                   ;\
    212,Morocco                    ;\
    258,Mozambique                 ;\
    95,Myanmar                     ;\
    264,Namibia                    ;\
    674,Nauru                      ;\
    977,Nepal                      ;\
    31,Netherlands                 ;\
    687,New Caledonia              ;\
    64,New Zealand                 ;\
    505,Nicaragua                  ;\
    227,Niger                      ;\
    234,Nigeria                    ;\
    683,Niue Island                ;\
    850,North Korea                ;\
    47,Norway                      ;\
    968,Oman                       ;\
    92,Pakistan                    ;\
    680,Palau                      ;\
    970,Palestine                  ;\
    507,Panama                     ;\
    675,Papau New Guinea           ;\
    595,Paraguay                   ;\
    51,Peru                        ;\
    63,Philippines                 ;\
    48,Poland                      ;\
    351,Portugal                   ;\
    239,Principe / Sao Tome        ;\
    974,Qatar                      ;\
    262,Reunion Island             ;\
    40,Romania                     ;\
    7,Russian Federetion           ;\
    250,Rwanda                     ;\
    378,San Marino                 ;\
    966,Saudi Arabia               ;\
    221,Senegal Republic           ;\
    381,Serbia / Yugoslavia        ;\
    248,Seychelles                 ;\
    232,Sierra Leone               ;\
    65,Singapore                   ;\
    421,Slovakia                   ;\
    386,Slovenia                   ;\
    677,Solomon Islands            ;\
    252,Somalia                    ;\
    27,South Africa                ;\
    82,South Korea                 ;\
    34,Spain                       ;\
    94,Sri Lanka                   ;\
    290,St. Helena                 ;\
    508,St. Pierre & Miquelon      ;\
    249,Sudan                      ;\
    597,Suriname                   ;\
    268,Swaziland                  ;\
    46,Sweden                      ;\
    41,Switzerland                 ;\
    963,Syria                      ;\
    886,Taiwan                     ;\
    992,Tajikistan                 ;\
    255,Tanzania / Zanzibar        ;\
    66,Thailand                    ;\
    228,Togo                       ;\
    690,Tokelau                    ;\
    676,Tonga                      ;\
    216,Tunisia                    ;\
    90,Turkey                      ;\
    993,Turkmenistan               ;\
    649,Turks/Caicos               ;\
    688,Tuvalu Islands             ;\
    971,UAE                        ;\
    256,Uganda                     ;\
    44,UK                          ;\
    380,Ukraine                    ;\
    598,Uruguay                    ;\
    1,US/Canada/Caribbean          ;\
    998,Uzbekistan                 ;\
    678,Vanuatu                    ;\
    58,Venezuela                   ;\
    84,Vietnam                     ;\
    681,Wallis/Futuna              ;\
    685,West Samoa                 ;\
    967,Yemen                      ;\
    260,Zambia                     ;\
    263,Zimbabwe                   ";
}    
function initCountryCode(){
    
    var country=CountryCodeText.split(";");
    CountryCode=new Array(country.length);
    CountryName=new Array(country.length);
    for(var i=0;i<country.length;i++){
        var xxx = country[i].split(",");
        
        CountryCode[i] =trim(xxx[0]);
        
        CountryName[i] =trim(xxx[1]);
        //alert(CountryCode[i] + "|" + CountryName[i] + "|" );
    }
}

function searchCountry(number){
    
    if(CountryCode == null){
        initCountryCode();
    }
    
    var code1,code2,code3,name,found=false;
    
    code1 = number.substr(0,1);
    code2 = number.substr(0,2);
    code3 = number.substr(0,3);
    
    //alert(number + "|" + code1 + "|" + code2 + "|"+ code3 + "|");
    
    for(var i=0;i<CountryCode.length;i++){
        if(CountryCode[i] == code1 || CountryCode[i] == code2 || CountryCode[i] == code3){
            name = CountryName[i];
            found = true;
            //alert("found="+name);
            break;
        }
    }
    if(found){
        return name;
    }else{
        return false;
    }
}

function displayCountryName(codeObjID, nameObjID){
    
    if(CountryCode == null){
        
        initCountryCode();
    }
    
    var nameObj = $(nameObjID);
    var codeObj = $(codeObjID);
    //alert(nameObj.innerHTML);
    
    var number = codeObj.value;
    var country = searchCountry(number);
    
    if(!country){
        nameObj.update(unknown_country);
    }else{
        nameObj.update(country);
    }
    if(!country && number.length>=3){
        var number = codeObj.value;
        codeObj.value = number.substr(0,2);
        alert(number.substr(0,3) + " is not a valid country code.");
        return false;
    }
    return true;
}

function onPhoneChanged(selectObjID,codeObjID){//change country by phone
    if(CountryCode==null){
        initCountryCode();
    }
    
    var countrySelect=$(selectObjID);
    var codeObj=$(codeObjID);
    var number=codeObj.value;
    //alert(number);
    var code;
    
    var country = searchCountry(number);
    
    if(!country){
        countrySelect.selectedIndex=0;
    }else{
    
        for(var i=0;i<CountryCode.length;i++){
            if(CountryName[i] == country){
                //alert(CountryCode[i]);
                code = CountryCode[i] ;
                countrySelect.value=code;
                //alert(i);
                break;
            } 
        }
    }
    if(!country && number.length>=3){
        alert("Please enter a valid country code.");
        countrySelect.selectedIndex = 0;
        codeObj.value =  countrySelect[0].value;
        return false;
    }
    return true;
}

function initCountrySelection(selectObjID, codeObjID){
    if(CountryCode == null){
        initCountryCode();
    }
    // init top conutry list
    var country=TopCountryCodeText.split(";");
    topCountryCode=new Array(country.length);
    topCountryName=new Array(country.length);
    for(var i=0;i<country.length;i++){
        var xxx = country[i].split(",");
        topCountryCode[i] =trim(xxx[0]);
        topCountryName[i] =trim(xxx[1]);
    }
    
    // get select object and selected code.
    var countrySelect=document.getElementById(selectObjID);
    
    if(codeObjID == null || codeObjID == ""){
        selectCode = 0;
    }else{
        var countryCode=$(codeObjID);
        var v=countryCode.value
        selectCode= v.substr(1, v.length-1);
    }

    // init top list.
    var selected=-1;

    for(var i=0;i<topCountryCode.length;i++){
        var x=document.createElement('option');
        x.text=topCountryName[i]+" - ("+topCountryCode[i]+")";
        x.value=topCountryCode[i]+"";
        if(topCountryCode[i] == selectCode){
            //alert("top "+x.text);
            selected = i;
        }
        try{
            countrySelect.add(x,null); // standards compliant
        }catch(ex){
            countrySelect.add(x);// IE only
        }
    }
    // seperator
    var x=document.createElement('option');
    x.text="-----------------------";
    x.value="-----------------------";
    try{
        countrySelect.add(x,null); // standards compliant
    }catch(ex){
        countrySelect.add(x);// IE only
    }
    // init full list
    for(var i=0;i<CountryCode.length;i++){
        var x=document.createElement('option');
        x.text=CountryName[i]+" - ("+CountryCode[i]+")";
        x.value=CountryCode[i]+"";
        if(CountryCode[i] == selectCode && selected==-1){
            //alert(x.text);
            selected = topCountryCode.length+1+i;
        }
        try{
            countrySelect.add(x,null); // standards compliant
        }catch(ex){
            countrySelect.add(x);// IE only
        }
    }
    // set selection
    countrySelect.selectedIndex = selected;
}

function onCountrySelectionChanged(selectObjID, codeObjID) {
    var countrySelect=$(selectObjID);
    var countryCode=$(codeObjID);
    
    var code = countrySelect [ countrySelect.selectedIndex ] .value;
    if(isNaN(code)){
        alert("Please select a country");
        countrySelect.selectedIndex = 0;
        countryCode.value = countrySelect[0].value;
        return false;
    }
    countryCode.value = code;
    return true;
}




/*****************************************************************************/
/******************* TOOLS **********************/
/*******************************************************************************/
function firstIsNaN(tostr){
    var hh=false;
    if(isNaN(tostr.substr(0,1))){
        //alert("11");
        hh=true;
    }else{
        //alert("22");
        hh=false;
    }
    return hh;
}

function isNumberKey(evt){
    var key = evt.charCode;
    
    if(key > 31 && (key < 48 || key > 57)){
        
        alert('Please input digit only');
        return false;
    }
    return true;
}


function trim(str)
{
    return str.replace(/^\s*|\s*$/g,"");
}




function pagination(type,page,totalpage){
    
    $('UpPage_'+type).observe('click',function(){
        location.href='?'+type+'&page=1';
    });
    
    $('indexPage_'+type).observe('click',function(){
        location.href='?'+type+'&page='+((parseInt(page)-1>1)?parseInt(page)-1:1);
    });
    
    $('NextPage_'+type).observe('click',function(){
        location.href= '?'+type+'&page='+((parseInt(page)+1<totalpage)?parseInt(page)+1:totalpage);
    });
    
    $('EndPage_'+type).observe('click',function(){
        location.href='?'+type+'&page='+totalpage;
    });
    
}


function setPage(totalPage,Page,v)
{ 
    var startPage = 1;
    var endPage = 10;
    var indexPage = Math.ceil(totalPage/10);
    
    if(totalPage<10){
        endPage = totalPage;
    }
    
    if(Page>=10){
        for(var i=2;i<=indexPage;i++){
            
            endPage = i*10;
            startPage = endPage-9;
            if(i==indexPage){
                endPage=totalPage;
                
            }
            if(Page/endPage<1)break;
            
        }
        
        if(Page%10==0){
            
            startPage = Page-1;
            
        }
    }
    
    
    var vPara = "&"+v;
    
    $("pagination_"+v).style.display="none";
    
    var pageHTML='';
    
    if(isNaN(totalPage))return;
    if(totalPage==1)return;
    
    for(var p=startPage;p<=endPage;p++){
        var tempHTML = new Element('a',{'id':p,'href':'?'+v+'&page='+p}).update(p);
        $("SetPage_"+v).appendChild(tempHTML);
    }
    
    pageHTML="";
    $("pagination_"+v).style.display="";
}


function getPage(Type,Page,totalpage){ 
    if($(Page))$(Page).className='curp';
    
    if(Page ==1){
        
        $("up_"+Type).style.display="none";
    }
    
    if(Page ==totalpage){
        $("down_"+Type).style.display="none";
    } 
    
}


function checkEmail(email) {
    var rejectedDomain=new Array()
    var index=0;
    rejectedDomain[index++]="spambox"
    
    var rejected=false
    var testresults=true
    var str=email
    var filter=/^.+@.+\..{2,3}$/
    if (filter.test(str)){
        var tempstring = str.split("@")
        tempstring = tempstring[1].split(".")
        for (i=0; i<rejectedDomain.length; i++) {
            if (tempstring[0]==rejectedDomain[i])
                testresults=false
        }
    } else {
        testresults=false
    }
    return (testresults)
}


function mSubstr(str,slen){
    var tmp = 0;
    var len = 0;
    var okLen = 0;
    for(var i=0;i<slen;i++){
        if(str.charCodeAt(i)>255){
            tmp += 2;
        }else{
            len += 1;
        }
        okLen += 1;
        if(tmp + len == slen){
            return (str.substring(0,okLen)+"...");
            break;
        }
        if(tmp + len > slen){
            return (str.substring(0,okLen - 1)+"...");
            break;
        }
    }
}

function md5(parameter){
    
   
    new Ajax.Request('/service/AjaxRun', 
    { 	//method:'get',
        parameters: {"wsfunc": "ws_md5",'parameter':parameter},
        requestHeaders: {Accept: 'application/json'},
        onSuccess: function(transport){
            var json = transport.responseText.evalJSON(true);
            if(json.RETURN){
                onMD5Success(json.token);
                    
            }                  
        }
    });
}
    
function changeShowHide(show_object,hide_object){
    $(hide_object).hide();
    $(show_object).show();
}
    
function loading(divID){
    var img = new Element('img',{'src':'images/loading.gif'});
    $(divID).update(img);
}
function loaded(divID){
    $(divID).update();
}
    

/*************************************************************************************/
/************************* util.js **********************************************/
/*************************************************************************************/
function loadContactsList(){
        
    new Ajax.Request('/service/AjaxRun', 
    { 	//method:'get',
        parameters: {"wsfunc": "ws_get_contact_list"},
        requestHeaders: {Accept: 'application/json'},
        onSuccess: function(transport){
            var json = transport.responseText.evalJSON(true);
            if(json.RETURN){
                        
                onLoadContactsSuccess(json.contact_list);
                        
            }else{
                onLoadContactsFail(json.MESSAGE);
            }
        }
            
    });
        
}
    
    
function checkTokivaID(tokivaID){
        
    new Ajax.Request('/service/AjaxRun', 
    { 	//method:'get',
                
        parameters: {"wsfunc": "ws_check_tokivaID","parameter":tokivaID},
        requestHeaders: {Accept: 'application/json'},
        onSuccess: function(transport){
            var json = transport.responseText.evalJSON(true);
            if(json.RETURN){
                        
                onCheckTokivaIDSuccess(json.userdata);
            }else{
                onCheckTokivaIDFail();
                    
            }
        }
    });  
}
    
function getContactByScreenName(screen_name){
    new Ajax.Request('/service/AjaxRun', 
    { 	//method:'get',
        parameters: {"wsfunc": "ws_get_contact_by_screen_name",'screen_name':screen_name},
        requestHeaders: {Accept: 'application/json'},
        onSuccess: function(transport){
            var json = transport.responseText.evalJSON(true);
            if(json.RETURN){
                onGetContactByScreenNameSuccess(json.contact_data);
                        
            }                  
        }
    });
}
        
function getUserByScreenName(screen_name){
    new Ajax.Request('/service/AjaxRun', 
    { 	//method:'get',
        parameters: {"wsfunc": "ws_get_user_by_screen_name",'screen_name':screen_name},
        requestHeaders: {Accept: 'application/json'},
        onSuccess: function(transport){
            var json = transport.responseText.evalJSON(true);
            if(json.RETURN){
                onGetUserByScreenNameSuccess(json.user_data);
                            
            }                  
        }
    });
                
}
            
            
function addRegularContact(phone,email,name,notes){
    new Ajax.Request('/service/AjaxRun', 
    { 	//method:'get',
        parameters: {'wsfunc':'ws_add_regular_contact','phone':phone,'email':email,'name':name,'notes':notes},
        requestHeaders: {Accept: 'application/json'},
        onSuccess: function(transport){
            var json = transport.responseText.evalJSON(true);
            if(json.RETURN){
                onAddRegularContactSuccess();
                                
            }else{
                onAddRegularContactFail(json.MESSAGE);
                            
            }                  
        }
    });
}
            
            
function updateRegularContact(cid,phone,email,name,notes){
    new Ajax.Request('/service/AjaxRun', 
    { 	//method:'get',
        parameters: {'wsfunc':'ws_update_regular_contact','cid':cid,'phone':phone,'email':email,'name':name,'notes':notes},
        requestHeaders: {Accept: 'application/json'},
        onSuccess: function(transport){
            var json = transport.responseText.evalJSON(true);
            if(json.RETURN){
                                
                onAddRegularContactSuccess();
                                
            }else{
                onAddRegularContactFail(json.MESSAGE);
                            
            }                  
        }
    });
}
            
            
function addTokivaContact(screen_name,name,note){
    new Ajax.Request('/service/AjaxRun', 
    { 	//method:'get',
        parameters: {"wsfunc": "ws_add_tokiva_contact",'screen_name':screen_name,'name':name,'note':note},
        requestHeaders: {Accept: 'application/json'},
        onSuccess: function(transport){
            var json = transport.responseText.evalJSON(true);
            if(json.RETURN){
                                
                onAddTokivaContactSuccess();
            }                  
        }
    });
}
                
function getInviteMail(){
    new Ajax.Request('/service/AjaxRun', 
    { 	//method:'get',
        parameters: {"wsfunc": "ws_get_invite_mail"},
        requestHeaders: {Accept: 'application/json'},
        onSuccess: function(transport){
            var json = transport.responseText.evalJSON(true);
            if(json.RETURN){
                onGetInviteMailSuccess(json.invite_mail);
            }                  
        }
    });
}
                    
function loadUserData(){
                        
    new Ajax.Request('/service/AjaxRun', 
    { 	//method:'get',
        parameters: {"wsfunc": "ws_get_user_data"},
        requestHeaders: {Accept: 'application/json'},
        onSuccess: function(transport){
            var json = transport.responseText.evalJSON(true);
            if(json.RETURN){
                onLoadUserDataSuccess(json.user_data);
            }
        }
    });
}
                        
                        
function inviteFriends(parameter){
    new Ajax.Request('/service/AjaxRun', 
    { 	//method:'get',
        parameters: {"wsfunc": "ws_invite_friends","parameter":parameter},
        requestHeaders: {Accept: 'application/json'},
        onSuccess: function(transport){
            var json = transport.responseText.evalJSON(true);
            if(json.RETURN){
                onInviteFriendsSuccess();
            }else{
                onInviteFriendsFail(json.MESSAGE);
            }
        }
    });
}
                        
function deleteContact(cid){
                            
    new Ajax.Request('/service/AjaxRun', 
    { 	//method:'get',
                                    
        parameters: {"wsfunc": "ws_delete_contact","cid":cid},
        requestHeaders: {Accept: 'application/json'},
        onSuccess: function(transport){
            var json = transport.responseText.evalJSON(true);
            if(json.RETURN){
                                            
                onDeleteContactSuccess();
            }else{
                onDeleteContactFail();
                                        
            }
        }
    });  
}
                        
                        
function checkCreditCard(card_number){
    $('confirm_submit_img').style.display='none';
    //  var card_number = $F('card_number');
    if(card_number.length<16){
        $('bill_errorMsg').update('Please input correct credit card number');
        $('bill_errorMsg').style.display='';
        return false;
    }
                            
    new Ajax.Request('/service/CreditCardCheck', 
    { 	//method:'get',
        parameters: {"card_number":card_number},
        requestHeaders: {Accept: 'application/json'},
        onSuccess: function(transport){
            var json = transport.responseText.evalJSON(true);
            if(json.RETURN){
                                            
                onCheckCreditCardSuccess();
                                            
            }else{
                onCheckCreditCardFail();
            }
        }
                                
    });
                            
}
                        
function changeCountryISO(){
    var country_iso_a2 = $F('bill_country')
    new Ajax.Request('/service/AjaxRun', 
    { 	//method:'get',
        parameters: {"wsfunc": "ws_change_country_iso","country_iso_a2":country_iso_a2},
        requestHeaders: {Accept: 'application/json'},
        onSuccess: function(transport){
            var json = transport.responseText.evalJSON(true);
            if(json.RETURN){
                                            
                onChangeCountryISOSuccess();
                                            
            }else{
                onChangeCountryISOFail();
            }
        }
                                
    });
}
                        
function getCountryISO(){
                            
                            
    new Ajax.Request('/service/AjaxRun', 
    { 	//method:'get',
        parameters: {"wsfunc":"ws_get_country_iso_a3"},
        requestHeaders: {Accept: 'application/json'},
        onSuccess: function(transport){
            var json = transport.responseText.evalJSON(true);
            if(json.RETURN){
                                            
                onGetCountryISOSuccess(json.country_isoV);
                                            
            }else{
                // onGetCountryISOFail();
            }
        }
                                
    });
}
                        
                        
function onLoadUserCreditData(){
    var card_type = $F('card_type');
    
    var card_number = $F('card_number');
    new Ajax.Request('/service/AjaxRun', 
    { 	//method:'get',
        parameters: {"wsfunc": "ws_load_creditcard","card_type":card_type,"card_number":card_number.toString()},
        requestHeaders: {Accept: 'application/json'},
        onSuccess: function(transport){
            var json = transport.responseText.evalJSON(true);
            if(json.RETURN){
                    
                if(json.msg!='No credit card info'){
                    onLoadUserCreditDataSuccess(json.cardInfo);
                }else{
                    onLoadUserCreditDataFail();
                }
            }
        }//,
        //onFailure: onLoginFail('Something went wrong...')
    });
}

                        
/********************************************************************************/
/*************** rates_public.js ******************************/
/********************************************************************************/
                        
function loadCountrySelection(){
    loadCountryCode();
    initCountrySelection("from_country", "");
    if($("to_country") != null){
    	initCountrySelection("to_country", "");
    }
                            
    $('from_country').observe('change',function(){
        CountryChanged();
    });
    if($("to_country") != null){
	    $('to_country').observe('change',function(){
	        CountryChanged();
	    })
    }
}
                        
function initCountryCode(){
    var country = CountryCodeText.split(";");
    CountryCode=new Array(country.length);
    CountryName=new Array(country.length);
    for(var i=0;i<country.length;i++){
        var xxx = country[i].split(",");
        CountryCode[i] = parseInt(xxx[0]);
        CountryName[i] = xxx[1].strip();
        //alert(CountryCode[i] + "|" + CountryName[i] + "|" );
    }
}
                        
function initCountrySelection(selectObjID, codeObjID){
    if(CountryCode == null){
        initCountryCode();
    }
    // init top conutry list
    var country = TopCountryCodeText.split(";");
    var topCountryCode = new Array(country.length);
    var topCountryName = new Array(country.length);
    for(var i=0;i<country.length;i++){
        var xxx = country[i].split(",");
        topCountryCode[i] = parseInt(xxx[0]);
        topCountryName[i] = xxx[1].strip();
    }
                            
    // get select object and selected code.
    var countrySelect = $(selectObjID);
    var selectCode = 0;
                            
    if(codeObjID == null || codeObjID == ""){
        selectCode = 0;
    }else{
        var countryCode = $(codeObjID);
        var v = countryCode.value
        selectCode = v.substr(1, v.length-1);
    }
                        
    // init top list.
    var selected=0;
                        
    for(i=0;i<topCountryCode.length;i++){
        var x = new Element('option',{'value':topCountryCode[i]+""}).update(topCountryName[i]+" - ("+topCountryCode[i]+")");
                            
        if(topCountryCode[i] == selectCode){
            //alert("top "+x.text);
            selected = i;
        }
        countrySelect.appendChild(x);
    }
    // seperator
    x = new Element('option',{'value':'-----------------------'}).update('-----------------------');
    countrySelect.appendChild(x);
                        
    // init full list
    for(i=0;i<CountryCode.length;i++){
        x= new Element('option',{'value':CountryCode[i]+""}).update(CountryName[i]+" - ("+CountryCode[i]+")");
                            
        if(CountryCode[i] == selectCode && selected==-1){
            //alert(x.text);
            selected = topCountryCode.length+1+i;
        }
        countrySelect.appendChild(x);
    }
    // set selection
    countrySelect.selectedIndex = selected;
}
                    
function CountryChanged(){
    var x = $('from_country').value;
    var y = $('to_country').value;
    if(isNaN(x)){
        alert("Please select a country");
        $('from_country').selectedIndex = 0;
        return false;
    }
    if(isNaN(y)){
        alert("Please select a country");
        $('to_country').selectedIndex = 0;
        return false;
    }
                        
    if ($('from_country').selectedIndex != 0 && $('to_country').selectedIndex  != 0){
        checkRatesC2C();
    }else{
        clearC2CRates();
    }
    return true;
}
                
function checkRatesC2C(){
    var form = $("ratesC2CForm").serialize();
    var para = "wsfunc=ws_getRateC2C&"+form;
                    
    new Ajax.Request('/service/AjaxRun', 
    {
        parameters: para,
        requestHeaders: {Accept: 'application/json'},
        onSuccess: function(transport){
            var json = transport.responseText.evalJSON(true);
            if(json.RETURN){
                showC2CRates(json.rates);
            }
        }
    }
);
}
                
function showC2CRates(rates){
    $('land2land').update('$'+rates.land2land);
    $('land2mobile').update('$'+rates.land2mobile);
    $('mobile2land').update('$'+rates.mobile2land);
    $('mobile2mobile').update('$'+rates.mobile2mobile);
    if($('C2Cnotes') != null){
	    $('C2Cnotes').show();
	    $('C2Cnotes').update('* USD/min <br>* Mobile rates starting from the prices above, actual rates depend on the carriers, please check "phone to phone" for accurate rates');
    }
}
                
function clearC2CRates(){
    $('land2land').update('$0.00');
    $('land2mobile').update('$0.00');
    $('mobile2land').update('$0.00');
    $('mobile2mobile').update('$0.00');
    if($('C2Cnotes') != null){
    	$('C2Cnotes').update();
    }
}
                
function checkRatesP2PForm(){
    var from = $('from_number');
    var to = $('to_number');
                    
    if(!from.present()){
        alert('Please input from number');
        return false;
    }
    if(!to.present()){
        alert('Please input to number');
        return false;
    }
                    
    return true;
}
                
function onSubmitP2PForm(){
    if(checkRatesP2PForm()){
        var from = $('from_number').getValue();
        var to = $('to_number').getValue();
        var para = {'wsfunc':'ws_check_rate','regular_from':from,'regular_to':to};
                        
        new Ajax.Request('/service/AjaxRun', 
        {
            parameters: para,
            requestHeaders: {Accept: 'application/json'},
            onSuccess: function(transport){
                var json = transport.responseText.evalJSON(true);
                var result = null;
                if(json.RETURN){
                    result = '<span style="font-size:24px">$'+json.rate + '</span> USD/min' + '<br/>* Rates accurate';
                }else{
                    //                    result = json.MESSAGE;
                    result = 'No rates found. Please check the phone numbers. <!--If you ar sure the number is correct, please contact us at support@tokiva.com-->';
                }
                showP2PRates(result);
            }
        });
    }
}
                
function showP2PRates(result){
    $('P2Prate').show();
    $('P2Prate').update(result);
}

/********************************************************************************/
/*************** Show return massage information ******************************/
/********************************************************************************/
var ActReturnMsg = Class.create({
    initialize: function(Msg){
        this.Msg = Msg;
    },
    showErrorMsg: function(location){
        $(location).update(this.Msg);
        $(location).className = 'wrong_message';
        $(location).show();
    },
    showSuccessMsg: function(location){
        $(location).update(this.Msg);
        $(location).className = 'ok_message';
        $(location).show();
    }
});


function correctPNG()
{
    if (Prototype.Browser.IE) {
        for(var i=0; i<document.images.length; i++)
        {
            var img = document.images[i];
            var imgName = img.src.toUpperCase();
            if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
            {
                var imgID = (img.id) ? "id='" + img.id + "' " : "";
                var imgClass = (img.className) ? "class='" + img.className + "' " : "";
                var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' ";
                var imgStyle = "display:inline-block;" + img.style.cssText;
                if (img.align == "left") imgStyle = "float:left;" + imgStyle;
                if (img.align == "right") imgStyle = "float:right;" + imgStyle;
                if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle;
                var strNewHTML = "<span "+ imgID + imgClass + imgTitle + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";" + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader" + "(src='" + img.src + "', sizingMethod='scale');\"></span>";
                img.outerHTML = strNewHTML;
                i = i-1;
            }
        }
    }
}
 
