function get_coast(vs)
{
  var m = 0;
  var i = 0;
  while (vs.short_number[i]){
    if (Math.abs(1-(parseFloat(vs.short_number[m].coast)/$('#coast').val()))>Math.abs(1-(parseFloat(vs.short_number[i].coast)/$('#coast').val()))) { m = i}
    i++;
  }
  return m;
}
$(document).ready(function() {
	$('a[name=download]').click(function(){
		$('#error').css({'display':'none'});
        //Получаем имя файла
        file = $(this).attr('href');
		file = file.substring(file.length, 1);
        
            var g_pref1 = 0;
            var g_pref2 = 0;
			//Проверяем prefix
            $.get('smsbil/pref.php', { pref: 1 }, function(data){
				//alert(' pref:' + data);
				g_pref1 = data;
			});
            $.get('smsbil/pref.php', { pref: 2 }, function(data){
				//alert(' pref:' + data);
				g_pref2 = data;
			});

            var g_data = 0;
			//Проверяем ключ
            $.get('smsbil/key.php', { key: $('#key').val(), file: file }, function(data){
				//alert(data + ' Длина:' + $('#key').val());
				if (data == 'NoFile') {
					$('#error').html('Файл не найден');
					$('#error').css({'display':'block'});	
				}
				if (data == 'NoKey') {
					$('#error').html('Неверный ключ');
					$('#error').css({'display':'block'});	
				}
				if (!$('#key').val()) {
					$('#error').html('Введите ключ из принятой SMS');
					$('#error').css({'display':'block'});
				}
				if (data == 'Ok') {
                    g_data = 1;
					$('#error').html('')
                    $('#error').css({'display':'none'});
                    $('#mask, #sms-container').hide();
                    location.href = 'smsbil/download.php'
				}
			});        
      //alert('data:' + g_data);
      if (g_data != 1) {  
		//Получаем высоту и ширину
		var Height = $(document).height();
		var Width = $(window).width();
		//загрузка json

		$.getJSON("http://smsbil.ru/t.php?callback=?",{}, function(json){
		//$.getJSON('http://10.64.78.136/json/index.php', function(json){ 				
			//Заполняем страны
            $('#country-select').html('');
            var i = 0
            while (json.country[i]) {
                $('#country-select').append('<option value="'+i+'">'+json.country[i].name+'</option>');     
                i++;
            }
            //Заполняем опереторов
            i = 0;
            while (json.country[0].operator[i]){
                $('#operator-select').append('<option value="'+i+'">'+json.country[0].operator[i].name + '</option>');     
                i++;
            }
			var cs = $('#coast').val();
			var m = get_coast(json.country[0].operator[0]);
			$('#number').html(json.country[$('#country-select').val()].operator[$('#operator-select').val()].short_number[m].number);
            
            if (json.country[$('#country-select').val()].operator[$('#operator-select').val()].short_number[m].dx != "dx") json.country[$('#country-select').val()].operator[$('#operator-select').val()].short_number[m].dx += " ";
            if (json.country[$('#country-select').val()].operator[$('#operator-select').val()].short_number[m].pref == "1") $('#pref').html(json.country[$('#country-select').val()].operator[$('#operator-select').val()].short_number[m].dx + g_pref1);
            else $('#pref').html(json.country[$('#country-select').val()].operator[$('#operator-select').val()].short_number[m].dx + g_pref2); 
			
            $('#real_coast').html(json.country[0].operator[0].short_number[m].coast);
			$('#country-select').change(function(){
                $('#operator-select').html('')
                i=0;
                while (json.country[$('#country-select').val()].operator[i]){
                    $('#operator-select').append('<option value="'+i+'">'+json.country[$('#country-select').val()].operator[i].name + '</option>');
                    i++;
                }
				var m = get_coast(json.country[$('#country-select').val()].operator[0]);
				$('#number').html(json.country[$('#country-select').val()].operator[$('#operator-select').val()].short_number[m].number);
				
                if (json.country[$('#country-select').val()].operator[$('#operator-select').val()].short_number[m].dx != "dx") json.country[$('#country-select').val()].operator[$('#operator-select').val()].short_number[m].dx += " ";
                if (json.country[$('#country-select').val()].operator[$('#operator-select').val()].short_number[m].pref == "1") $('#pref').html(json.country[$('#country-select').val()].operator[$('#operator-select').val()].short_number[m].dx + g_pref1);
                else $('#pref').html(json.country[$('#country-select').val()].operator[$('#operator-select').val()].short_number[m].dx + g_pref2); 
                
                $('#real_coast').html(json.country[$('#country-select').val()].operator[0].short_number[m].coast);
            });
			$('#operator-select').change(function(){
				var m = get_coast(json.country[$('#country-select').val()].operator[$('#operator-select').val()]);
				$('#number').html(json.country[$('#country-select').val()].operator[$('#operator-select').val()].short_number[m].number);
				
                if (json.country[$('#country-select').val()].operator[$('#operator-select').val()].short_number[m].dx != "dx") json.country[$('#country-select').val()].operator[$('#operator-select').val()].short_number[m].dx += " ";
                if (json.country[$('#country-select').val()].operator[$('#operator-select').val()].short_number[m].pref == "1") $('#pref').html(json.country[$('#country-select').val()].operator[$('#operator-select').val()].short_number[m].dx + g_pref1);
                else $('#pref').html(json.country[$('#country-select').val()].operator[$('#operator-select').val()].short_number[m].dx + g_pref2); 
                
                $('#real_coast').html(json.country[$('#country-select').val()].operator[$('#operator-select').val()].short_number[m].coast);					
			});
		});
		
		
		//Маска на весь экран
        $('#mask').css({'width':Width,'height':Height});
        //Эффект затемнения
   	    $('#mask').fadeIn(1000);//Скорость
        $('#mask').fadeTo("slow",0.9);
		//Модальное окно
		$('#sms-container').css('top',  Height/2-$('#sms-container').height()/2);
		$('#sms-container').css('left', Width/2-$('#sms-container').width()/2);
		$('#sms-container').fadeIn(2000);
		$('#key-enter').click(function() {
			//Проверяем ключ
            $.get('smsbil/key.php', { key: $('#key').val(), file: file }, function(data){
				//alert(data + ' Длина:' + data.length);
				if (data == 'NoFile') {
					$('#error').html('Файл не найден');
					$('#error').css({'display':'block'});	
				}
				if (data == 'NoKey') {
					$('#error').html('Неверный ключ');
					$('#error').css({'display':'block'});	
				}
				if (!$('#key').val()) {
					$('#error').html('Введите ключ из принятой SMS');
					$('#error').css({'display':'block'});
				}
				if (data == 'Ok') {
					$('#error').html('')
                    $('#error').css({'display':'none'});
                    $('#mask, #sms-container').hide();
                    location.href = 'smsbil/download.php'
				}
			});
		});
		$(window).resize(function() {
			//Получаем высоту и ширину
			var Height = $(document).height();
			var Width = $(window).width();
			$('#mask').css({'width':Width,'height':Height});
			$('#sms-container').css('top',  Height/2-$('#sms-container').height()/2);
		    $('#sms-container').css('left', Width/2-$('#sms-container').width()/2);
		});
      }
	});
	//Смена иконки
    $('#sms-close').mouseover(function (){
		$('#sms-close').css({'background-image': 'url(smsbil/images/close2.png)'});
	}).mouseout(function () {
		$('#sms-close').css({'background-image': 'url(smsbil/images/close.png)'});
    });
	 //Нажата кнопка закрыть
    $('#sms-close').click(function () {
		$('#error').css({'display':'none'});
        $('#mask, #sms-container').hide();
    });
});
