/**
 * @author <a href="http://media5.com">Media5</a> - <a href="mailto:banzalik@gmail.com">Бойченко Александр</a>
 * @description скрипты для m5 css framework
 */

 /**
 * @description полная загрузка страницы, картинки при этом уже загрузились
 */
//document.onmousedown=function(){return false}
document.documentElement.id = "js" // добавляем тегу html id=js

window.onload=documentLoaded; // присваиваем функцию documentLoaded

/**
 * @description вызов функций при полной загрузке страницы, картинки при этом уже загрузились
 */
function documentLoaded(){
	 loaderLeft();
	 //$(".loader").remove();
}


/**
 * @description вызов функций при полной загрузке DOM дерева, картинки при этом еще не загрузились
 */
$(document).ready(function(){
			$("<div class='pxppx'></div>").appendTo(".wrapper p");
			autoclearInput();
			m5formsWidthNormalize();
})

var infoHover='';

/**
 * @description очистка инпутов, при клике на них
 */
function autoclearInput(){
	$(".autoclear").each(function(){
		$(this).attr("defaultvalue",$(this).attr("value")); // записываем в defaultvalue значение по умолчанию, необходимо для проверки нового стекста со старым
	});

	$(".autoclear").click(function(){
		if ($(this).attr("value")==$(this).attr("defaultvalue")) { // проверяем совпадают ли value и defaultvalue
			$(this).attr("value", ""); // сбрасываем значение value
		}
	})
}


/**
 * @description выравнивание input[type=text], input[type=password], textarea
 */
function m5formsWidthNormalize(){
	if ($.browser.msie && $.browser.version<7) {
		$("select.m5formsNormalize").each(function(i){
			var m5formnormalizepadding=Math.ceil(Number(String($(this).css("padding-left")).slice(0,-2)))+Math.ceil(Number(String($(this).css("padding-right")).slice(0,-2)));
			var m5formnormalizeborder= Math.ceil(Number(String($(this).css("border-left-width")).slice(0,-2)))+Math.ceil(Number(String($(this).css("border-right-width")).slice(0,-2)));
			var m5formnormalizewidth=Math.ceil(Number($(this).width()))+m5formnormalizepadding+m5formnormalizeborder*2;
			$(this).width(m5formnormalizewidth);
		})
	} else {
		$("input[type=text].m5formsNormalize, input[type=password].m5formsNormalize, textarea.m5formsNormalize").each(function(i){
			var m5formnormalizepadding=Math.ceil(Number(String($(this).css("padding-left")).slice(0,-2)))+Math.ceil(Number(String($(this).css("padding-right")).slice(0,-2)));
			var m5formnormalizewidth=Math.ceil(Number($(this).width()))-m5formnormalizepadding;
			$(this).width(m5formnormalizewidth);
			})
		$("select.m5formsNormalize").each(function(i){
			var m5formnormalizepadding=Math.ceil(Number(String($(this).css("padding-left")).slice(0,-2)))+Math.ceil(Number(String($(this).css("padding-right")).slice(0,-2)));
			var m5formnormalizeborder= Math.ceil(Number(String($(this).css("border-left-width")).slice(0,-2)))+Math.ceil(Number(String($(this).css("border-right-width")).slice(0,-2)));
			if ($.browser.msie && $.browser.version<8){
				var m5formnormalizewidth=Math.ceil(Number($(this).width()))+m5formnormalizepadding+m5formnormalizeborder*2;
			} else {
				var m5formnormalizewidth=Math.ceil(Number($(this).width()))+m5formnormalizepadding+m5formnormalizeborder;
			}
			$(this).width(m5formnormalizewidth);
		})
	}
}

