var country_select;
var countrys;
var nums_active = false;

window.onload = function(){
	countrys = document.forms.countrys.flags;
	country_select = countrys.value;
	setInterval(checkCountry, 500);
	initNums();
}

function checkCountry(){
	if ( countrys.value==country_select ) return;
	
	country_select = countrys.value;

	country_index = 0;

	for(i=0;i<countrys.length;i++)
	{
		if(countrys[i].value == countrys.value)
		{
			country_index = i;
			break;
		}
	}

	document.getElementById('flags').className = 'ico'+convert(countrys[i].text);

	selectCountry(countrys.value);
}

function initNums(){
	num = 1;
	while ( document.getElementById('nums_'+num) ){
		addNumEvent(num);
		++num;
	}
}
function addNumEvent(num){
	if ( document.getElementById('nums_'+num).className=='active' ){
		nums_active = num;
	}
	
	document.getElementById('nums_'+num).onclick = function(){
		if ( nums_active ){
			document.getElementById('nums_'+nums_active).className = '';
		}
		document.getElementById('nums_'+num).className = 'active';
		nums_active = num;

		links = document.getElementById('nums_'+num).getElementsByTagName('a');
		addr = links[0].href.split('?', 2);
		addr = addr[1].split('&');
		for ( i=0;i<addr.length;++i ){
			temp = addr[i].split('=', 2);
			switch ( temp[0] ){
				case 'country_id':
					country_id = temp[1];
					break;
				case 'num':
					phone_num = temp[1];
					break;
				case 'pref':
					phone_prefix = temp[1];
					break;
			}
		}
		
		clearTarifTable();
		getAjaxPrices(country_id, phone_num, phone_prefix);

		return false;
	}
}

function addCountryListener(id){
	id.onclick = function(){ return selectCountry(id); }
}

var ukr_pension_text = '<br><br>Тариф в гривнах с учетом НДС. Дополнительно удерживается сбор в пенсионный фонд в размере 7,5% от стоимости услуги без учета НДС.';

var ifree_text = '<br><br>Услуга действительна для абонентов всех национальных GSM Операторов Украины. Услуги предоставляет компания ООО "Айфри Украина". Адрес: 03124, г. Киев, ул. Н. Василенко 7А. Служба поддержки абонентов, тел: 0445457703. Услуга предоставляется только для совершеннолетних.';

var _2838_text = '<br><br>Стоимость исходящих смс: 0.00 руб.<br><br>Стоимость входящих смс:';

var mts_text = '<font color="#0582A7">*</font>&nbsp;Стоимость доступа к услугам контент-провайдера устанавливается Вашим оператором. Подробную информацию можно узнать в разделе «Услуги по коротким номерам»<br>на сайте <a href="http://www.mts.ru" target="_blank">www.mts.ru</a> или обратившись в контактный центр по телефону 8 800 333 0890 (0890 для абонентов МТС)';

var gb_text = '<br><br>Post address: Birmingham NEC, 4200 Waterside Centre, Birmingham B37 7YN<br>Phone number: 0121 717 4836';

var _770860_text = '<br><br>Стоимость исходящих смс: 0.00 руб.<br><br>Стоимость входящих смс:';
var _770861_text = 'Стоимость входящих смс:';
var _770862_text = 'Стоимость входящих смс:';
var _770863_text = 'Стоимость входящих смс:';
var _770864_text = 'Стоимость входящих смс:';
var _770865_text = 'Стоимость входящих смс:';
var _770866_text = 'Стоимость входящих смс:';
var _770867_text = 'Стоимость входящих смс:';
var _770868_text = 'Стоимость входящих смс:';
var _770869_text = 'Стоимость входящих смс:';
var _770870_text = 'Стоимость входящих смс:';

