$(document).ready(function(){

	var overlay = $("#overlay");
	var dwidth = $(document).width();
	var dheight = $(document).height();

	$("#cart_link").click(function() {
			overlay.css({'display':'block'}).css({'width':dwidth}).css({'height':dheight});
			$("#login_box").css({'display':'block'})

			$("#login_result").html('').removeClass();
	})

	$("#login_link").click(function() {
			overlay.css({'display':'block'}).css({'width':dwidth}).css({'height':dheight});
			$("#login_box").css({'display':'block'})

			$("#login_result").html('').removeClass();
	})

	$("#overlay").click(function() {
			$("#login_box").hide();
			$("#overlay").hide();
	})

	// 3 - обработка отправки формы
	$("#login_form").submit(function() {
	        // указываем класс process для div-а сообщений и плавно показываем его
	        $("#login_result").removeClass().addClass('process').css({'text-align':'center'}).text('Проверка....').fadeIn(1000);
	        // проверяем через AJAX имя пользователя пароль
	        $.post($("#login_form").attr('action'), { username:$('#username').val(),password:$('#password').val(),rand:Math.random() } ,function(data) {
	        	if (!$('#username').val()){
				    $("#username").animate({ backgroundColor: "#ffd6d6" }, 500);
	        	}else{
					$('#username').animate({ backgroundColor: "#ffffff" }, 500);
	        	}
	        	$('#password').animate({ backgroundColor: "#ffffff" }, 500);
	        	if (!$('#password').val()){
				    $("#password").animate({ backgroundColor: "#ffd6d6" }, 500);
	        	}
				if(data==1) {
					// логин верный
					$("#login_result").fadeTo(200,0.1,function() {
						var cart = getCookieValue('CART');
						if (cart){
							$(this).html('Все верно. Переходим к <b>оформлению</b>.....').removeClass().css({'text-align':'center'}).addClass('success').fadeTo(900,1,
							function() {
								document.location='/cart/step1/';
							});
						}else{
							$(this).html('Все верно. Переходим в <b>заказы</b>.....').removeClass().css({'text-align':'center'}).addClass('success').fadeTo(900,1,
							function() {
								document.location='/my/';
							});
						}
					});
				} else {
					// логин неверный
					$("#login_result").fadeTo(200,0.1,function(){
						$(this).html('Логин неверен ...').removeClass().addClass('error').fadeTo(900,1);
					});
				}
			});
			return false;// отмена отправки формы (действие по умолчанию)
	});

	// 3 - обработка отправки заказа
	$("#order_form").submit(function() {
	        // указываем класс process для div-а сообщений и плавно показываем его
	        $("#order_result").removeClass().css({'text-align':'center'}).addClass('process').text('Проверка....').fadeIn(1000);
	        // проверяем через AJAX имя пользователя пароль
	        createMessage('Заказ оформляется, это может занять до 10 секунд...','#000000',10000);
	        var deliv_id = 0;
	        if (document.getElementById('iz_ofica').checked == true){
	        	var deliv_id = 1;
	        }
        	var riv_id = 'right';
        	var fmethod = $("#fast_method").val();
//        	alert(fmethod);
//	        alert(("#order_form").attr('action'));
//	        alert($('#country_id').val());
	        $.post($("#order_form").attr('action'), { rivage:riv_id,tochka_vidachi:$('#sam_rivage').val(),volume:$('#volume').val(),delivery_adress:$('#DelAdr').val(),ssh:$('#s-sh').val(),spom:$('#s-pom').val(),spoh:$('#s-poh').val(),ssm:$('#s-sm').val(),to_name:$('#ToName').val(),phones_to_name:$('#PhToName').val(),delivery_date:$('#delivery_date').val(),country_id:$('#country_id').val(),country_name:$('#country_name').val(),skidka:$('#skidka').val(),delivery:deliv_id,market_seo_id:$('#market_seo_id').val(),rand:Math.random() } ,function(data) {
				$('#ToName').animate({ backgroundColor: "#ffffff" }, 200);
	        	$('#PhToName').animate({ backgroundColor: "#ffffff" }, 200);
	        	$('#DelAdr').animate({ backgroundColor: "#ffffff" }, 200);
				if(data>1) {
					$("#login_box").hide();
//					createMessage('Ваш заказ <h2>№'+data+'</h2> оформлен.<br>В ближайшее время с Вами свяжется менеджер<br>для подтверждения заказа','#000000',10000);
					$("#order_result").removeClass().empty();
					var fast_str = '';
					if (fmethod == 'fast'){
						var fast_str = '&method=fast';
					}
					setTimeout("location.href='/congratulation/?order_id="+data+""+fast_str+"';",6000);
				}else{
					if (!$('#ToName').val()){
					    $("#ToName").animate({ backgroundColor: "#ff9b9b" }, 400);
					    $("#ToName").animate({ backgroundColor: "#ffd6d6" }, 200);
		        	}else{
						$('#ToName').animate({ backgroundColor: "#ffffff" }, 200);
		        	}
		        	var reg = /_/;
		        	if (reg.test($('#PhToName').val())){
		        		$("#PhToName").animate({ backgroundColor: "#ff9b9b" }, 400);
					    $("#PhToName").animate({ backgroundColor: "#ffd6d6" }, 200);
		        	}else{
						$('#PhToName').animate({ backgroundColor: "#ffffff" }, 200);
		        	}
		        	$('#DelAdr').animate({ backgroundColor: "#ffffff" }, 200);
		        	if (!$('#DelAdr').val()){
		        		$("#DelAdr").animate({ backgroundColor: "#ff9b9b" }, 400);
		        		$('#DelAdr').animate({ backgroundColor: "#ffd6d6" }, 200);
		        	}else{
		        		$('#DelAdr').animate({ backgroundColor: "#ffffff" }, 200);
		        	}
		        	$("#order_result").removeClass().empty();
		        	createMessage('Ваш заказ не оформлен.<br>Если возникают трудности свяжитесь<br>с менеджером по телефону.<br><b>тел. 8(044)390-50-22</b>','#000000',4000);
				}
			});
			return false;// отмена отправки формы (действие по умолчанию)
	});

	$("#reg_new").submit(function() {

		$("#sbm_reg_result").html('');

		var sbmfrm = $("#reg-layer");
		var sbmfrm_w = $("#reg-layer").width()/2;
		var sbmfrm_h = $("#reg-layer").height()/2;

		$("#reg-layer").css({'opacity':'.6'});
		$("#reg-layer").css({'filter':'alpha(opacity=60)'});

		$("#Loader")
		.css({'position' : 'relative'})
		.css({'top' : sbmfrm_h})
		.css({'left' : 120})
		.html('<img src="/i/loader.gif">');

		 var form_value = "";
		 for (var i=0;i<document.forms["reg_new"].length;i++ )
		 {
		 	 var id = document.forms["reg_new"].elements[i].id;
		 	 var val = document.forms["reg_new"].elements[i].value;
	 	 	 form_value += id+":"+val+",";
		 }
		 var str_to_post = form_value.substr(0,form_value.length-1);
//		 alert(str_to_post);
		 $.post($("#reg_new").attr('action'), {post_str:str_to_post} ,function(data) {
		 			createMessage('Подождите немного, ваши данные сохраняются','#000000',2500);
					if(data==1) {
						$("#Loader").empty();
						$("#reg-layer").css({'opacity':'1'});
						createMessage('Данные успешно сохранены!','#000000',2500);
						var cart = getCookieValue('CART');
						if (cart){
							location.href='/cart/step1/#step1';
						}else{
							location.href='/my/profile/';
						}
					}else{
						$("#Loader").empty();
						$("#reg-layer").css({'opacity':'1'});
						$("#reg-layer").css({'filter':'alpha(opacity=100)'});
						$("#sbm_reg_result").html('&nbsp;- объязательные для заполнения поля.').removeClass().addClass('error').fadeTo(900,1);
						createMessage(data,'#000000',5000);
					}
		})
	return false;// отмена отправки формы (действие по умолчанию)
	});
	$('#main_login_form').bind('submit', function (event){
		if ($('#main_username').val() != '' && $('#main_password').val() != ''){
			$.post($('#main_login_form').attr('action'), {username: $('#main_username').val(), password:$('#main_password').val() }, function (data){
				if (data == 1){
					window.location='/my/profile/';
				}else{
					createMessage('Данные авторизации не верны','#000000',5000);

				}
			})
		} else {
			$('#main_login_form input[value=]').animate({ backgroundColor: "#ffd6d6" }, 500);
		}
		event.preventDefault();
	})
});

