$(document).ready(function(){
	var check1 = 0;
	var priceList = null;
	var pricePlan = null;
	// Hosting information (name, discount, price, period)
	var hostingName = null;
	var hostingDiscount = 0;
	var hostingPriceMonth = 0;
	var hostingOrderMonth = 0;
        // Domain information (name, zone, cost, bonus-free)
        var domainCost = 0.00;
	var domainName = null;
	var domainTLD = null;	
	var domainBuy = false;
	var domainFree = Array();

	if (typeof PriceJSON != "undefined") 
	{
		priceList = $.parseJSON(PriceJSON);
		s1_Init();
	}

	function s1_Init() 
	{
		hostingName = null;
		hostingDiscount = 0;
		hostingPriceMonth = 0;
		hostingOrderMonth = 0;

		if (priceList != null) 
		{
			pricePlan = priceList["hosting"][0];
			hostingName = priceList["hosting"][0]["name"];	
		}
		
		domainCost = 0.00;
		domainName = null;
		domainTLD = null;
		domainBuy = false;
		domainFree = Array();		

		s1_UpdatePrice();

		s1_UpdateInfo();
	}

	function getRoundPrice(p)
        {
		return (Math.round(p * 100) / 100).toString().replace('.',',');
        }

	function getHostingPrice()
	{
		return (hostingPriceMonth * hostingOrderMonth) * (1.00 - (0.01 * hostingDiscount));
	}

	function getDomainPrice()
	{
		return parseFloat(domainCost)
	}

	function getTotalPrice() 
	{
		return getHostingPrice() + getDomainPrice();
	}

	function s1_UpdatePrice() {
		if (pricePlan != null && typeof pricePlan["discounts"] != "undefined") {
			hostingDiscount = 0;
			for (i=0;i<pricePlan["discounts"].length;i++) 
			{
				if (typeof pricePlan["discounts"][i]["month"] != "undefined" &&
				    typeof pricePlan["discounts"][i]["value"] != "undefined") 
				{
					var discountMonth = parseInt(pricePlan["discounts"][i]["month"]);
					if (hostingOrderMonth >= discountMonth) {
						hostingDiscount = parseInt(pricePlan["discounts"][i]["value"]);
					}
				}
			}
			$('.rate').find('.total .discount').text(hostingDiscount + ' %');
		}
		if (pricePlan != null && typeof pricePlan["month-price"] != "undefined") {
			hostingPriceMonth = parseFloat(pricePlan["month-price"]);
			$('.rate').find('.total .price').text(getRoundPrice(getTotalPrice()) + ' рублей');
		}
	}

	function s1_UpdateInfo() 
	{
		if (hostingName != null) {
			$('.rate').find('.title a').text(hostingName);
		}
		if (pricePlan != null) 
		{
			if (typeof pricePlan["podarok"] != "undefined") 
			{
				var podarokTlds = null;
				for (i=0;i<pricePlan["podarok"].length;i++)
				{
					if (typeof pricePlan["podarok"][i]["month"] != "undefined" &&
					    typeof pricePlan["podarok"][i]["domain"] != "undefined")
					{
						var podarokMonth = parseInt(pricePlan["podarok"][i]["month"]);
						if (hostingOrderMonth >= podarokMonth) 
						{
							podarokTlds = ((podarokTlds != null) ? podarokTlds + ' или .': '.') + pricePlan["podarok"][i]["domain"].toUpperCase();
							domainFree.push(pricePlan["podarok"][i]["domain"].toLowerCase());
						}
					}
				}
				$('.rate').find('.rate-podarok-tld').text(((podarokTlds == null) ? "нет" : ""+podarokTlds+""));
			}
			if (typeof pricePlan["options"]["hdd"] != "undefined") {
				var hddValue = pricePlan["options"]["hdd"];
				$('.rate').find('.rate-hdd').text(hddValue + ' MB');
			}
			if (typeof pricePlan["options"]["domains"] != "undefined") {
				var domainsValue = pricePlan["options"]["domains"];
				$('.rate').find('.rate-domains').text('(доменов)'+domainsValue);
			} 
			if (typeof pricePlan["options"]["php"] != "undefined") {
				var phpValue = pricePlan["options"]["php"];
				$('.rate').find('.rate-php').text(((phpValue == true) ? "есть" : "нет"));
			} 
			if (typeof pricePlan["options"]["databases"] != "undefined") {
				var databasesValue = pricePlan["options"]["databases"];
				$('.rate').find('.rate-databases').text(databasesValue);
			} 
			if (typeof pricePlan["options"]["email"] != "undefined") {
				var emailValue = pricePlan["options"]["email"];
				$('.rate').find('.rate-email').text(emailValue);
			} 
			if (typeof pricePlan["options"]["panel"] != "undefined") {
				var panelValue = pricePlan["options"]["panel"];
				$('.rate').find('.rate-panel').text(panelValue);
			}
		}
	}

	function s3_UpdateInfo() 
	{
		$(".bill").html("");

		$('<li class="grey"><span>Хостинг, тариф '+hostingName+' (период оплаты '+hostingOrderMonth+' мес.):</span><em>'+getRoundPrice(getHostingPrice())+' руб.</em></li>').appendTo($(".bill"));
		if (domainBuy == true) {
			var price = domainCost;
			for (i=0;i<domainFree.length;i++) 
			{
				if (domainFree[i].toLowerCase() == domainTLD.toLowerCase()) 
				{
					domainCost = 0.00;
					break;
				}
			}
			$('<li class="white"><span>Регистрация доменного имени '+domainName+'.'+domainTLD+':</span><em>'+domainCost+' руб.</em></li>').appendTo($(".bill"));
		}
		$('<li><span>Всего к оплате:</span><em>'+getRoundPrice(getTotalPrice())+' руб.</em></li>').appendTo($(".bill"));
	}

	function IsEmailValid(str) 
	{
		var lat=str.indexOf('@');
		var ldot=str.indexOf('.');
		var lstr=str.length;

		if (str.indexOf('@') == -1 || str.indexOf('@') == 0 || str.indexOf('@') == lstr ||
		    str.indexOf('.') == -1 || str.indexOf('.') == 0 || str.indexOf('.') == lstr)
		{
		    return false;		
		}

		if (str.indexOf('@',(lat+1))!=-1)
		{
		   return false;
		}

		if (str.substring(lat-1,lat) == '.' || str.substring(lat+1,lat+2) == '.')
		{
		    return false;
		}

		if (str.indexOf('.',(lat+2))==-1)
		{
		    return false;		 
		}
		
		if (str.indexOf(" ")!=-1)
		{
		    return false;		 
		}

 		return true;
	}

	function whoisShowHide() {
	    if ($("#fb-domain-list").is(':visible')) {
		$("#fb-domain-list").hide();
	    } else {
		$("#fb-domain-list").show();
	    }
	}

	function whoisShow() {
	    if (!$("#fb-domain-list").is(':visible')) {
		$("#fb-domain-list").show();
	    }
	}

	function whoisHide() {
	    if ($("#fb-domain-list").is(':visible')) {
		$("#fb-domain-list").hide();
	    }
	}

	function whoisGetName(n) {
	    if (!n) {
		return "";
	    }
	    n = $.trim(n.toLowerCase());
	    if (!n || n.length < 2) {
		return "";
	    }
	    if (n[0] == '-' || n[n.length - 1] == '-') {
		return "";
	    }
	    for (i=0;i<n.length;i++) 
	    {
		if (!((n[i] >= 'a' && n[i] <= 'z') ||
		      (n[i] >= '0' && n[i] <= '9'))) 
		{		    
		    if (n[i] == '-' || n[i] == '.') 
		    {
			var prev = i - ((i > 0) ? 1 : 0);
			var next = i + ((i<(n.length-1)) ? 1 : 0);
			if (n[prev] == '-' || n[prev] == '.') return "";
			if (n[next] == '-' || n[next] == '.') return "";
		    } 
		    else 
		    {
			return "";
		    }
		}
	    }
	    return n;
	}

	function whoisNameLevel(n) {
	    var level = 1;

	    if (!n) {
		return 0;
	    }
	    for (i=0;i<n.length;i++) {
		if (n[i] == '.') {
		    level += 1;
		}
	    }
	    return level;
	}

	function whoisExtractName(n) {
	    if (!n) {
		return "";
	    }
	    for (i=0;i<n.length;i++) {
		if (n[i] == '.') {
		    return n.substr(0,i);
		}
	    }
	    return n;
	}

	function whoisExtractTLD(n) {
	    if (!n) {
		return "";
	    }
	    for (i=0;i<n.length;i++) {
		if (n[i] == '.') {
		    return n.substr(i + 1);
		}
	    }
	    return "";
	}

	function getDomain()
	{
		var szDomain = "";
		var szName = "";
		var szTLD = "";
		var iLevel = 0;
	
		szDomain = $("#fb-domain-name").val();
		if (!szDomain) {
		    return false;
		}
		szDomain = whoisGetName(szDomain);
		if (!szDomain) {
		    return false;
		}

		iLevel = whoisNameLevel(szDomain);
		if (iLevel == 0 || iLevel > 3) {
		    return false;
		}
		szName = whoisExtractName(szDomain);
		if (!szName) {
		    return false;
		}
		szTLD = whoisExtractTLD(szDomain);
		if (!szTLD && iLevel > 1) {
		    return false;
		}

		domainTLD = szTLD;
		domainName = szName;

		return true;
	}
	function domain_click() {
		var PriceList = null;
		var iFieldId = 0;

		if (getDomain() == false) {
		    return false;
		}
	
		if (!PriceJSON) {
		    return false;
		}

		PriceList = $.parseJSON(PriceJSON);
		if (!PriceList || !PriceList["domains"]) {
		    return false;
		}

		$("#fb-domain-list").html("<tr><th class=\"col1\">Название домена</th><th class=\"col2\">Статус</th><th class=\"col3\" colspan=\"2\">Цена</th></tr>");

		whoisShow();

		function whoisAdd(argName,argTLD) {
		    var argTLDup = "";
		    var priceTLD = "0.00";
		    var iLiId = "";
		    var classLi = "";
		    
		    if (!argName || !argTLD) {
			return false;
		    }

		    argTLDup = argTLD.toUpperCase();

		    for(i=0;i<PriceList["domains"].length;i++)
		    {	
			if (PriceList["domains"][i] && 
			    PriceList["domains"][i]["new"] && 
			    PriceList["domains"][i]["new"][argTLDup])
			{
			    if (parseInt(PriceList["domains"][i]["new"][argTLDup]) < parseInt(priceTLD) || parseInt(priceTLD) == 0)
			    {
				priceTLD = PriceList["domains"][i]["new"][argTLDup];
			    }
			}
		    }

		    if (parseInt(priceTLD) == 0) {
			return false;
		    }

		    iLiId = "domain_tr_" + iFieldId;
		    classLi = ((iFieldId&1)?"white":"grey");
	 	    iFieldId += 1;

		    $('<tr id="'+iLiId+'" class="'+classLi+'"><td class="col1">'+argName+'.'+argTLD+'</td>' +
		      '<td class="col2">&nbsp;</td><td class="col3">от '+priceTLD+' руб.</td>' + 
		      '<td class="col4">&nbsp;</td></tr>').appendTo("#fb-domain-list");

		    $.ajax({
			type: "POST",
			url: "/whois.php",
			data: "name="+argName+"&tld="+argTLD,
			dataType: "JSON",
			success: function(m){
			    var AnswerJSON = $.parseJSON(m);
			    var free = false;
			    var busy = false;

			    if (AnswerJSON && AnswerJSON["Result"] == "OK") {
			        free = (AnswerJSON["Data"] == "FREE");
			        busy = (AnswerJSON["Data"] == "BORROWED");
			    }

			    if (busy == true)
			    {
				$("#"+iLiId).addClass("occupied");
				$("#"+iLiId+" td.col2").text("занят");
			    }
			    else if (free == true)
			    {
				$("#"+iLiId).addClass("free");
				$("#"+iLiId+" td.col2").text("свободен");
				$("#"+iLiId+" td.col4").html('<a href="#" class="order">заказать</a>');
				$("#"+iLiId+" td.col4 a").click(function () {
				    domainName = argName;
				    domainTLD = argTLD;
				    domainCost = priceTLD;
				    domainBuy = true;
				    $('.step2').show();
				});
			    }
			}
		    });
		}

		whoisAdd(domainName, domainTLD);
	
		if ($("#fb-check2").is(":checked") == true)
		{
			var tlds = Array("ru", "su", "com", "net", "org", "info", "biz", "name", "tv", "ws", "cc", "mobi", "me", "tw", "asia");
			for (t=0;t<tlds.length;t++) 
			{
			    if (!domainTLD || tlds[t] != domainTLD) 
			    {
				whoisAdd(domainName, tlds[t]);
			    }
			}
		}
	}

	function domain2_click() {
		var PriceList = null;
		var iFieldId = 0;
	
		if (getDomain() == false) {
		    return false;
		}

		if (!PriceJSON) {
		    return false;
		}

		PriceList = $.parseJSON(PriceJSON);
		if (!PriceList || !PriceList["domains"]) {
		    return false;
		}

		$('.exist').find('a').html("");

		$('.exist').show();

		function whoisAdd(argName,argTLD) {
		    var argTLDup = "";
		
		    if (!argName || !argTLD) {
			return false;
		    }

		    $('.exist').find('a').html(argName+'.'+argTLD);

		    $.ajax({
			type: "POST",
			url: "/whois.php",
			data: "name="+argName+"&tld="+argTLD,
			dataType: "JSON",
			success: function(m){
			    var AnswerJSON = $.parseJSON(m);
			    var free = false;
			    var busy = false;

			    if (AnswerJSON && AnswerJSON["Result"] == "OK") {
			        free = (AnswerJSON["Data"] == "FREE");
			        busy = (AnswerJSON["Data"] == "BORROWED");
			    }

			    if (busy == true)
			    {
				$('.exist').find('strong').html('существует');
			        domainName = argName;
			        domainTLD = argTLD;
			        domainCost = 0.00;
			        domainBuy = false;
			        $('.step2').show();
			    }
			    else if (free == true)
			    {
				$('.exist').find('strong').html('не существует');
			    }
			}
		    });
		}

		whoisAdd(domainName, domainTLD);
	}


	$('#fb-side-menu.active li').live('click',function(){
		$(this).parent().find('.active').removeClass('active');
		$(this).addClass('active');
		if (priceList != null && typeof priceList["hosting"] != "undefined") 
		{
			hostingName = $(this).find('.title').text();

			for (i=0;i<priceList["hosting"].length;i++) 
			{
				if (typeof priceList["hosting"][i]["name"] != "undefined" &&
				    typeof priceList["hosting"][i]["options"] != "undefined" && 
				    priceList["hosting"][i]["name"].toLowerCase() == hostingName.toLowerCase()) 
				{
					pricePlan = priceList["hosting"][i];
					break;
				}
			}

			s1_UpdateInfo();

			s1_UpdatePrice();
		}
		if ((check1 == 1)) {
			$('a.step1').show();
		}
		return false;
	});
	$('.month li').click(function(){
		$(this).parent().find('.active').removeClass('active');
		$(this).addClass('active');

		hostingOrderMonth = parseInt($(this).find('strong').text());

		s1_UpdateInfo();

		s1_UpdatePrice();

		check1 = 1;
		$('a.step1').show();
		return false;
	});
	$('a.step1').click(function(){
		$('.step1-holder').fadeOut(100, function(){
			$('#fb-steps').find('.active').next().addClass('active');
			$('.step2-holder').fadeIn(100);
		});
		$('#fb-side-menu').removeClass('active');
		return false;
	});
	var haveDomain = 0; 
	$('.choice a').click(function(){
		$(this).parent().find('.active').removeClass('active');
		$(this).addClass('active');
		$('#fb-search').val('');
		if ($(this).is('.no-domain')) {
			$('.step2').hide();
			$('.exist').hide();
			$('form.domain').find('.another-check').show();
			$('form.domain').show();
			haveDomain = 0;
		} else if ($(this).is('.have-domain')){
			$('.domain-list').hide();
			$('.exist').hide();
			$('.step2').hide();
			$('form.domain').find('.another-check').hide();
			$('form.domain').show();
			haveDomain = 1;
		} else if ($(this).is('.no-akk')) {
			$('.enter').hide();
			$('#fb-reg-email').val('');
			$('#fb-reg-pass').val('');
			$('#fb-reg-pass-conf').val('');
			$('#fb-reg-name').val('');
			$('.reg').show();
			$('.continue').show();
			
		} else if ($(this).is('.have-akk')) {
			$('.reg').hide();
			$('#fb-login-email').val('');
			$('#fb-login-pass').val('');
			$('.enter').show();
			$('.continue').show();
		};
		return false;
	});
	$('form.domain #fb-check').click(function(){
		if (haveDomain == 0) {
//			$('.domain-list').show();
			domain_click();
		} else {
			domain2_click();
//			$('.exist').show();
//			$('.step2').show();
		}
		return false;
	});
	$('.order').click(function(){
		$('.step2').show();
		$(this).parent().parent().find('td').css('background-color', '#00000');
	});
	$('.step2').click(function(){
		$('.step2-holder').fadeOut(100, function(){
			$('#fb-steps').find('.active').next().addClass('active');
			$('.step3-holder').fadeIn(100);
			s3_UpdateInfo();
		})
		return false;
	});
	$('.cont').click(function(){
		if ($('.have-akk').hasClass('active'))
		{
	 	    var argEmail = $('#fb-login-email').val();
		    var argPass = $('#fb-login-pass').val();

		    validateLogin();

		    if (argEmail.length == 0 || IsEmailValid(argEmail) == false)
		    {
			alert("Вы ввели неверный Email");
			return false;
		    }
		    
		    if (argPass.length < 6)
		    {
			alert("Пароль должен содержать минимум 6 символов");
			return false;
		    }
		    $.ajax({
			type: "POST",
			url: "/fastbuy.php",
			data: "action=login&user="+argEmail+"&pass="+argPass+"&domain_name="+domainName+"&domain_tld="+domainTLD+"&domain_action="+((domainBuy == true) ? "order" : "link")+"&hosting="+hostingName+"&hosting_period="+hostingOrderMonth,
			dataType: "JSON",
			success: function(m){
			    var AnswerJSON = $.parseJSON(m);
			    if (AnswerJSON)
			    { 
			        if (AnswerJSON["Result"] == "OK") {
  		                    document.location = AnswerJSON["Content"];
			        } else {
			            alert(AnswerJSON["Content"]);
			        }
			    }
			}
		    });
		    return false;
		}
		else if ($('.no-akk').hasClass('active'))
		{
		    var argEmail = $('#fb-reg-email').val();
		    var argPass = $('#fb-reg-pass').val();
		    var argName = $('#fb-reg-name').val();

		    if (argEmail.length == 0 || IsEmailValid(argEmail) == false)
		    {
			alert("Вы ввели неверный Email");
			return false;
		    }

		    if ($('#fb-reg-pass-conf').val() != $('#fb-reg-pass-conf').val())
		    {
			alert("Пароли не совпадают");
			return false;
		    }
		    
		    if (argPass.length < 6)
		    {
			alert("Пароль должен содержать минимум 6 символов");
			return false;
		    }

		    if (argName.length < 3)
		    {
			alert("Короткое имя");
			return false;
		    }

	            $.ajax({
		        type: "POST",
		        url: "/fastbuy.php",
		        data: "action=register&user="+argEmail+"&pass="+argPass+"&name="+argName+"&domain_name="+domainName+"&domain_tld="+domainTLD+"&domain_action="+((domainBuy == true) ? "order" : "link")+"&hosting="+hostingName+"&hosting_period="+hostingOrderMonth,
		        dataType: "JSON",
		        success: function(m){
			        var AnswerJSON = $.parseJSON(m);

			        if (AnswerJSON)
			        { 
			            if (AnswerJSON["Result"] == "OK") {
  		                        document.location = AnswerJSON["Content"];
			            } else {
			                alert(AnswerJSON["Content"]);
			            }
			        }
		        }
	            });
	            return false;
		}
	});
	$('.reset-order').click(function(){
		$('.step3-holder').fadeOut(100,function(){
			$('#fb-steps').find('.active').removeClass('active');
			$('#fb-steps li:first').addClass('active');
			$('#fb-side-menu').addClass('active');
			$('#fb-side-menu .active').removeClass('active');
			$('#fb-side-menu li:first').click();
			$('.month .active').removeClass('active');
			$('.step1').hide();
			$('.step2').hide();
			check1 = 0;
			$('.choice .active').removeClass('active');
			$('.domain').hide();
			$('.another-check').hide();
			$('.exist').hide();
			$('.another-check #fb-check2').attr('checked','');
			$('.domain-list').hide();
			$('.enter').hide();
			$('.reg').hide();
			$('.continue').hide();
			$('#fb-reg-email').val('');
			$('#fb-reg-pass').val('');
			$('#fb-reg-pass-conf').val('');
			$('#fb-reg-name').val('');
			$('#fb-login-email').val('');
			$('#fb-login-pass').val('');
			$('.step1-holder').fadeIn(100);
			s1_Init();
		})
		return false;
	});
	function validateLogin()
	{
	 	var argEmail = $('#fb-login-email').val();
		var argPass = $('#fb-login-pass').val();

  	        if (argEmail.length == 0 || IsEmailValid(argEmail) == false)
		{
		    $('#fb-login-email').css("border", "1px solid #ff8888");
		}
		else
		{
		    $('#fb-login-email').css("border", "1px solid #66bb66");
		}

		if (argPass.length < 6)
		{
		    $('#fb-login-pass').css("border", "1px solid #ff8888");
		}
		else
		{
		    $('#fb-login-pass').css("border", "1px solid #66bb66");
		}
	}
});
