$(document).ready(function(){
	$('body').append('<div id="brekedlayer"></div>');
	//$("#deliv1800").hide();
	// Loading Animator ----------------------------------
	function loadingAnimator () {
		var t = 0, i = 0;
		var intervalID = setInterval(function() {
			if(i == 12) {
				i = 0;
				t = 0;
			}
			$("div.loadingimg").css("backgroundPosition", "0 " + t + "px");
			t = t - 40;
			i++;
		}, 50);
		return intervalID;
	}
	//-----------------------------------------------------
	function windEvent(){
		$('div.closewindow').click(function(){
			$(this).parent('div.fastorderwindow').fadeOut('slow');
			$(this).parent('div.fastorderwindow').stop().fadeOut('slow', function(){
				$("#quick").empty();
			});
			$('#brekedlayer').fadeOut('slow');
		});
		var floatRegExp = /(\d+\s?)+(\.\d{1,2})?/;
		$('div.windplus').click(function(){
			var inttxt = parseInt($(this).nextAll('span.itemcol').text());
			$(this).nextAll('span.itemcol').text(inttxt + 1);
			$(this).nextAll('input.inpitemcol').val(inttxt + 1);
			var $nextObj = $(this).parent('div.windtddivbord2').parent('td').next('td').children('div.windtblsumm').children('span');
			var tempPrevStr = $('#summ_span').text();
			//alert(tempPrevStr.charAt(0));
			//var tempPrevStr = floatRegExp.exec($prevObj.text()).charAt(0);
			//var tempPrevStr = $prevObj.text().charAt(0);
			var tempPrevParsedStr = "";			
			
			for(i = 0; i < tempPrevStr.length; i++) {
				///alert(tempPrevStr.charAt(0));
				if(tempPrevStr.charAt(i)){
					if(tempPrevStr.charAt(i).search(/\s/) == -1){					
						tempPrevParsedStr += tempPrevStr.charAt(i);
					}
				}	
			}			
			var prevPrice = parseFloat(tempPrevParsedStr).toFixed(0);
			
			var tempNextStr = (prevPrice * (inttxt + 1)).toFixed(0).toString();
			var nextPrice = "";
			var flag = 0;
			for(i = tempNextStr.length - 1; i >= 0; i--){
				if(flag < 3){
					if(tempNextStr.charAt(i) != '.'){
						var tmp = tempNextStr.charAt(i) + nextPrice;
						nextPrice = tmp;
						flag++;
					}
					else {
						var tmp = tempNextStr.charAt(i) + nextPrice;
						nextPrice = tmp;
						flag = 0;
					}
				}
				else {
					var tmp = tempNextStr.charAt(i) + ' ' + nextPrice;
					nextPrice = tmp;
					flag = 1;
				}
			}
			$nextObj.text(nextPrice + '');
		});
		$('div.windminus').click(function(){
			var inttxt = parseInt($(this).nextAll('span.itemcol').text());
			if(inttxt > 1) {
				$(this).nextAll('span.itemcol').text(inttxt - 1);
				$(this).nextAll('input.inpitemcol').val(inttxt - 1);
				var $nextObj = $(this).parent('div.windtddivbord2').parent('td').next('td').children('div.windtblsumm').children('span');
				//var $prevObj = $(this).parent('div.windtddivbord2').parent('td').prev('td').children('div.windtddivbord').children('span');
				var tempPrevStr = $('#cost_span').text();
				var tempPrevParsedStr = "";
				for(i = 0; i < tempPrevStr.length; i++) {
					if(tempPrevStr.charAt(i).search(/\s/) == -1){
						tempPrevParsedStr += tempPrevStr.charAt(i);
					}
				}
				
				var prevPrice = parseFloat(tempPrevParsedStr).toFixed(0);
				var tempNextStr = (prevPrice * (inttxt-1)).toFixed(0).toString();
				
				var nextPrice = "";
				var flag = 0;
				for(i = tempNextStr.length - 1; i >= 0; i--){
					if(flag < 3){
						if(tempNextStr.charAt(i) != '.'){
							var tmp = tempNextStr.charAt(i) + nextPrice;
							nextPrice = tmp;
							flag++;
						}
						else {
							var tmp = tempNextStr.charAt(i) + nextPrice;
							nextPrice = tmp;
							flag = 0;
						}
					}
					else {
						var tmp = tempNextStr.charAt(i) + ' ' + nextPrice;
						nextPrice = tmp;
						flag = 1;
					}
				}
				$nextObj.text(nextPrice + '');
			}
			else {
				$(this).nextAll('span.itemcol').text(1);
				$(this).nextAll('input.inpitemcol').val(1);
				var $nextObj = $(this).parent('div.windtddivbord2').parent('td').next('td').children('div.windtblsumm').children('span');
				var $prevObj = $(this).parent('div.windtddivbord2').parent('td').prev('td').children('div.windtddivbord').children('span');
				var tempPrevStr = floatRegExp.exec($prevObj.text())[0];
				var tempPrevParsedStr = "";
				for(i = 0; i < tempPrevStr.length; i++) {
					if(tempPrevStr.charAt(i).search(/\s/) == -1){
						tempPrevParsedStr += tempPrevStr.charAt(i);
					}
				}
				var prevPrice = parseFloat(tempPrevParsedStr).toFixed(0);
				var tempNextStr = (prevPrice * 1).toFixed(0).toString();
				var nextPrice = "";
				var flag = 0;
				for(i = tempNextStr.length - 1; i >= 0; i--){
					if(flag < 3){
						if(tempNextStr.charAt(i) != '.'){
							var tmp = tempNextStr.charAt(i) + nextPrice;
							nextPrice = tmp;
							flag++;
						}
						else {
							var tmp = tempNextStr.charAt(i) + nextPrice;
							nextPrice = tmp;
							flag = 0;
						}
					}
					else {
						var tmp = tempNextStr.charAt(i) + ' ' + nextPrice;
						nextPrice = tmp;
						flag = 1;
					}
				}
				$nextObj.text(nextPrice + '');
			}
		});
		/**/
		$('input.windhideedcheck:radio:checked').parent('div').removeClass('windunch').addClass('windch').next('label.windlabel').addClass('reddltext');
		$('input.windhideedcheck:radio').click(function(){
			$('input.windhideedcheck:radio').parent('div').removeClass('windch').addClass('windunch').next('label.windlabel').removeClass('reddltext');
			$('input.windhideedcheck:radio:checked').parent('div').removeClass('windunch').addClass('windch').next('label.windlabel').addClass('reddltext');
		});
		$('.methodDel input').click(function(){
			if($(this).val() == '1118'){
				$('#addr .windinplabel span').css('display',"none");
				$('#street').removeClass('required');
				$('#bild').removeClass('required');
			}else{
				$('#street').addClass('required');
				$('#bild').addClass('required');
				$('#addr .windinplabel span').css('display',"inline");
			}
		});

		/**/
		//$('select.windorigselect').prev('span.windseltext');
		var tmpStr = "";
		$("select.windorigselect option:selected").each(function () {
			tmpStr = $(this).text();
			$(this).parent('select.windorigselect').prev('span.windseltext').text(tmpStr);
		});
		$('select.windorigselect').change(function(){
			var tmpStr = "";
			$(">option:selected", this).each(function () {
				tmpStr = $(this).text();
				$(this).parent('select.windorigselect').prev('span.windseltext').text(tmpStr);
			});
		});
		$('#city').change(function(){
			$("option:selected", this).each(function () {
				//alert('a');
				tmpStr = $(this).val();
				if(tmpStr != "547"){ //NO MOSC
					$('#deliv1110').css("display","none");
					$('#deliv1118').css("display","none");
					$('#pay1114').css("display","none");
					$('#deliv1112').css("display","block");
					$('#windsender1110').removeAttr("checked");
					$('#windsender1114').removeAttr("checked");
					$('#windsender1112').attr('checked', true);
					$('#street').addClass('required');
					$('#bild').addClass('required');
					$('#addr .windinplabel span').css('display',"inline");
				}else{ // MOSC
					$('#pay1114').css("display","block");
					$('#deliv1112').css("display","none");
					$('#deliv1110').css("display","block");
					$('#deliv1118').css("display","block");
					//$('#deliv1110 :label').addClass("reddltext");
					$('#windsender1112').removeAttr("checked");
					$('#windsender1110').attr('checked', true);

				//$('#windsender1112').removeAttr("checked")
				//alert($('#windsender1110').attr('checked')+tmpStr);
				}
			});
		});
	}
	windEvent();
	// Quick ----------------------------------------------------------------------------------------------------------------------------
	$("input.quick, a.quick_order").click(function(){
		var animInterval;
		eid = $(this).attr("rel");
		url = "/quick.php?ajax=Y&ID="+eid;
		$.ajax({
			url: url,
			cache: false,
			beforeSend: function(){
				$("#quick").empty();
				// Активация Анимации
				animInterval = loadingAnimator ();
				$("div.loadingimg").show();
			},
			success: function(html){
				$("#quick").append(html);
				height = $(document).scrollTop()+10;
				$("div.fastorderwindow").css("top",height+"px");
				$("#quick").show();
				$("div.fastorderwindow").css("top",height+"px");
				$('#brekedlayer').fadeIn('slow');
				// Дизактивация анимации когда окно загрузилось
				$("div.loadingimg").hide();
				clearInterval(animInterval);
				// Привяжем события к новым элементам в DOM------------------------------
				// События окна --------------
				windEvent();
				// Validation ----------------
				$("#iblock_add").submit(function(){
					var options = {
						errorContainer: ".error"
					}
					var errorAmount = 0;
					// оплата
					var val = $(".pay :checked").val();
					if (!val) {
						$(".methodPay").addClass("divError");
						errorAmount++;
					}
					// доставка
					val = $(".methodDel input:checked").val();
					if (!val) {
						$(".methodDel").addClass("divError");
						errorAmount++;
					}
					var mobphone = $('#mobphone').val();
					var homephone = $('#homephone').val();
					if(homephone == "" && mobphone == ""){
						errorAmount++;
						$("#contphonname").css("border","1px solid red");
					}
					var collection = $("#"+ $(this).attr("id") +" input[type='text']");
					collection.add("#"+ $(this).attr("id")+" input[type='radio']");
					collection.add("#"+ $(this).attr("id")+" input[type='file']");
					collection.add("#"+ $(this).attr("id")+" textarea");
					collection.add("#"+ $(this).attr("id")+" select");
					collection.each(function() {
						var element = $(this);
						var length = $.trim(element.attr('value'));
						if (!length && element.hasClass("required")) {
							if(element.attr("id") == 'idcode')
							{
							//alert("test");
							//var delmet = $(".methodDel input:checked").val();
							//if(delmet == "1802" || delmet == "1800"){
							//	element.addClass('inputError');
							//	errorAmount++;
							//}
							}else{
								element.addClass('inputError');
								errorAmount++;
							}
						//
						}
						else {
							if(element.attr("id") == 'email'){
								var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
								if(!emailReg.test(element.val())) {
									alert("Введите правильный email")
									element.addClass('inputError');
									errorAmount++;
								}
							}else
								element.removeClass('inputError');
						}
					});
					collection.keypress( function (){
						$(this).removeClass('inputError');
					});
					collection.change( function() {
						if (($(this).attr('value')).length < 1) {
							$(this).addClass('inputError');
						}
						else {
							$(this).removeClass('inputError');
						}
					});
					if (errorAmount) {
						$(options.errorContainer).html('<p style="color:red; font-size:14px;">Заполните пожалуйста правильно выделенные поля</p>');
						$(options.errorContainer).show();
						return false;
					}
					else {
						$(options.errorContainer).hide();
					}
					return submitForm();
				});
				// Submit form -----------------------------------------------------------------
				function submitForm() {
					var animInterval;
					var options = {
						target: "#iblockrequest",
						beforeSubmit : function(){
							// Активация Анимации
							animInterval = loadingAnimator ();
							$("div.loadingimg").show();
							$("div.fastorderwindow").append('<div id="iblockrequest" class="windpostblk"></div>');
						},
						success: function(responseText) {
							// Дизактивация анимации когда окно загрузилось
							$("div.loadingimg").hide();
							clearInterval(animInterval);
							$("#iblock_add").remove();
							$('#iblockrequest').html(responseText);
							//$('#iblockrequest').css('top','1300px');
							$('.fastorderwindow').css('top','1000px');
							windEvent();
							console.log(responseText);
						}
					};
					var qString = $("#iblock_add").formSerialize();
					$("#iblock_add").ajaxSubmit(options);
					return false;
				}
				//------------------------------------------------------------------------------------------
				// Unknow what this --------------------------------------------------------------
				function showResponse(responseText, statusText, xhr, $form)  {
					confirm (responseText)
					$('#order_form form').trigger( 'reset' );
					$.fancybox.close();
				}
				function setSamo() {
					$("#pay708").show();
					$("#pay712").show();
					$("#pay1799").show();
					$('#pay1801').show();
					//$("#windsender1800").removeAttr('checked');
					$("#pay712 input").removeAttr('checked');
					$("#addr input").removeClass("required");
					$(".methodDel").removeAttr("divError");
				}
				function setEMS() {
					setCurier();
					$('#pay708').hide();
					$('#windsender708').removeAttr("checked");
					$('#pay1801').hide();
					$('#windsender1801').removeAttr("checked");
					$(".store input").removeAttr("checked");
					$(".store").removeClass("windch");
					$(".store").addClass("windunch");
				}
				function setCurier() {
					$('#pay1801').show();
					$("#pay712").hide();
					$("#pay1799").hide();
					$("#pay1799 input").removeAttr('checked');
					city = $("select[name='PROPERTY[103531]']").val();
					if(city=="705") {
						$("#pay708").show();
					//$("#deliv1800").show();
					}
					else {
						$("#pay708").hide();
						//$("#deliv1800").hide();
						$("#pay708 input").removeAttr('checked');
					}
					$("#street").addClass("required");
					$("#bild").addClass("required");
					$(".methodDel").removeClass("divError");
				}
				function setBank() {
					//alert("ok");
					//$(".pay").hide();
					$("#pay1801").hide();
					$("#pay1801 input").removeAttr('checked');
					$("#pay708").hide();
					$("#pay708 input").removeAttr('checked');
					$("#pay1799").hide();
					$("#pay1799 input").removeAttr('checked');
				}
				//-------------------------------------------------------------------------------------
				//$(".windradioslev").css("display","none");
				$(".methodPay input").click(function(){
					$(".methodPay").removeClass("divError");
				});
				$("#windsender707").click(function(){
					$(".windradioslev").css("display","block");
					$("#addr").hide();
					$("#addr select").attr("selected","");
					setSamo();
				});
				$("#windsender1800").click(function(){
					setEMS();
				});
				$("#windsender1802").change(function(){
					setBank();
				});
				$("#windsender706").click(function(){
					setCurier();
					//$(".windradioslev").css("display","none");
					$("#addr").show();
					$(".store").removeClass("windch").addClass("windunch");
					$("label.store").removeClass("windch").removeClass("reddltext");
					$(".store input").attr("checked","");
					// city
					city = $("select[name='PROPERTY[103531]']").val();
					if(city=="705") {
						$("#pay708").show();
					} else {
						$("#pay708").hide();
						$("#pay708").attr("checked","");
					}
				});
				$("select[name='PROPERTY[103531]']").change(function(){
					if($(this).val()==705) {
						$("#pay708").show();
						//$("#pay1799").show();
						$("#deliv1800").hide();
					} else {
						$("#pay708").hide();
						$("#deliv1800").show();
						$("#paywindradioflev input").removeAttr('checked');
						$("#pay1799").hide();
						$("#pay1799 input").removeAttr('checked');
					}
				});
				/**/
				$(".store input").click(function(){
					$("#addr").hide();
					$("#addr select").attr("selected","");
					$(".windradioflev .windch input").removeAttr('checked');
					$(".windradioflev #del706").removeClass("windch").addClass("windunch");
					$(".windradioflev #del1800").removeClass("windch").addClass("windunch");
					$(".windlabel").removeClass("reddltext");
					// tsv
					//$("#del706").removeClass("windch").addClass("windunch");
					//$("#del706 input").removeAttr('checked');
					//alert($("#windsender1800").attr("checked"));
					// tsv =================
					$("#del707").removeClass("windunch").addClass("windch");
					$("#del707 input").attr("checked","check");
					setSamo();
				});
			/*/
				// tsv
				$('.windhideedcheck').change(function() {
					selid = $(this).val();
					if(selid == '1800')
					{
						$('#pay1801').hide();
						$('#windsender1801').removeAttr("checked")
					}
					else $('#pay1801').show();
				});
	// tsv ===
    /**/
			// End Unknow what this ----------------------------------------------------
			/* YANDEX ADDRESS */ 
			$("#quick_yandex").click(function(){				
				window.open("/quick/yandex.php", "yandex", "toolbar=0,width=1000,height=900");							
				$('.fastorderwindow').css('top','15px');
			});
			/* YANDEX ADDRESS */
			//--------------------------------------------
			}
		});
		return false;
	});
});

