var ratesLoaded = false;
var afterLogin = false;

function bindEventsToRatesList()
{
	// фильтр валют
	$(".filter a").click(function() {
		$(".filter .current").removeClass("current");
		$(this).parent().parent().addClass("current");
		if (this.className == "ps-all")
		{
			$(".rates tr").show();
		}
		else
		{
			$(".rates tr:not(." + this.className + ")").hide();
			$(".rates tr." + this.className).show();
			if (this.className == "ps-SMS")
			{
			    var _html = ""
	            _html += "<select style=\"width: 180px;\" id=\"country_select2\" onchange=\"changeSMSCountryInExchangeTab()\"><option value=\"0\">Не выбрана</option>";
	            for (var a in countries) 
	                if (isCountrySet(a))_html += "<option value=\"" + a + "\"" + (readCookie("obmennik%2Eru%5Fcountry") == a ? " selected=\"selected\" " : "")+ ">" + countries[a] + "</option>";
	            _html += "</select>";
            	
	            $("#sms_countries2").html(_html);
	            changeSMSCountryInExchangeTab();
			    
			}
			
		}
		return false;
	});
	getSMSRates();
    var _html = ""
	_html += "<select style=\"width: 180px;\" id=\"country_select2\" onchange=\"changeSMSCountryInExchangeTab()\"><option value=\"0\">Не выбрана</option>";
	for (var a in countries) 
	if (isCountrySet(a))_html += "<option value=\"" + a + "\"" + (readCookie("obmennik%2Eru%5Fcountry") == a ? " selected=\"selected\" " : "")+ ">" + countries[a] + "</option>";
	_html += "</select>";
           	
	$("#sms_countries2").html(_html);
	changeSMSCountryInExchangeTab();
	// переключалка типов обмена
	$(".exchange-type-switcher2 input").click(function() {
        var curr="all";
        var show_all = true;
        $(".rates tr [class^=ps-]").each(function() 
        { 
            if ($(this).css("display") != "none")
                curr = String($(this).attr("class")).substr(3);
            else
                show_all = false;
        }); 
        if (show_all) curr = "all";
		$(".exchange-type-switcher2").removeClass("UT").removeClass("ST").addClass(this.value);
		$(".rates-tab").load("/exchange.asp?type=" + this.value + "&sc=" + curr, null, function() {
			bindEventsToRatesList();
		});
	});
}

function switchToExchangeTab()
{
    if (String(location.hash).indexOf("sms") != -1)
    {
        location.href = "/";
        return;
	}
	$(".tabs li").removeClass("current-last").removeClass("current");
	$(".tabs .exchange a").parent().addClass("current");
	$(".tab-content").hide();
	$("." + $(".tabs .exchange a").attr("rel")).show();
}

function switchToInOutTab()
{
    if (String(location.hash).indexOf("sms") != -1)
    {
        location.href = "/";
        return;
	}
	$(".tabs li").removeClass("current-last").removeClass("current");
	$(".tabs .inout a").parent().addClass("current");
	$(".tab-content").hide();
	$("." + $(".tabs .inout a").attr("rel")).show();
}

function setCountryOperator()
{
    var country = $("#country_select2").val();
    var operator = $("#operator_select2").val();
    if (country != 0 && operator != 0 && country != "undefined" && operator != "undefined")
    {
        createCookie("obmennik%2Eru%5Fcountry", country, true)
        createCookie("obmennik%2Eru%5Foperator", operator, true);
    }
    
}

function isCountrySet(country_id)
{
    for (var i in tariff)
        if (tariff[i].country_id == country_id) return true;
    return false;
}

function isOperatorSet(operator_id)
{
    for (var i in tariff)
        if (tariff[i].op_id == operator_id) return true;
    return false;
}

