/**
 * @author <a href="http://media5.com">Media5</a> - <a href="mailto:banzalik@gmail.com">Бойченко Александр</a>
 * @description скрипты для m5 css framework
 */

 /**
 * @description полная загрузка страницы, картинки при этом уже загрузились
 */
document.documentElement.id = "js" // добавляем тегу html id=js

window.onload=documentLoaded; // присваиваем функцию documentLoaded

/**
 * @description вызов функций при полной загрузке страницы, картинки при этом уже загрузились
 */
function documentLoaded(){
	 loaderLeft();
	 img_no();
	 if ($('div.leftDescription img').length!=0) fly_gallery();
	 social();
	 days();
	 statistiks();
	 ttb();
}

function ttb()
{
	
if($(window).height() < 804)
	{
		var m = parseFloat($('.mainBg').css('top'));
		var d = 395-(m*-1)-50
		var h = $(window).height()-d-$('.tumba_bot').height()+60;
		$('.tumba_bg').height(h);
		$('.tumba_bot').css('bottom','').css('top',h+50);
	}
}

function statistiks() {
	var height_stat=$(document).height();
	var left_media5=($('body').width()-950)/2+25;
	var ha=height_stat-56+'px';
    var ha2=height_stat-40+'px';
	$('#mail_ru,#rambler_ru').css({'top':ha});
	$('a.media5_logo').css({'top':ha2,'left':left_media5});
}

function days() {
	var hover=0;
	var index=0;
	$('div.some_day').hover(function(){
		   if (!$(this).hasClass('day_active')) {hover=1;index=parseInt($(this).attr('rel'));$(this).find('img').attr('src','/images/day_'+index+'.png')}
		},
		function(){
		  if (hover==1) {hover=0;$(this).find('img').attr('src','/images/day_'+index+'_not'+'.png')}
		}
		);
}


function social() {
	$('div.social_icons_2 a').hover(function(){
											 w=$(this).width();
											 $(this).find('div').css('left',w/2-5).show();
											 },
									function(){
											 $(this).find('div').hide();
										}		 
									)
	}

function img_no() {
	if ($('div.photoBigleadingNew img').length==0 && $('div.acterinfo').length==0) {
		  $('div.photoBigleadingNew').remove();
		  $('div.leftDescription').css('marginLeft',0);
		}
	}

function fly_gallery () {
		var src;
		$('div.leftDescription img').each(function(i){
						   src=$(this).attr('src');
						   if(!$(this).parent('a'))
						   $(this).wrap('<a href="' + src + '" class="m5_gallery"></a>');
	    })
		gal1 = new m5_gallery('gal1', 'none', '/images/m5_gallery/next.png', '/images/m5_gallery/prev.png', '/images/m5_gallery/close.png', 5);
	}

/**
 * @description вызов функций при полной загрузке DOM дерева, картинки при этом еще не загрузились
 */
$(document).ready(function(){
			$("<div class='pxppx'></div>").appendTo(".wrapper p");
			autoclearInput();
			m5formsWidthNormalize();
		    statistiks();
			hover_menu();
			inner_pages_mobile();
})