/* YANDEX ADDRESS */
function yandex_answer(n) { 
	if(n[16])
		document.getElementById('name').value = n[16];				
	if(n[15])
		document.getElementById('secondname').value = n[15];
	//if(n[17])
		//document.getElementById('lostname').value = n[17];
	if(n[18])
		document.getElementById('mobphone').value = n[18];
	if(n[19])
		document.getElementById('homephone').value = n[19];
	if(n[20])
		document.getElementById('email').value = n[20];
	if(n[3])
		document.getElementById('street').value = n[3];
	if(n[4])
		document.getElementById('bild').value = n[4];
	if(n[6])
		document.getElementById('flat').value = n[6];
	if(n[7])
		document.getElementById('porch').value = n[7];
	if(n[9])
		document.getElementById('code').value = n[9];
	//if(n[12])
		//document.getElementById('idcode').value = n[12];
	if(n[5])
		document.getElementById('structure').value = n[5];
	if(n[21])
		document.getElementById('customtext').innerHTML = n[21];
	
	var objSelCity = document.getElementById("city");	
	var city = n[10].toLowerCase();
	for (var i=0; i < objSelCity.options.length; i++)
	{			
		var city_option = objSelCity.options[i].text.toLowerCase();
		
		if (city == city_option){ 
		  objSelCity.options[i].selected = true;
		};
	}
	
	
	/*
	 
	      
	 **/
} 
/* YANDEX ADDRESS */