function  getPageSize() {
	var xScroll, yScroll;

	if (window.innerHeight && window.scrollMaxY) {
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else if (document.documentElement && document.documentElement.scrollHeight > document.documentElement.offsetHeight){ // Explorer 6 strict mode
		xScroll = document.documentElement.scrollWidth;
		yScroll = document.documentElement.scrollHeight;
	} else { // Explorer Mac...would also work in Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}

	var windowWidth, windowHeight;
	if (self.innerHeight) { // all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}

	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else {
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}

	return [pageWidth,pageHeight,windowWidth,windowHeight];
}




function mainpage() {
	var getPageSizeArr=getPageSize();
	var pageWidth=getPageSizeArr[0];
	//console.log('pageWidth',pageWidth);
	//alert(pageWidth);
	var pageHeight=getPageSizeArr[1];
	//console.log('pageHeight',pageHeight);
	var windowWidth=getPageSizeArr[2];
	//console.log('windowWidth',windowWidth);
	var windowHeight=getPageSizeArr[3];
	//console.log('windowHeight',windowHeight);
	// hide scroll mainScreen
	if ( pageWidth<1000)
	{
		pageWidth=1000;
	}
	if ( windowHeight<400)
	{
		windowHeight=400;
	}

	$(".mainScreen").width(pageWidth);
	$(".mainScreen").height(windowHeight);
	$(".mainBgJs").width(pageWidth);
	$(".mainBgJs").height(windowHeight);
	$(".loader").width(pageWidth);
	$(".loader").height(windowHeight);
	

	

	// up to div width link
	var amendment=(pageHeight-$(".mainBg").height())/2;
	/*console.log('amendment',amendment);*/
	$(".mainBg").css("top",amendment, "left",0);

	// scrolling
	var menuAnimate=1;
	$(".menu a").click(function(){
		var href=$(this).attr("href");
		//console.log('href',href);
		var toLeft=$(href).css("left").slice(0,-2)-(pageWidth/2);
		var selector=$(href).html();
		//alert(selector);
		if (toLeft<0) {  toLeft=0; }
		//if (toLeft>pageWidth) { toLeft=pageWidth; }
		//alert (toLeft);
		//alert($(".mainBg").css('left'));
		//console.log('toLeft',toLeft);
		if (menuAnimate==1){
			if ($(".loader").length)
			  {	
				   
				   $(".loader").animate({
					width: 0
					}, 1500, function(){
							$(".loader").remove();
								$(".rightCurr").css({	
									  "width": "5%",
									  "margin-left":"-5%"
								})	
					})		  
        		
			   }
				menuAnimate=0;
				$(".mainBg").animate({
				left: -toLeft
				}, 1500, function(){ 
					menuAnimate=1;
					if (selector!=''){
						selectros=$(selector);
						$(".hovers").addClass("hideHover");
						$(".hovers").removeClass("thisActive");
						selectros.hide();
						//selectros.addClass("thisActive");
						selectros.removeClass("hideHover");
						selectros.fadeIn("slow", function(){
														  
														  $(this).addClass("thisActive");
									/*selectros.fadeOut("slow", function(){
										selectros.addClass("hideHover");
										selectros.show();
									});*/									
									
							});
					}

					
				});


		}
		return false;
	});

	var slide=0;
	$("map#Map area").hover(
      function () {
		  $(".hovers").addClass("hideHover");
		  var slide='.'+$(this).attr("rel");
		  //alert(slide);
		  $(slide).removeClass("hideHover");
      },
      function () {
		  $(slide).addClass("hideHover");
      }
    );

	$(".hovers").hover(
      function () {
      },
      function () {
		  	$(this).addClass("hideHover");
			$('.thisActive').removeClass("hideHover");
      }
    );
	
	
	
	
		
	
				
			$(".mainScreen").mousewheel(function(objEvent, intDelta){
												 
				var pageW=getPageSizeArr[0];
				
			    if (intDelta > 0){
					var mbg=$(".mainBg");
					var toLft=mbg.css("left").slice(0,-2)*1;
					if (toLft<0) {
						var leftCss= toLft+100;
						if (leftCss>=0) {leftCss=0; $(".leftCurr").hide(); } 
						mbg.css({left: leftCss});
						
					}				
						$(".rightCurr").show();
				}
			    else if (intDelta < 0){
					var mbg=$(".mainBg");
					var toLft=-mbg.css("left").slice(0,-2)*1;
					if (toLft<(4800-pageW)) {
						mbg.css({left: -toLft-100})						
						$(".leftCurr").show();
					} else {
						$(".rightCurr").hide();
					
					}
				}
			});
	


	winresize ();
	mainCurrs(windowHeight,pageWidth);

}


function winresize (){

			$(window).resize(function(){

	var getPageSizeArr=getPageSize();
	var pageWidth=getPageSizeArr[0];
	//console.log('pageWidth',pageWidth);
	//alert(pageWidth);
	var pageHeight=getPageSizeArr[1];
	//console.log('pageHeight',pageHeight);
	var windowWidth=getPageSizeArr[2];
	//console.log('windowWidth',windowWidth);
	var windowHeight=getPageSizeArr[3];
	//console.log('windowHeight',windowHeight);
	// hide scroll mainScreen
	if ( pageWidth<1000)
	{
		pageWidth=1000;
	}
	if ( windowHeight<400)
	{
		windowHeight=400;
	}

	$(".mainScreen").width(pageWidth);
	$(".mainScreen").height(windowHeight);
	$(".mainBgJs").width(pageWidth);
	$(".mainBgJs").height(windowHeight);

	// up to div width link
	var amendment=(pageHeight-$(".mainBg").height())/2;
	/*console.log('amendment',amendment);*/
	$(".mainBg").css("top",amendment, "left",0);

	mainCurrs(windowHeight,pageWidth);

		});

}


function mainCurrs(hg, wg){
	var menuAnimate=1;
	var mH=$(".menu").height();
	totalh=hg-mH;
	$(".mainCurrs").css({top:mH, height:totalh});
		$(".rightCurr").hover(
		  function () {
			  var toLft=4800-wg;
			  var totime=toLft*2.5;
			  //alert(toLft);
				$(".leftCurr").show();
			  	$(".mainBg").animate({left: -toLft}, totime, function(){
					$(".rightCurr").hide();
					$(".leftCurr").show();
				});
			  
			  			  
			  
		/*	  if ($(".loader").length)
			  {	
				   
				   $(".loader").animate({
					width: 0
					}, 1500, function(){
							$(".loader").remove();
								$(".rightCurr").css({	
									  "width": "5%",
									  "margin-left":"-5%"
								})	
					})		  
        		
			   }*/
			  
			  
			  

		  },
		  function () {
			  $(".mainBg").stop();
			  $(".leftCurr").show();
		  }
		);

		$(".leftCurr").hover(
		  function () {
			$(".rightCurr").show();
			  if ($(".mainBg").css("left").slice(0,-2)==0)
			  {
				$(".leftCurr").hide();				
				}
				
			  var toLft=-$(".mainBg").css("left").slice(0,-2);
			  var totime=toLft*2.5;
			  //console.log(totime);
			  //alert(toLft);
			  $(".mainBg").animate({
				left: 0
				}, totime, function(){$(".leftCurr").hide();})

		  },
		  function () {
			  $(".mainBg").stop();
		  }
		);





}


function checkPhorm(phorm, fields, names){
			for(i in fields){
				if(phorm.elements[fields[i]].value == ''){
					alert('Заполните, пожалуйста, поле "'+names[i]+'"!');
					phorm.elements[fields[i]].focus();
					return false;
					}
				 else if ((phorm.elements[fields[i]].name == 'name' && !phorm.elements[fields[i]].value.match(/^([а-яA-Яa-zA-Z]+\.?-?\s*)+$/)) || (phorm.elements[fields[i]].name == 'email' && !phorm.elements[fields[i]].value.match(/^\w+([.\-]?\w+)*@\w+([.\-]?\w+)*\.\w{2,4}$/)) || (phorm.elements[fields[i]].name == 'phone' && !phorm.elements[fields[i]].value.match(/^([0-9()\-+,;]+\s*)+$/))){
					alert('Пожалуйста, корректно заполните поле "'+names[i]+'"!');
					phorm.elements[fields[i]].value = '';
					phorm.elements[fields[i]].focus();
					return false;
					 }
				} return true;
			}
	
function str_replace(search, replace, subject) {
   
    var f = search, r = replace, s = subject;
    var ra = r instanceof Array, sa = s instanceof Array, f = [].concat(f), r = [].concat(r), i = (s = [].concat(s)).length;
 
    while (j = 0, i--) {
        if (s[i]) {
            while (s[i] = (s[i]+'').split(f[j]).join(ra ? r[j] || "" : r[0]), ++j in f){};
        }
    };
 
    return sa ? s : s[0];
}



function loaderLeft() {
	$(".loader").css({	
	  "background-color": "transparent",
	  "z-index": 10 ,
      "left": "auto"
	});
	
	
	$(".loader").animate({
	  "right": "0",
	  "width": "230px"
    }, 1500, function(){	
		$(".rightCurr").css({	
		  "width": "230",
		  "margin-left": "-230"
		});		
	});

}