function updateCountryHeadText()
{
	phone_num = '';
  document.getElementById('mts_mess').innerHTML = "";
  
	for(num = 1 ; ; num++)
	{
		elt = document.getElementById('nums_'+num);

		if(!elt)
			break;

		if(elt.className != 'active')
			continue;

		links = document.getElementById('nums_'+num).getElementsByTagName('a');
		addr = links[0].href.split('?', 2);
		addr = addr[1].split('&');

		for ( i=0;i<addr.length;++i )
		{
			temp = addr[i].split('=', 2);

			switch ( temp[0] )
			{
				case 'country_id':
					country_id = temp[1];
					break;
				case 'num':
					phone_num = temp[1];
					break;
				case 'pref':
					phone_prefix = temp[1];
					break;
			}
		}

		break;
	}

	head_text = 'Таблица тарифов';
	foot_text = '';
	
	col1_text = 'Цена за 1 СМС<br>без НДС';
	col2_text = 'Цена за 1 СМС<br>с НДС';
	
	col1_display = '';
	col2_display = '';

	for(i=0;i<countrys.length;i++)
	{
		if(countrys[i].value == countrys.value)
		{
			if(countrys[i].innerHTML == 'Россия')
			{
				document.getElementById('mts_mess').innerHTML = mts_text;
        if(phone_num == '2838')
					{ head_text = _2838_text; }
				else if(phone_num == '770860')
					{ head_text = _770860_text; }
				else if(phone_num == '770861')
					{ head_text = _770861_text; }
				else if(phone_num == '770862')
					{ head_text = _770862_text; }
				else if(phone_num == '770863')
					{ head_text = _770863_text; }
				else if(phone_num == '770864')
					{ head_text = _770864_text; }
				else if(phone_num == '770865')
					{ head_text = _770865_text; }
				else if(phone_num == '770866')
					{ head_text = _770866_text; }
				else if(phone_num == '770867')
					{ head_text = _770867_text; }
				else if(phone_num == '770868')
					{ head_text = _770868_text; }
				else if(phone_num == '770869')
					{ head_text = _770869_text; }
				else if(phone_num == '770870')
					{ head_text = _770870_text; }
			}
			else if(countrys[i].innerHTML == 'Украина')
			{
				head_text += ukr_pension_text;

				if(	phone_num == '4443' ||
					phone_num == '4444' ||
					phone_num == '4445' ||
					phone_num == '4446' ||
					phone_num == '4447' ||
					phone_num == '3351' ||
					phone_num == '4448' ||
					phone_num == '4449' ||
					phone_num == '3353' ||
					phone_num == '4161' ||
					phone_num == '3354')
				{
					foot_text += ifree_text;					
				}
			}
			else if(countrys[i].innerHTML == 'Беларусь')
			{
				col1_text = 'Цена за 1 СМС<br>без налогов';
				col2_text = '';
				
				col1_display = '';				
				col2_display = 'none';
			}
			else if(countrys[i].innerHTML == 'Великобритания')
			{
				foot_text += gb_text;
			}

			break;
		}
	}

	document.getElementById('table_head').innerHTML = head_text;
	document.getElementById('table_foot').innerHTML = foot_text;
	
	document.getElementById('price_col1').innerHTML = col1_text;
	document.getElementById('price_col2').innerHTML = col2_text;
	
	document.getElementById('price_col1').style.display = col1_display;
	document.getElementById('price_col2').style.display = col2_display;
}

function selectCountry(id){
	document.getElementById('nums_list').innerHTML = '<li>Загрузка&#133;</li>';
	getAjaxNums(id);
	clearTarifTable();
	updateCountryHeadText();
	return false;
}

function clearTarifTable(without_load){
	var table = document.getElementById('prices').getElementsByTagName('table')[0];
	var trs = table.getElementsByTagName('tr').length;
	for ( i=1;i<trs;++i ){
		table.deleteRow(1);
	}
	
	if ( !without_load ){
		addTarifTableRow('<span>Загрузка&#133;</span>', '', '');
	}
}

function addTarifTableRow(ceil1, ceil2, ceil3, className, insertNum){
	if ( !className ){
		className = 'row1';
	}
	if ( !insertNum ){
		insertNum = 0;
	}
	var table = document.getElementById('prices').getElementsByTagName('table')[0];
	table = table.getElementsByTagName('tbody')[0];
	var newRow=table.insertRow(insertNum);
	newRow.className = className;  
	var newCell1 = newRow.insertCell(0);
	newCell1.innerHTML = ceil1;
	var newCell2 = newRow.insertCell(1);
	newCell2.innerHTML = ceil2;
	var newCell3 = newRow.insertCell(2);
	newCell3.innerHTML = ceil3;
	
	if(ceil3 == '#none#')
		newCell3.style.display = 'none';
}