function changeCustomerType(type)
{
    if ('new' == type)
    {
        document.getElementById('new_customer').className = 'selection_over';
        document.getElementById('old_customer').className = 'selection';
        document.getElementById('just_order').className = 'selection';

        document.getElementById('content_chk_new_customer').style.display = 'block';
        document.getElementById('login_old_customer').style.display = 'none';
        document.getElementById('order').style.display = 'none';
    }
    else if ('login' == type)
    {
        document.getElementById('new_customer').className = 'selection';
        document.getElementById('old_customer').className = 'selection_over';
        document.getElementById('just_order').className = 'selection';

        document.getElementById('content_chk_new_customer').style.display = 'none';
        document.getElementById('login_old_customer').style.display = 'block';
        document.getElementById('order').style.display = 'none';
    }
    else if ('order' == type)
    {
        document.getElementById('new_customer').className = 'selection';
        document.getElementById('old_customer').className = 'selection';
        document.getElementById('just_order').className = 'selection_over';

        document.getElementById('content_chk_new_customer').style.display = 'none';
        document.getElementById('login_old_customer').style.display = 'none';
        document.getElementById('order').style.display = 'block';
    }
}

function changeCustomerStyle(obj, new_class)
{
    if ( document.getElementById('chk_'+obj.id).checked )
    {
    }
    else
    {
        obj.className = new_class;
    }
}