function changeSMSCountry()
{
    var temp_array = [];
    var country_id = $("#country_select").val();
    var _html = ""
	_html += "<select id=\"operator_select\" style=\"width: 300px;\" onchange=\"changeSMSOperator()\"><option value=\"0\">Не указан</option>";
	for (var a in operators)
	{
	   
	    if (operators[a]["country_id"] == country_id && isOperatorSet(a)) 
	         temp_array.push(operators[a]["name"]);//_html += "<option value=\"" + a + "\"" + (a == $("#select_operator").val() || readCookie("obmennik%2Eru%5Foperator") == a  ? " selected=\"selected\" " : "") + ">" + operators[a]["name"] + "</option>";
	}
	temp_array.sort()
	for (var i = 0; i < temp_array.length; i++)
	{
	    for (var a in operators)
	    {
	        if (operators[a]["name"] == temp_array[i] && operators[a]["country_id"] == country_id && isOperatorSet(a)) _html += "<option value=\"" + a + "\"" + (a == $("#select_operator").val() || readCookie("obmennik%2Eru%5Foperator") == a  ? " selected=\"selected\" " : "") + ">" + operators[a]["name"] + "</option>";
	    }
	}
	_html += "</select>";
	
	$("#sms_operators").html(_html);
	$("#sms_tariff").html("");
}

function changeSMSCountryInExchangeTab()
{
    var country_id = $("#country_select2").val();
    var _html = ""
	_html += "<select id=\"operator_select2\" style=\"width: 300px;\" onchange=\"changeSMSOperator()\"><option value=\"0\">Не указан</option>";
	for (var a in operators) 
	    if (operators[a]["country_id"] == country_id && isOperatorSet(a)) _html += "<option value=\"" + a + "\"" + (readCookie("obmennik%2Eru%5Foperator") == a  ? " selected=\"selected\" " : "") + ">" + operators[a]["name"] + "</option>";
	_html += "</select>";
	
	$("#sms_operators2").html(_html);
}

function changeSMSCurrency()
{
    $("#reserve2").html(_getReserveString($("#to2").val(), "UT"));
    $("#target_account2").val(String($("#to2").val()).substring(2,3));
    if (!(readCookie("obmennik%2Eru%5Fsms%5F" + $("#to2").val()) in {"undefined":1,"null":1} )) $("#target_account2").val(readCookie("obmennik%2Eru%5Fsms%5F" + $("#to2").val()));
    changeSMSOperator();    
}

function changeSMSOperator()
{
/*
    var operator_id = $("#operator_select").val();
    var _html = ""
	_html += "<form name=\"radioForm\"><table style=\"text-align: center\"><col width=15% /><col width=35% /><col width=35% /><tr><th>Номер</th><th>Стоимость SMS</th><th>Получаете</th></tr>";
	var to = String($("#to2").val());
	var target_value;
	var i = 0;
	for (var a in tariff)
	{
	    target_value = sms_rates[to].source_master == 1 ? Math.floor((tariff[a]["partner_income"] * sms_rates[to].rate) * 100) / 100 : Math.floor((tariff[a]["partner_income"] / sms_rates[to].rate) * 100) / 100
	    if (tariff[a]["operator_id"] == operator_id) {i++;_html += "<tr><td style=\"padding: 0px;\"><input style=\"float: left;\" type=\"radio\" name=\"tariff_radio\" id=\"tariff_radio" + i + "\" value=\"" + a + "\"" + (a == $("#select_number").val() ? " checked=\"checked\" " : "") + "><label style=\"font-size: 13px;\" for=\"tariff_radio" + i + "\">" + String(a).split("-")[0] + "</label></td><td style=\"padding: 0px;\">" + tariff[a]["price_abonent"] + " " + (tariff[a]["abonent_currency"] != "rur" ? tariff[a]["abonent_currency"] : "") + "</td><td style=\"padding: 0px;\">" + target_value + " " + to + "</td></tr>";}
	}
	// если радиобаттон (номер телефона) всего один, то при получении значения группы, состоящей из одного элемента, возникают проблемы. Поэтому добавляем еще один фиктивный и дизэблим его   
	if (i == 1) _html += "<tr style=\"display: none;\"><td colspan=\"3\"><input style=\"\" type=\"radio\" name=\"tariff_radio\" id=\"tariff_radio1\" value=\"null\"></td></tr>" 
	_html += "</table></form>";
	
	if (i != 0) $("#sms_tariff").html(_html);
*/
}

function backSMS()
{
    //$(".exch-tab2").html("");
    //switchToSMSTab();
    goToSMS(true);
}