function loadNums(text){
	document.getElementById('nums_list').innerHTML = text;
	nums_active = false;
	initNums();
	
	if ( nums_active && nums_active!=1 ){
		document.getElementById('nums_'+nums_active).className = '';
	}
	document.getElementById('nums_1').className = 'active';
	nums_active = 1;
	
	links = document.getElementById('nums_1').getElementsByTagName('a');
	addr = links[0].href.split('?', 2);
	addr = addr[1].split('&');

	for ( i=0;i<addr.length;++i ){
		temp = addr[i].split('=', 2);
		switch ( temp[0] ){
			case 'country_id':
				country_id = temp[1];
				break;
			case 'num':
				phone_num = temp[1];
				break;
			case 'pref':
				phone_prefix = temp[1];
				break;
		}
	}
	
	clearTarifTable();
	getAjaxPrices(country_id, phone_num, phone_prefix);
}

function getAjaxNums(country_id){
	try{
		ajaxRequest = new XMLHttpRequest();
	} catch (e){
		try{
			ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try{
				ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e){
				return false;
			}
		}
	}
	
	ajaxRequest.onreadystatechange = function(){
		if(ajaxRequest.readyState == 4){
			loadNums( ajaxRequest.responseText );
		}
	}
	
	ajaxRequest.open('GET', 'ajaxo.php?mode=tarif_nums&r='+Math.random()+'&country_id='+country_id, true);
	ajaxRequest.send(null);
}

function getAjaxPrices(country_id, num, prefix){
	try{
		ajaxRequest = new XMLHttpRequest();
	} catch (e){
		try{
			ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try{
				ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e){
				return false;
			}
		}
	}
	
	ajaxRequest.onreadystatechange = function(){
		if(ajaxRequest.readyState == 4){
			var text = ajaxRequest.responseText;
			text = text.split('</tr>');
			clearTarifTable(true);
			for ( var i=0;i<text.length-1;++i ){
				td_text = text[i].replace(/<tr class="row\d">/, '').replace(/<\/td>/g, '').split('<td>');
				addTarifTableRow(td_text[1], td_text[2], td_text[3], (i%2 ? 'row2' : 'row1'), i);
			}
		}
	}
	
	ajaxRequest.open('GET', 'ajaxo.php?mode=tarif_prices&r='+Math.random()+'&country_id='+country_id+'&num='+num+'&pref='+prefix, true);
	ajaxRequest.send(null);

	updateCountryHeadText();
}

var rusChars = new Array('А','Б','В','Г','Д','Е','Ё','Ж','З','И','Й','К','Л','М','Н','О','П','Р','С','Т','У','Ф','Х','Ч','Ц','Ш','Щ','Э','Ю','Я','Ы','Ъ','Ь',
    'а','б','в','г','д','е','ё','ж','з','и','й','к','л','м','н','о','п','р','с','т','у','ф','х','ч','ц','ш','щ','э','ю','\я','ы','ъ','ь');
var transChars = new Array('A','B','V','G','D','E','Jo','Zh','Z','I','J','K','L','M','N','O','P','R','S','T','U','F','H','Ch','C','Sh','Csh','E','Ju','Ja','Y','','',
    'a','b','v','g','d','e','jo','zh','z','i','j','k','l','m','n','o','p','r','s','t','u','f','h','ch','c','sh','csh','e','ju','ja','y','','');
var from = "";

function convert(from){
	var to = "";
	var len = from.length;
	var character, isRus;
	for(i=0; i < len; i++){
		character = from.charAt(i,1);
		isRus = false;
		for(j=0; j < rusChars.length; j++){
			if(character == rusChars[j]){
				isRus = true;
				break;
			}
		}
		to += (isRus) ? transChars[j] : character;
	}
	return to;
}