function show_fast_adr(val){
	if (val.checked == true){
		document.getElementById('fast_riv').style.display='none';
		document.getElementById('fast_vol').style.display='none';
		document.getElementById('fast_adr').style.display='none';
		document.getElementById('city').style.display='none';
		$('#DelAdr').val('Самовывоз из офиса.');
		$('#del_time_label').html = 'Дата самовывоза:';
		$('#delivery_date_label').html = 'Время самовывоза:';
	}else{
		document.getElementById('fast_riv').style.display='';
		document.getElementById('fast_vol').style.display='';
		document.getElementById('fast_adr').style.display='';
		document.getElementById('city').style.display='';
		//document.getElementById('country').value='Киев';
		$('#DelAdr').val('');
		document.getElementById('del_time_label').innerHTML = 'Дата доставки:';
		document.getElementById('delivery_date_label').innerHTML = 'Время доставки:';
	}
}
function getCookieValue (name) {
    var cookieValue = document.cookie;
    var r = new RegExp("\\b"+name+"\\b");
    var cookieStart = cookieValue.search(r);
    if (cookieStart == -1)
        cookieValue = null;
    else {
        cookieStart = cookieValue.indexOf("=", cookieStart) + 1;
		if (cookieStart != 0) {
	        var cookieEnd = cookieValue.indexOf(";", cookieStart);
	        if (cookieEnd == -1)
	            cookieEnd = cookieValue.length;
	        cookieValue = unescape(cookieValue.substring(cookieStart, cookieEnd));
		} else cookieValue = null;
    }
    return cookieValue;
}
load_timer = 0;
function hideMessage()
{
	with(document.getElementById('mess')){
		innerHTML = "";
		style.visibility = "hidden";
		style.color = "black";
	}
}
function createMessage(text, color, time_to_show)
{
	with(document.getElementById('mess'))
	{
		style.visibility = "visible";
		innerHTML = "<div class=\"msg\">"+text+"</div>";
		style.color = color;
	}
	if(time_to_show > 0)
		setTimeout("hideMessage()", time_to_show);
}
window.onscroll = setX;
var ScrollY = 0;
function setX()
{
	var m = document.getElementById('mess');
	if (m) {
		m.style.top = document.body.scrollTop + 200;
		ScrollY = document.body.scrollTop;
	}
}