var timeoutId = null;

function getSMSRates()
{
	$.getJSON('/service-routine/_services/get_sms_page_data.asp',
			function(data) {
				sms_rates = data.sms_rates;
				countries = data.countries;
				operators = data.operators;
				tariff	  =	data.tariff;
				updateSSMTab();
			}
	);
}

function smsTabBindData(data)
{
	//
	_rates = data.rates;
	_balances = data.balances;
	// меняем блок результир валюты
	var _type = "UT";
	var selectedVal = $("#to2").val();
	if (typeof(gotoExchangeData) != "undefined") selectedVal = gotoExchangeData[1];
	var _html = ["<select name='to2' id='to2' style='width: 180px' class='styled' onchange='changeSMSCurrency()'>"];
	data = data.order;
	rates = _rates;
	//
	for (var i = 0, l = data.length; i < l; i++)
	{
		if (typeof(rates[_type][data[i].id]) != "undefined" && !rates[_type][data[i].id].d)
		{
			_html[_html.length] = "<option value='" + data[i].id + "'" + (selectedVal == data[i].id || (typeof val != "undefined" && val == data[i].id) ? " selected " : "") +  ">" + currencyFullName[data[i].id];
		}
	}
	_html[_html.length] = "</select>";
	$("#to2").parent().html(_html.join(""));
	//
	var _curr = $("#to2").val();
	$("#reserve2").html(_getReserveString($("#to2").val(), "UT"));
	if (typeof flag == "undefined")
		$("#target_account2").val(String($("#to2").val()).substring(2,3));
	else
	{
		changeSMSCountry();
		changeSMSOperator();
	}
	changeSMSCurrency();
	//renderExchangeInfoBlock(_curr);
	exchangeCoursesLoaded = true;
}

function updateSSMTab()
{
	if(timeoutId != null)
	{
		window.clearTimeout(timeoutId);
		timeoutId = null;
	}
	
	//if(sms_rates == null){ return; }
	/*
	$(".tabs li").removeClass("current");
	$(".tabs .exchange2 a").parent().addClass("current");
	$(".tab-content").hide();
	$("." + $(".tabs .exchange2 a").attr("rel")).show();
	*/
	
	var _html = ""
	_html += "<select style=\"width: 180px;\" id=\"country_select\" onchange=\"changeSMSCountry()\"><option value=\"0\">Не выбрана</option>";
		
	for (var a in countries) 
	{		
		if (isCountrySet(a))_html += "<option value=\"" + a + "\"" + (a == $("#select_country").val() || readCookie("obmennik%2Eru%5Fcountry") == a ? " selected=\"selected\" " : "")+ ">" + countries[a] + "</option>";
	}	
	_html += "</select>";
	
	$("#sms_countries").html(_html);
	
	changeSMSCountry();
	
	
	
}

function switchToSMSTab(val, flag)
{
    var _source_curr = "SMS";
	payer = whoPayFindersFee(_source_curr) != null;
	
	if (_source_curr in _targetCurrCache) // если уже запрашивали, берем из кеша
	{
		
		smsTabBindData(_targetCurrCache[_source_curr]);
		/*
		renderExchangeBlock(_targetCurrCache[_source_curr]);
		if (isFromExchangeRates)
		{
			fillFormFromExchangeRatesTab();
		}
		*/
	}
    else
	{
		$.getJSON('/service-routine/_services/get_target_currs.asp',
			{ id: _source_curr },
			function(data) {
				_targetCurrCache[_source_curr] = data;
				smsTabBindData(data);				
			}
		);
	}
    if (location.hash > "" && !flag)
    {
        location.href = "/SMS/";
        return;
	}
	
	$(".tabs li").removeClass("current-last").removeClass("current");
	$(".tabs .exchange2 a").parent().addClass("current");
	$(".tab-content").hide();
	$("." + $(".tabs .exchange2 a").attr("rel")).show();
	if(sms_rates == null)
	{
		getSMSRates();
		timeoutId = window.setTimeout(updateSSMTab , 500);
	} 
	else
	{
		updateSSMTab();	
	}
}

