$(document).ready(
  function() {
	
	//search-box
	$("#q").focus(function() {
	  if (($(this).val() == $(this).attr("check")) || ($(this).val().length == 0)) $(this).removeClass("empty").val('')
	})
	$("#q").blur(function() {
	  if (($(this).val() == $(this).attr("check")) || ($(this).val().length == 0)) $(this).addClass("empty").val($(this).attr("check"))
	})
	
	//regions
	$(".current-region a").click(
	  function() {
		$("#shadow").fadeIn("fast")
		$("#regions").fadeIn("fast")
		return false;
	  }
	)
	$("#shadow").click(
	  function() {
		closeRegions()
	  }
	)
	$("#regions .closer").click(
	  function() {
		closeRegions()
	  }
	)
	$("#landing .popup").click(
	  function() {
		$("#shadow").fadeIn("fast")
		$("#regions").fadeIn("fast")
		return false;
	  }
	)
	
	
	//slider
	$(".slider h3").click(
	  function() {
		var x = $(this).parent()
		if (x.hasClass('opened')){
		  x.find(".holder").hide()
		  x.removeClass("opened")
		}
		else
		{
		  x.find(".holder").show()
		  x.addClass("opened")
		}
		return false
	  }
	)
	
	//forms
	$("form").not(".search-box form, .connect form, #info-feedback form").jqTransform({imgPath:"/f/i/forms/"});

	$(".binfo").click(function() {
		$(".mcol .mopen").removeClass("mopen");
		$(this).parents(".mcol li").toggleClass("mopen");
		})
	$(".map-buble .close").click(function() {
		$(this).parents(".mcol .mopen").removeClass("mopen");
		})

	$(".mb-link").click(function() {
		$(".mb-serv .mopen").removeClass("mopen");
		$(this).parents(".mb-serv li").toggleClass("mopen");
		return false;
		})
	$(".map-buble .close").click(function() {
		$(this).parents(".mb-serv .mopen").removeClass("mopen");
		})

	$(".map-marker").click(function() {
		$(".map-marker-open").removeClass("map-marker-open");
		$(".map-wrap3").addClass("mw-index");
		$(this).addClass("map-marker-open");

		return false;
		})
	$(".map-wrap3").click(function() {
		$(".mw-index").removeClass("mw-index");
		$(".map-marker-open").removeClass("map-marker-open");
		})
	
	
	// faq
	var slideList = $('#faqs, dl.slideText');
	$('dt a', slideList).click(
		function() {
			var prnt = $(this).parent();
			if (!prnt.hasClass('expanded')) {
				prnt.next('dd:eq(0)').slideDown(450, function() { prnt.addClass('expanded'); });
			} else {
				prnt.next('dd:eq(0)').slideUp(450, function() { prnt.removeClass('expanded'); });
			}
			return !1;
		}
	);
	
	if ($("#info-feedback").size()) {
		function isValidEmailAddress(emailAddress) {
			var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
			return pattern.test(emailAddress);
		}
		$("#info-feedback-form").click(function(){
			$("#info-feedback").show();
			return false;
		});
		$("#info-feedback .continue").click(function(){
			activeIndex = $("#info-feedback ul.steps li.active").index();
			nextIndex = activeIndex + 1;
			errorExist = false;
			activeItem = $("#info-feedback .items .item").eq(activeIndex);
			$(".error", activeItem).hide();
			$(".requared input, .requared textarea", activeItem).each(function(){
				if ($(this).val() == "") {
					$(".error", activeItem).show();
					errorExist = true;
				}
				else if ($(this).attr("id") == "email") {
					if (!isValidEmailAddress($(this).val())) {
						$(".error", activeItem).show();
						errorExist = true;
					}
				}
			});
			
			if (errorExist == false && nextIndex != 3) {
				$("#info-feedback ul.steps li.active").removeClass("active");
				$("#info-feedback ul.steps li").eq(nextIndex).addClass("active");
				$("#info-feedback .items .items-inner").animate({
					marginLeft: "-"+(nextIndex*455)+"px"
				});
			}
			else if (errorExist == false && nextIndex == 3){
				data = $.ajax({
					type : 'POST',
					url : '/handlers/feedback.php?'+Math.random(),
					data : $("#info-feedback form").serialize(),
					cache: false,
					async: false,
					success: function(data) {
						activeItem = $("#info-feedback .items .item").eq(nextIndex);
						$("p.success", activeItem).html(data);
						$("#info-feedback ul.steps").hide();
						$("#info-feedback .items .items-inner").animate({
							marginLeft: "-"+(nextIndex*455)+"px"
						});
					}
				}).responseText;
			}
			return false;
		});
		$("#info-feedback .back").click(function(){
			activeIndex = $("#info-feedback ul.steps li.active").index();
			$("#info-feedback ul.steps li.active").removeClass("active");
			$("#info-feedback ul.steps li").eq(activeIndex-1).addClass("active");
			$("#info-feedback .items .items-inner").animate({
				marginLeft: "-"+((activeIndex-1)*455)+"px"
			});
			return false;
		});
		$("#info-feedback .close").click(function(){
			$("#info-feedback").hide();
			return false;
		});
	}
	
	var LANG;
	if( window.location.href.indexOf("/ru/") != -1 ){
		LANG = "ru";
	}else if( window.location.href.indexOf("/en/") != -1 ){
		LANG = "en";
	}else{
		LANG = "uz";
	}
	
	$.ctrl = function(key, callback, args) {
    var code = (IsNumeric(key) ? parseInt(key) : key.toString().charCodeAt(0));
    if(LANG == 'ru'){
		var settings = {
			  maxlen: 250,
				wText:  {
				  Big: "Выдели текст с ошибкой меньшего размера.",
					NoSupport: "Ваш браузер не поддерживает возможность перехвата выделенного текста",
					Error: "Орфографическая ошибка в тексте",
					Send: "Отослать сообщение об ошибке редакторам? \n Ваш браузер останется на той же странице.",
					Mark: "<ошибка>",
					Url: "Страница: ",
					VarErr: "Статья: ",
					Err: "Ошибка:   "
				}
			};
	}else if (LANG == 'en'){
		var settings = {
	          maxlen: 250,
	            wText:  {
					Big: "Select the text with error smaller.",
					NoSupport: "Your browser does not support the interception of selected text",
					Error: "Spelling mistake in the text",
					Send: "Send error message to editors? \n Your browser will remain on the same page.",
					Mark: "<mistake>",
					Url: "Page: ",
					VarErr: "Article: ",
					Err: "Mistake:   "
	            }
	        };	
	}else if (LANG == 'uz'){
		var settings = {
	          maxlen: 250,
	            wText:  {
					Big: "Выдели текст с ошибкой меньшего размера.",
					NoSupport: "Sizning brauzeringiz belgilangan matnni olish imkoniyatini bermaydi",
					Error: "Matnda orfografik xato",
					Send: "Xato haqida xabarni muharrirga yuborish kerakmi? \n Sizning brauzeringiz shu sahidfada qoladi.",
					Mark: "<xato>",
					Url: "Sahifa: ",
					VarErr: "Maqola: ",
					Err: "Xato:   "
	            }
	        };	
	}
	
	
    $(document).keydown(function(e) {
        if(!args) args=[]; // IE barks when args is null
        if(e.keyCode == code && e.ctrlKey) {
          var text = getSelectionText();
          var re = /\r|\n/gi;
          
          if (text == null) {
                    alert(settings.wText.NoSupport);
                    return;
                }
                
                text = text.toString().replace(re, " ");
                
                if (text.length > settings.maxlen) {
                    alert(settings.wText.Big);
                    return;
                }
                
                if (text == "") return;
          
          if (confirm(settings.wText.Error + "\n" + settings.wText.Mark + text + settings.wText.Mark + "\n\n" + settings.wText.Send)){
            args.push(text);
            callback.apply(this, args);
          }
          
          return false;
        }
    });
  };
  
	  function IsNumeric(n) {
	    return !isNaN(parseFloat(n)) && isFinite(n);
	  };
	
	  function getSelectionText(){
	    if (window.getSelection){
	        selectionTxt = window.getSelection();
	      }
	      else if (document.getSelection){
	        selectionTxt = document.getSelection();
	      }
	      else if (document.selection){
	        selectionTxt = document.selection.createRange().text;
	      }
	    
	      return selectionTxt;
	  };

		 	$.ctrl(13, function(text) {
			var url = window.location.href;
			var hostname = window.location.hostname;
			var string = {'text':text, 'url': url, 'hostname': hostname}
			
			$.ajax({
				type: "POST",
				url: "/handlers/error_send.php",
				dataType: "json",
				data: string,
				success: function(){
				}
				});
			//window.location.reload(true);
			});
			
	
	
	
	$('.swf-show').click(function() {
		File = $(this).attr('href');
		window.open('/handlers/swf_show.php?file='+File, 'swf', "menubar=no,location=0,resizable=yes,scrollbars=no,status=no,height=784,width=1026")
		return false;
	});
  }
)


function closeRegions()
{
  $("#regions").fadeOut("fast")
  $("#shadow").fadeOut("fast")
}

