
	// {{{ блок обмена
	var isButtonClick = 0;
	var currStep = 1;
	var _targetCurrCache = {};
	var _rates = null;
	var _balances = null;
	var exchangeCoursesLoaded = sellbuyCoursesLoaded = false;	
	
	function checkStep()
	{
	  
	   var step = document.location.hash;
	   if (!document.getElementById("login") && step == "#authorize") step="#shownum";
	   //alert(step + " " + currStep);
	   switch(step)
	   {
	        case "#main":
	        case "":
	            if (currStep != 1 || isButtonClick) goToStep1();
	            break;
	        case "#calculate":
	            if (isButtonClick)
	                goToStep2();
	            else if (currStep != 2)
	            {
	                if (currStep == 1 && isButtonClick)    
	                    goToStep2();
	                else if (currStep == 3)
	                     goToStep2();
	            }
	            break;
	        case "#smsback":
	            if (isButtonClick)
	                goToSMS(true);
	            else if (currStep != 2)
	            {
	                if (currStep == 1 && isButtonClick)    
	                    goToSMS(true);
	                else if (currStep == 3)
	                    goToSMS(true);
	            }
	            break;
	         case "#numback":
	            if (isButtonClick)
	                showNum();
	            else if (currStep != 2)
	            {
	                if (currStep == 1 && isButtonClick)    
	                    showNum();
	                else if (currStep == 3)
	                    showNum();
	            }
	            break;
	        case "#shownum":
	            if (isButtonClick)
	                showNum();
	            else if (currStep != 3)
	            {
	                if (currStep == 2 && isButtonClick)    
	                    showNum();
	                else if (currStep == 4)
	                     showNum();
	            }
	            break;
	        case "#authorize":
	            if (isButtonClick)
	                showAuthorize();
	            else if (currStep != 3)
	            {
	                if (currStep == 2 && isButtonClick)    
	                    showAuthorize();
	                else if (currStep == 4)
	                     showAuthorize();
	            }
	            break;
	        case "#createsms":
	            if (isButtonClick)
	                goToSMS();
	            else if (currStep != 3)
	            {
	                if (currStep == 2 && isButtonClick)    
	                    goToSMS();
	                else if (currStep == 4)
	                     goToSMS();
	            }
	            break;
	        case "#confirm":
	            if (isButtonClick)
	                goToStep3();
	            else if (currStep != 3)
	            {
	                if (currStep == 2 && isButtonClick)    
	                    goToStep3();
	                else if (currStep == 4)
	                     goToStep3();
	            }
	            break;
	        case "#create":
	            if (isButtonClick)
	                goToStep4();
	            else if (currStep != 4)
	            {
	                if (currStep == 3 && isButtonClick)    
	                    goToStep4();
	            }
	            break; 
	        case "#sms":
	            if (isButtonClick)
	                goToSMS2();
	            else if (currStep != 4)
	            {
	                if (currStep == 3 && isButtonClick)    
	                    goToSMS2();
	            }
	            break;    
	   }
	   
	}
	
	function setFlag()
	{
	    setTimeout(function() {}, 10)
	    isButtonClick = 1;
	}
	
	// событие смены исходной валюты
	function sourceCurrency_OnChange()
	{
		var _source_curr = sourceCurrency = (gotoExchangeData && goToExchangeFromQuery ? gotoExchangeData[0] : $("#from").val());		
		
		payer = whoPayFindersFee(_source_curr) != null;
		if (_source_curr in _targetCurrCache) // если уже запрашивали, берем из кеша
		{
			renderExchangeBlock(_targetCurrCache[_source_curr]);
			if (isFromExchangeRates)
			{
				fillFormFromExchangeRatesTab();
			}
		}
		else // заправшиваем через ajax
		{
			$.getJSON('/service-routine/_services/get_target_currs.asp',
				{ id: _source_curr },
				function(data) {
					_targetCurrCache[_source_curr] = data;
					renderExchangeBlock(data);
					exchangeCoursesLoaded = true;
					if (isFromExchangeRates)
					{
						fillFormFromExchangeRatesTab();
					}
					
					if (goToExchangeFromQuery)
					{
						gotoExchangeForm(gotoExchangeData[0], gotoExchangeData[1], gotoExchangeData[2]);
						goToExchangeFromQuery = false;
					}
				}
			);
		}
	}

	// событие смены результирующей валюты
	function targetCurrency_OnChange()
	{
		var _curr = targetCurrency = $("#to").val();
		renderExchangeInfoBlock(_curr);
	}
	
	// отрисовка выпадающего списка результирующих валют
	function redrawTargetCurrDropDown(data, rates)
	{
		var _type = $("input[name='exchange-type']").val();//$radio("exchange-type");
		if (null == _type)
		{
			_type = "UT";
		}
		var selectedVal = $("#to").val();
        if (typeof(gotoExchangeData) != "undefined") selectedVal = gotoExchangeData[1];
		var disabled = true;
		var _html = ["<select name='to' id='to' class='styled'>"];
		for (var i = 0, l = data.length; i < l; i++)
		{
			if (typeof(rates[_type][data[i].id]) != "undefined" /*&& !rates[_type][data[i].id].d*/)
			{
				if(!rates[_type][data[i].id].d)
				{
					disabled = false;
				}
				_html[_html.length] = "<option value='" + data[i].id + "'" + (selectedVal == data[i].id ? " selected " : "") +  ">" + currencyFullName[data[i].id];
			}
		}
		_html[_html.length] = "</select>";
		$("#to").parent().html(_html.join(""));
		//if(disabled){ window.location.href = "http://www.obmennik.ru/"}
		$("#to").attr( {"disabled" : disabled} );
	}
	
	// перерисовка блока обмена
	function renderExchangeBlock(data)
	{
	    
		_rates = data.rates;
		_balances = data.balances;
		// меняем блок результир валюты
		redrawTargetCurrDropDown(data.order, _rates);
		
		$("#to").change(targetCurrency_OnChange);
		
		var _curr = $("#to").val();
		
		renderExchangeInfoBlock(_curr);
	}
	
	// перерисовка переключателя типов обмена и информации об обмене
	var isFirstRender = false;
	function renderExchangeInfoBlock(target_curr)
	{
		// {{{ проверяем тип обмена
		$("#ut_access").html("");
		$("#st_access").html("");
		if ((_rates["UT"][target_curr] && _rates["UT"][target_curr].d) || (_rates["ST"][target_curr] && _rates["ST"][target_curr].d))
		{
			if (_rates["UT"][target_curr].d) // UT disabled?
			{
				$("#exchange-type1").attr("disabled", "disabled");
				$("#ut_access").html("(недоступен)");
				
				$("#exchange-type2").attr("disabled", "");
				if (!isFirstRender)
				{
					$("#exchange-type1").attr("checked", "");
					$("#exchange-type2").attr("checked", "checked");
				}
			}
			if (_rates["ST"][target_curr].d) // maybe ST disabled?
			{
				$("#exchange-type2").attr("disabled", "disabled");
				$("#st_access").html("(недоступен)");
				
				$("#exchange-type1").attr("disabled", "");
				if (!isFirstRender)
				{
					$("#exchange-type2").attr("checked", "");
					$("#exchange-type1").attr("checked", "checked");
				}
			}
		}
		else
		{
			$("#exchange-type1").attr("disabled", "");
			$("#exchange-type2").attr("disabled", "");
			$("#exchange-type2").attr("checked", "");
			if (!isFirstRender)
			{
				$("#exchange-type1").attr("checked", "checked");
			}
		}
		// }}}
		
		// {{{ rates, min, max
		var _source_curr = $("#from").val();
		$("#rate").html(_getRateString(_source_curr, target_curr, "UT"));
		//$("#st_rate").html(_getRateString(_source_curr, target_curr, "ST"));
		$("#reserve").html(_getReserveString(target_curr, "UT"));
		//$("#min_val").html(_getMinValue(target_curr, "UT"));
		$("#max_val").html(_getMaxValue(target_curr, "UT"));
		//$("#st_reserve").html(_getReserveString(target_curr, "ST"));
		// }}}

		bindExchangeParameters();
		moneyCount("source");
	}
	
	function st_Selected()
	{
		exchangeType_Selected("ST");
	}
	
	function ut_Selected()
	{
		exchangeType_Selected("UT");
	}
	
	function exchangeType_Selected(t)
	{
		var _source_curr = $("#from").val();
		var _target_curr = $("#to").val();
		
		if (_rates[t][_target_curr].d) return;
		$("#rate").html(_getRateString(_source_curr, _target_curr, t));
		$("#reserve").html(_getReserveString(_target_curr, t));
		//$("#min_val").html(_getMinValue(_target_curr, t));
		$("#max_val").html(_getMaxValue(_target_curr, t));
		
		
		// меняем блок результир валюты
		var _data = _targetCurrCache[_source_curr].order;
	
		//redrawTargetCurrDropDown(_data.order, _rates)
        
        var selectedVal = $("#to").val();
        if (typeof(gotoExchangeData) != "undefined") selectedVal = gotoExchangeData[1];
        
  		var _html = ["<select name='to' id='to' class='styled' onchange='targetCurrency_OnChange()'>"];
		for (var i = 0, l = _data.length; i < l; i++)
		{
			if (typeof(_rates[t][_data[i].id]) != "undefined" && !_rates[t][_data[i].id].d)
			{
				_html[_html.length] = "<option value='" + _data[i].id + "'" + (selectedVal == _data[i].id ? " selected " : "") +  ">" + currencyFullName[_data[i].id];
			}
		}
		_html[_html.length] = "</select>";
		
		$("#to_span").html(_html.join(""));
        //alert(currencyFullName[gotoExchangeData[1]]);
        
        _target_curr = $("#to").val();
        if (_rates[t][_target_curr].d) return;
		$("#rate").html(_getRateString(_source_curr, _target_curr, t));
		$("#reserve").html(_getReserveString(_target_curr, t));
		//$("#min_val").html(_getMinValue(_target_curr, t));
		$("#max_val").html(_getMaxValue(_target_curr, t));
        
        
        //var _source_curr = sourceCurrency = $("#from").val();
		//renderExchangeBlock(_targetCurrCache[_source_curr]);
		//sourceCurrency_OnChange();
		_moneyCount($my("source_value"));
	}
	
	// формирует отформатированную строку с курсом
	function _getRateString(source_curr, target_curr, type)
	{
		//alert(currencyNames[source_curr] + " " + currencyNames[target_curr] + " " + type);
		var res = "";
		if (_rates[type][target_curr].m)
		{
			res = "1 {0} : {1} {2}".format(source_curr, _rates[type][target_curr].r, target_curr);
		}
		else
		{
			res = "{1} {0} : 1 {2}".format(source_curr, _rates[type][target_curr].r, target_curr);
		}
		return res;
	}
	
	// формирует отформатированную строку с резервом
	function _getReserveString(target_curr, type)
	{
		var res = "";
		res = "{0} {1}".format(formatBigFloat(_balances[type][target_curr]), target_curr);
		return res;
	}
	function _getMinValue(target_curr, type)
	{
		var res = "";
		res = formatBigFloat(_rates[type][target_curr].minValue) + " " + _rates[type][target_curr].minCode;
		return res;
	}
	function _getMaxValue(target_curr, type)
	{
		var res = "";
		res = formatBigFloat(_rates[type][target_curr].maxValue) + " " + _rates[type][target_curr].maxCode;
		return res;
	}


	// }}}

	
	function switchType(ttype)
	{
		$(".exchange-type-switcher1").removeClass("UT").removeClass("ST").addClass(ttype);
		$("input[name='exchange-type']").val(ttype);
	}
	
	// запуск инициализации форм обмена на главной
	function bindMainPageExchangeForms()
	{
		
		// переключалка типов обмена
        $(".exchange-type-switcher1 input").click(function() {
			switchType(this.value);
		});

		/*
		$("input.summ")
			.keypress(function(e) { return checkInput(this, e); })
			.keyup(function() { _moneyCount(this); })
			.keydown(function() { _moneyCount(this); })
			.focus(function() { _moneyCount(this); })
			.blur(function() { _moneyCount(this); });
		*/
		$("#source_value")
			.keypress(function(e) { return checkInput(this, e); })
			.keyup(function() { moneyCount("source"); })
			.keydown(function() { moneyCount("source"); })
			.focus(function() { moneyCount("source");resetZero(this)  })
			.blur(function() { moneyCount("source");showZero(this) });

		$("#source_full")
			.keypress(function(e) { return checkInput(this, e); })
			.keyup(function() { moneyCount("sourceFull"); })
			.keydown(function() { moneyCount("sourceFull"); })
			.focus(function() { moneyCount("sourceFull");resetZero(this)  })
			.blur(function() { moneyCount("sourceFull");showZero(this) });

		$("#target_value")
			.keypress(function(e) { return checkInput(this, e); })
			.keyup(function() { moneyCount("target"); })
			.keydown(function() { moneyCount("target"); })
			.focus(function() { moneyCount("target"); resetZero(this) })
			.blur(function() { moneyCount("target"); showZero(this) });

		// exchange block
		$("#from").change(sourceCurrency_OnChange);
		$("#exchange-type1").click(ut_Selected);
		$("#exchange-type2").click(st_Selected);
	}
	
	function initMainPageExchangeForms()
	{
		bindMainPageExchangeForms();
		sourceCurrency_OnChange();
	}
	function resetZero(obj)
	{
	    if (obj.value == 0) obj.value = "";
	}
	function showZero(obj)
	{
	    if (obj.value == "") obj.value = "0.00";
	}

	var payer, recipient, sourceMaster, rate, sourceCurrency, targetCurrency;
	function _moneyCount(obj)
	{
		var from;
		if (/source_value/.test(obj.id))
		{
			from = "source";
		}
		else if (/target_value/.test(obj.id))
		{
			from = "target";
		}
		bindExchangeParameters();
		moneyCount(from);
	}
	
	function bindExchangeParameters(suffix)
	{
		var _type = $("input[name='exchange-type']").val();
		if (typeof _type == "undefined") _type = "UT";
		var _curr = $("#to").val();
		sourceMaster = _rates[_type][_curr].m;
		rate = _rates[_type][_curr].r;
	}
	
	function getRadioGroupValue(radioGroupObj)
    {  
      for (var i=0; i < radioGroupObj.length; i++)
        if (radioGroupObj[i].checked) return radioGroupObj[i].value;

      return null;
    }
    
    function showAuthorize(flag)
    {
        var from = 2;
	    var to = 2.1;
	    currStep = to;
	    if (flag) currStep = from;
		$(".exch-tab2").load(
			"/exchange/request_ajax.asp?from={0}&to={1}&type={2}&t={3}".format("SMS", $("#to2").val(), "UT", (new Date()).valueOf()) + (flag ? "&flag=1" : ""),
			{
			    country: $("#country_select").val(),
			    operator: $("#operator_select").val(),
				from: "SMS",
				to: $("#to2").val(),
				validation_code: $("input[name='validation_code']").val(),
			//	source_value: source_value,//$("#source_value").val(),
			//	source_full: 0.98,//$("#source_full").val(),
		//		target_value: 0.03,//$("#target_value").val(),
	//			target_full: $("#target_full").val(),
				target_account: $("#target_account2").val(),
				phone: $("#phone").val(),
				payment_type_ID: $("#payment_type_ID").val(),
				email: "",//$("#email").val(),
				step: from,
				goto: to
			},
			function() {
				if (!$my("last_step"))
				{
					bindMainPageExchangeForms();
					exchangeType_Selected($("input[name='exchange-type']").val());
					moneyCount("source");
					if (!afterLogin)
					{
						$("#errors").fadeIn();
					}
					else
					{
						afterLogin = false;
					}
				}
			}
		);
		isButtonClick = 0;
	}
    
    function showNum(flag, mylogin, mypass)
	{
	    var do_auth;
	    
	    if (document.radioForm2)
	    {
	        do_auth = getRadioGroupValue(document.radioForm2.authorize);
	    }
	    var from = 2;
	    var to = 2.5;
	    currStep = to;
	    if (flag) currStep = from;
		$(".exch-tab2").load(
			"/exchange/request_ajax.asp?from={0}&to={1}&type={2}".format("SMS", $("#to2").val(), "UT") + (flag ? "" : ""),
			{
			    country: $("#country_select").val(),
			    operator: $("#operator_select").val(),
				from: "SMS",
				to: $("#to2").val(),
				validation_code: $("input[name='validation_code']").val(),
				target_account: $("#target_account2").val(),
				phone: $("#phone").val(),
				payment_type_ID: $("#payment_type_ID").val(),
				email: "",//$("#email").val(),
				todo: do_auth,
				login: mylogin ? mylogin : $("#smslogin").val(),
				password: mypass ? mypass : $("#smspassword").val(),
				reglogin: $("#smsreglogin").val(),
				regname: $("#smsregname").val(),
				regpassword: $("#smsregpassword").val(),
				regpassword2: $("#smsregpassword2").val(),
				step: from,
				goto: to
			},
			function(data) {
                
                if (document.getElementById("sms-user-data"))
			    {
			        $(".login-form").after($("#sms-user-data").html());
				    $(".login-form").remove();
			    }
			    
				if (!$my("last_step"))
				{
					bindMainPageExchangeForms();
					exchangeType_Selected($("input[name='exchange-type']").val());
					moneyCount("source");
					if (!afterLogin)
					{
						$("#errors").fadeIn();
					}
					else
					{
						afterLogin = false;
					}
				}
			}
		);
		isButtonClick = 0;
	}
	
	function goToSMS(flag)
	{
	    var sms_number;
	    if (document.radioForm)
	    {
	        sms_number = getRadioGroupValue(document.radioForm.tariff_radio);
	    }
	    else sms_number = null;
	    var source_value;
	    if (sms_number == null) source_value = 0;
	    else source_value = tariff[sms_number].pi;
	    if (flag ) sms_number = 0;
	    else if ($("#country_select").val() == 0) source_value = 0;
	    var from = 2;
	    var to = 3;
	    currStep = to;
	    if (flag) {currStep = from; to=2.1};
		$(".exch-tab2").load(
			"/exchange/request_ajax.asp?from={0}&to={1}&type={2}&t={3}".format("SMS", $("#to2").val(), "UT", (new Date()).valueOf()) + (flag ? "&flag=1" : ""),
			{
			    country: $("#country_select").val(),
			    operator: $("#operator_select").val(),
				from: "SMS",
				to: $("#to2").val(),
				validation_code: $("input[name='validation_code']").val(),
				source_value: source_value,//$("#source_value").val(),
			//	source_full: 0.98,//$("#source_full").val(),
		//		target_value: 0.03,//$("#target_value").val(),
	//			target_full: $("#target_full").val(),
				target_account: $("#target_account2").val(),
				phone: $("#phone").val(),
				payment_type_ID: $("#payment_type_ID").val(),
				email: $("#email").val(),
				step: from,
				goto: to,
				sms_number: sms_number
			},
			function() {
				if (!$my("last_step"))
				{
					bindMainPageExchangeForms();
					exchangeType_Selected($("input[name='exchange-type']").val());
					moneyCount("source");
					if (!afterLogin)
					{
						$("#errors").fadeIn();
					}
					else
					{
						afterLogin = false;
					}
				}
			}
		);
		isButtonClick = 0;
	}
	
	
	function goToStep(from, to)
	{
	    currStep = to;
		$(".exch-tab").load(
			"/exchange/request_ajax.asp?from={0}&to={1}&type={2}".format($("#from").val(), $("#to").val(), $("input[name='exchange-type']").val()),
			{
				from: $("#from").val(),
				to: $("#to").val(),
				validation_code: $("input[name='validation_code']").val(),
				source_value: $("#source_value").val(),
				source_full: $("#source_full").val(),
				target_value: $("#target_value").val(),
				target_full: $("#target_full").val(),
				source_account: $("#source_account").val(),
				target_account: $("#target_account").val(),
				payment_type_ID: $("#payment_type_ID").val(),
				email: $("#email").val(),
				step: from,
				goto: to
			},
			function() {
				if (!$my("last_step"))
				{
					bindMainPageExchangeForms();
					exchangeType_Selected($("input[name='exchange-type']").val());
					moneyCount("source");
					if (!afterLogin)
					{
						$("#errors").fadeIn();
					}
					else
					{
						afterLogin = false;
					}
				}
			}
		);
		isButtonClick = 0;
	}
	
	function goToStep4()
	{
	    currStep = 4;
		$(".exch-tab").load(
			"/exchange/handle.asp?type={0}".format($("input[name='exchange-type']").val()),
			{
				from: $("#from").val(),
				to: $("#to").val(),
				validation_code: $("input[name='validation_code']").val(),
				source_value: $("#source_value").val(),
				source_full: $("#source_full").val(),
				target_value: $("#target_value").val(),
				target_full: $("#target_full").val(),
				source_account: $("#source_account").val(),
				target_account: $("#target_account").val(),
				payment_type_ID: $("#payment_type_ID").val(),
				email: $("#email").val(),
				actionButton: "Continue",
				user_random_id: $("#user_random_id").val()
			},
			function() {
				//alert(1);
			}
		);
		isButtonClick = 0;
	}
	
	function goToSMS2()
	{
	    var sms_number;
	    if (document.radioForm)
	    {
	        sms_number = getRadioGroupValue(document.radioForm.tariff_radio);
	    }
	    else sms_number = null;
	    var source_value;
	    if (sms_number == null) source_value = 0;
	    else source_value = tariff[sms_number].pi;      
	    if (Number(String($("#daychange").val()).replace(",",".")) + Number(tariff[sms_number].pao)/Number($("#cb_rate").val()) >= $("#daylimit").val()) $("#limiterrors2").fadeIn();
	    else if (Number(String($("#hourchange").val()).replace(",",".")) + Number(tariff[sms_number].piu)*1.7 >= $("#hourlimit").val()) $("#limiterrors").fadeIn();
	    else {
    	    sms_number = String(sms_number).split("-")[0];
	        currStep = 4;
		    $(".exch-tab2").load(
			    "/exchange/handle.asp?type={0}".format($("input[name='exchange-type']").val()),
			    {
    			    
				    from: "SMS",
				    to: $("#to2").val(),
				    validation_code: $("input[name='validation_code']").val(),
				    source_value: source_value,//$("#source_value2").val(),
				    //source_full: $("#source_full").val(),
				    //target_value: $("#target_value").val(),
				    //target_full: $("#target_full").val(),
				    target_account: $("#target_account2").val(),
				    phone: $("#phone").val(),
				    payment_type_ID: $("#payment_type_ID").val(),
				    email: $("#email").val(),
				    actionButton: "Continue",
				    user_random_id: $("#user_random_id").val(),
				    country: $("#country_select").val(),
				    operator: $("#operator_select").val(),
				    sms_number: sms_number//$("#sms_number").val()
			    },
			    function() {
    				
			    }
		    );
		}
		isButtonClick = 0;
		
	}
	
	// отправка запроса с шага 1
	function goToStep2()
	{
		goToStep(1, 2);
	}
	
	// отправка запроса с шага 2
	function goToStep1()
	{
		goToStep(2, 1);
	}
	
	// отправка запроса с шага 2
	function goToStep3()
	{
		goToStep(2, 3);
	}
	
	// {{{ коды ошибок
	var ERROR_CODES  = {
		VALUE_LESS_THAN_MIN_VALUE: 55,
		VALUE_MORE_THAN_MAX_VALUE: 56,
		VALUE_MORE_THAN_QUOTA: 60,
		INPUT_INVALID_ACCOUNT: 2
	}
	// }}}
	var STEP1_ERRORS = { 55:1, 56:1, 60:1 };
	var STEP2_ERRORS = { 55:1, 56:1, 60:1, 2:1 };

	// переход с закладки курсов на оформление
	var isFromExchangeRates = false; // флаг перехода с курсов на оформление
	var targetFromExchangeRates = null;
	var typeFromExchangeRates = null;
	function gotoExchangeForm(source, target, ttype)
	{
		isFromExchangeRates = true;
		$("#from").val(source);
		targetFromExchangeRates = target;
		typeFromExchangeRates = ttype;
		//sourceCurrency_OnChange();
		return false;
	}
	
	function fillFormFromExchangeRatesTab()
	{
		isFromExchangeRates = false;
		$("#to").val(targetFromExchangeRates);
		targetCurrency_OnChange();
		exchangeType_Selected(typeFromExchangeRates);
		switchType(typeFromExchangeRates);
		switchToExchangeTab();
	}
    
    function formatBigFloat(val)
    {
        var result = "";
        if (val / 1000 < 1)
            return val;
        var str = String(val);
        var parts = new Array();
        var pos = (str.indexOf(".") == -1 ? str.length : str.indexOf("."));
        while (pos > 0)
        {
            var s_pos = (pos - 3 < 0 ? 0 : pos - 3);
            var e_pos = (parts.length == 0 ? -1 : pos);
            if (e_pos != -1)
                parts.push(str.slice(s_pos, e_pos));
            else
                parts.push(str.slice(s_pos));
            pos -= 3;
        }
        return parts.reverse().join(" ");
    }
    
    function handlePhone(num)
    {
	    var RegEx=/[\s()\+]/g;
        num=num.replace(RegEx,"");
        if (num[0] != "7") num = "7" + num.substring(1);
        return num;
    }