$(function() {
		// переключение табов
        
		$(".tabs .exchange a").click(function() {
			switchToExchangeTab();
			return false;
		});
		
		$(".tabs .exchange2 a").click(function() {
			switchToSMSTab();
			return false;
		});
		
		$(".tabs .inout a").click(function() {
			switchToInOutTab();
			return false;
		});
		
		// загрузка курсов валют
		$(".tabs .rates a").click(function() {
			 $(".tabs li").removeClass("current-last").removeClass("current");
			if ($(".tabs li").length == 4)
			{
			    $(this).parent().addClass("current-last");
			}
			else 
			{
			    $(this).parent().addClass("current");
			}
			$(".tab-content").hide();
			
			if (ratesLoaded)
			{
				$("." + $(this).attr("rel")).show();
			}
			else
			{
				$("." + $(this).attr("rel")).show().load("/exchange.asp?type=UT" + (pid > 0 ? "&pid=" + pid : ""), null, function() {
					ratesLoaded = true;
					bindEventsToRatesList();
				});
			}
			return false;
		});

		// события кнопки логина
        $("#dologin")
			.hover(
				function() { this.src = "/images/btn_enter_h.png"; },
				function() { this.src = "/images/btn_enter.png"; }
			)
			
			.click(
				function() {
					//if ($("#login").val() && $("#password").val())
					{
						$.post(
							"/members/default.asp",
							{
								member_email: $("#login").val(),
								member_password: $("#password").val(),
								validation_code: $("input[name='validation_code']").val()
							},
							function(data) {
							    
								if (/^1/.test(data))
								{
									afterLogin = true;
									$(".login-form").after(data.substr(1));
									$(".login-form").remove();
									var reg=/(\d+)/ 
                                    var arr=reg.exec(data.split("<br />")[2])  
                                    var discount_sms = parseInt(arr[0]);
                                    $("#my_sms_discount").html(discount_sms);
									if ($my("btn-next1"))
									{
										$my("btn-next1").onclick();
									}
									if (document.radioForm2) showNum(0, $("#login").val(), $("#password").val())
								}
								else
								{
									$(".login-error-area").html(data);
									$("#login-error").fadeIn();
								}
							}
						);
					}
					return false;
				}
			);
});

// переход к выбранному обмену
function submitExchange(suffix, type)
{
	bindExchangeParameters(suffix);
	if ("exchange" == type)
	{
		document.forms["exchange-form"].action = "/exchange/{0}/{1}/{2}/".format(sourceCurrency, targetCurrency, $radio("type"));
	}
	else
	{
		document.forms["exchange-form"].action = "/{2}/{0}/{1}/".format(sourceCurrency, targetCurrency, type);
	}
	$("#source_value").val($("#source_value" + suffix).val());
	$("#target_value").val($("#target_value" + suffix).val());
	$("#from").val(sourceCurrency);
	$("#to").val(targetCurrency);
	document.forms["exchange-form"].submit();
}

function getBrowserInfo() {
 var t,v = undefined;
 if (window.opera) t = 'Opera';
 else if (document.all) {
  t = 'IE';
  var nv = navigator.appVersion;
  var s = nv.indexOf('MSIE')+5;
  v = nv.substring(s,s+1);
 }
 else if (navigator.appName) t = 'Netscape';
 return {type:t,version:v};
}
 
function addToFavorite(a){
 var url = window.document.location;
 var title = window.document.title;
 var b = getBrowserInfo();
 if (b.type == 'IE' /*&& 7 > b.version && b.version >= 4*/) window.external.AddFavorite(url,title);
 else if (b.type == 'Opera') {
  a.href = url;
  a.rel = "sidebar";
  a.title = url+','+title;
  return true;
 }
 else if (b.type == "Netscape") window.sidebar.addPanel(title,url,"");
 else alert("Нажмите CTRL-D, чтобы добавить страницу в закладки.");
 return false;
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function createCookie(name, value, days, path) {
	var expires = "", _path = "/";
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
	//	var expires = "; expires="+date.toGMTString();
		var expires = "; expires=Thu, 31 Dec 2037 21:00:00 GMT";
	}
	document.cookie = name+"="+value+expires+"; path=" + _path;
}