function inner_pages_mobile() {
	if ($('body.spPage').length!=0)	{
			var wid=$(window).width()
			if (wid<950) { 
				$('div.wrapper').width(wid).css('marginLeft',-wid/2);
				$('div.crown').css('marginLeft',wid-146);
				$('div.wrapper_in').show()
			}
		} 
}

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];
	
	var pageHeight=getPageSizeArr[1];
	
	var windowWidth=getPageSizeArr[2];
	
	var windowHeight=getPageSizeArr[3];
	
	//svg vml
	var paper = Raphael(document.getElementById("megaloader"), windowWidth, windowHeight);
	paper.safari();
	var right_wing=paper.image("images/right_wing.png",windowWidth/2+9,windowHeight/2-56,106,106);
	var left_wing=paper.image("images/left_wing.png",windowWidth/2-123,windowHeight/2-56,106,106);
	var vector=paper.image("images/loader_vector.png",windowWidth/2-103, windowHeight/2-95, 206, 190);
	vector.toBack()
	
	function wings() {
		left_wing.animate({rotation:-45},250,function(){this.animate({rotation:0},250)});
		right_wing.animate({rotation:45},250,function(){this.animate({rotation:0},250)})	
	}
	var wings_repeat=setInterval(wings,500);
	//svg vml
	
	var paper_nogi = Raphael(document.getElementById("nogi"), 200, 200);
	paper_nogi.safari();
	var noga1=paper_nogi.image("images/noga1.png",47,9,38,173);
	var noga2=paper_nogi.image("images/noga2.png",85,15,37,174);
	noga2.rotate(-10,18,18);
	noga1.rotate(0,18,18);
	function noga1_up() {noga1.animate({rotation:-15,x:67},1000,function(){noga1_down()})}
	function noga1_down() {noga1.animate({rotation:0,x:47},1000)}
	function noga2_up() {noga2.animate({rotation:-35,x:95,y:-5},1000,function(){noga2_down()})}
	function noga2_down() {noga2.animate({rotation:-10,x:85,y:10},1000)}
	var noga1_int;
	var noga2_int;
	
	$('#nogi').hover(function(){
		$(this).find('image:eq(0)').live('click',function(){alert('1')});
		$(this).find('image:eq(1)').live('click',function(){alert('1')});
	});

	function noga1_start() {
			setTimeout(function(){noga1_up()},0)	
			return noga1_int=setInterval(function(){noga1_up()},2000);
	}
	noga1_start();
	function noga2_start() {
			setTimeout(function(){noga2_up()},0)	
			return noga2_int=setInterval(function(){noga2_up()},2000);
		}
	noga2_start();
	
	function microhover() {
	$('div.new_slide21 a').hover(function(){
										clearInterval(noga1_int);
										clearInterval(noga2_int);
										  },
								 function(){
										noga1_start();
										noga2_start();
								 		}
								)
	}
	setTimeout(function(){microhover()},500);
		
	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);
	$('.megaloader').width(pageWidth);
	$(".megaloader").height(windowHeight);
	var isiPad = navigator.userAgent.match(/iPad/i) != null;		
   	var isiPhone = navigator.userAgent.match(/iPhone/i) != null;
   	var isiPod = navigator.userAgent.match(/iPod/i) != null;
	/*if(isiPad || isiPhone || isiPod){*/
	$('#main_bg').attr('src','/images/blank.gif'); 
	$('#apple_1').attr('src','').load(function(){  // предзагрузка первого куска
								 	$(".megaloader").remove();
									clearInterval(wings_repeat);
								}).attr('src','/images/bgMenu_apple_1.jpg')
	/*
    }
    else {
    $('#main_bg').attr('src','').unbind('load').load(function(){
									$(".megaloader").remove();
									clearInterval(wings_repeat);
								})
	  .attr('src','/images/bgMenu.jpg') 
	}*/
	
	var amendment=(pageHeight-$(".mainBg").height())/2;
	$(".mainBg").css("top",amendment, "left",0);
	// scrolling
	var menuAnimate=1;
	$(".menu a").click(function(){
		var href=$(this).attr("href");
		var act_src=[];
		switch (href) {
			 case '#menuItem1': 
			 	act_src=['/images/hover2.jpg','/images/hover4.jpg','/images/hover5.jpg','/images/hover6.jpg'];
				break;
			 case '#menuItem2': 
			 	act_src=['/images/hover8.jpg','/images/hover11.jpg','/images/hover12.jpg'];
				break;
			 case '#menuItem3': 
			 	act_src=['/images/hover1.jpg'];
				break;
			 case '#menuItem4': 
			 	act_src=['/images/hover7.jpg'];
				break;
			 case '#menuItem5': 
			 	act_src=['/images/hover14.jpg','/images/hover15.jpg'];
				break;
			 case '#menuItem6': 
			 	act_src=['/images/hover9.jpg'];
				break;	
			 case '#menuItem7': 
			 	act_src=['/images/hover16.jpg','/images/hover17.jpg'];
				break;
			 case '#menuItem8': 
			 	act_src=['/images/hover10.jpg'];
				break;
			 case '#menuItem9': 
			 	act_src=['/images/hover19.jpg'];
				break;
			 case '#menuItem10': 
			 	act_src=['/images/hover3.jpg'];
				break;
			 case '#menuItem11': 
			 	act_src=['/images/hover13.jpg'];
				break;
			 case '#menuItem12': 
			 	act_src=['/images/hover18.jpg'];
				break;	
			}
		
		var toLeft=$(href).css("left").slice(0,-2)-(pageWidth/2);
		var selector=$(href).html();
		
		if (toLeft<0) {  toLeft=0; }
		
		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.removeClass("hideHover");
						selectros.each(function(j){
												$(this).find('img').attr('src',act_src[j]);
												})
						selectros.fadeIn("slow", function(){
														  $(this).addClass("thisActive");
						});
					}
				});
		}
		return false;
	});
    
	var slide=0;
	var src;
	$("map#Map area").hover(
      function () {
		  $(".hovers").addClass("hideHover");
		  var slide='.'+$(this).attr("rel");
		  if (slide.length==7) src='/images/hover'+slide.substr(6,1)+'.jpg';
		  if (slide.length==8) src='/images/hover'+slide.substr(6,2)+'.jpg';
		  $('img',slide).attr('src','').load(function(){
										  $(slide).removeClass("hideHover");									   									   
							  })
		  .attr('src',src)
      },
      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(){
	ttb();
	var getPageSizeArr=getPageSize();
	var pageWidth=getPageSizeArr[0];
	var pageHeight=getPageSizeArr[1];
	var windowWidth=getPageSizeArr[2];
	var windowHeight=getPageSizeArr[3];
	
	if ( pageWidth<1000)
	{
		pageWidth=1000;
	}
	if ( windowHeight<400)
	{
		windowHeight=400;
	}

	$(".mainScreen").width(pageWidth);
	$(".mainScreen").height(windowHeight);
	$(".mainBgJs").width(pageWidth);
	$(".mainBgJs").height(windowHeight);

	var amendment=(pageHeight-$(".mainBg").height())/2;
	
	$(".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();
				});
		  },
		  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;
			  $(".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"
		});		
	});

}

//-------------Двойной/нормальный размер видео-----------------------------------
function doubleSize(){
	$("#videolist").hide();
	$("#flvplayer").attr("width",920);
	$("#flvplayer").attr("height",744);
	location.replace('#video_player');
}

function normalSize(){
	$("#flvplayer").attr("width",492);
	$("#flvplayer").attr("height",398);
	$("#videolist").show();
	location.replace('#video_player');
}
//-------------Двойной/нормальный размер видео-----------------------------------

function hover_menu() {
	$('div.menuContent li').hover(function(){
										  $(this).addClass('a_hover');
										  w=$(this).find('span.a_popup').width();
										  $('span.a_popup_b').width(w+6)
										  },
								function(){
										  $(this).removeClass('a_hover');	
										  }		  
								 )
}
