var endCoords = {};
$(document).ready(function(){

	if (navigator.userAgent.toLowerCase().match(/(iphone|ipod|ipad)/)) {
		$('#splashscreen').removeClass('white').addClass('ipad').show();
		$(document.body).bind("touchstart touchmove", function(event) {
    		endCoords = event.originalEvent.targetTouches[0];
		});
	} else {
		$('#splashscreen').hide();
	}

	$('#ipadVideoLoadBtn').click(function(event){
		event.preventDefault();
		if (navigator.userAgent.toLowerCase().match(/(iphone|ipod|ipad)/)) {
			$(api.video).bind('play', function(){
				console.log('начал воспроизводится');
				$(api.video).unbind('play');
				// TODO!! Add callback after video inisialization
				function onCanPlay(){
					console.log('сработал ивент МОГУ воспроизводится');
					// hide preloader
					//opt.preloader('hide');
					console.log('preloader hide onCanPlay');
					api.video.removeEventListener('canplaythrough', onCanPlay, false);
					api.video.removeEventListener('load', onCanPlay, false);
					api.video.removeEventListener('canplay', onCanPlay, false);
					//video is ready
					console.log('video is ready' + api.nowplaylist.ready());
					api.nowplaylist.ready();
					$(api.events).trigger('ready_callback');
				}
				if(api.video.readyState !== 4){ //HAVE_ENOUGH_DATA
					api.video.addEventListener('canplaythrough', onCanPlay, false);
					api.video.addEventListener('canplay', onCanPlay, false);
					api.video.addEventListener('load', onCanPlay, false); //add load event as well to avoid errors, sometimes 'canplaythrough' won't dispatch.
					setTimeout(function(){
						api.video.pause(); //block play so it buffers before playing
					}, 1); //it needs to be after a delay otherwise it doesn't work properly.
				} else {
					// hide preloader
					opt.preloader('hide');
					console.log('preloader hide cideo_is_ready');
					console.log('video is ready');
					api.nowplaylist.ready();
					$(api.events).trigger('ready_callback');
				}
				$(api.events).trigger('init');
				console.log('video init done');
			}); 
			api.video.load();
			api.video.play();
		}
	}); 

	$("#dayNight").click(function(event){
		event.preventDefault();
		var pano = document.getElementById('pano')
		if($(this).hasClass('day') && !$(this).hasClass('night'))
		{
			$.ajax({
				url: "/day-night-switch.html?daytime=night",
				success: function(msg){
					console.log( msg );
				}
			});
			$(this).text('Ночь').removeClass('day').addClass('night');
			if( api.nowpos )
			{
				api.utils.initNewPlaylist(api.playlists['day'], api.nowpos.replace('Night','Day'));
				$('#closeFly').show();
			} else {
				api.utils.initNewPlaylist(api.playlists['day']);
			}

			if(pano) {
				var scene = pano.get('xml.scene');
				viewParams = document.getElementById('pano').get('view');
				document.getElementById('pano').call("loadscene('" + scene.replace('day','night') + "',view.hlookat="+viewParams.hlookat+"&view.vlookat="+viewParams.vlookat+"&view.fov="+viewParams.fov+",MERGE)");
				$('#closeFly').show();
			}

		} else {
			if(!$(this).hasClass('day') && $(this).hasClass('night'))
			{
				$.ajax({url: "/day-night-switch.html?daytime=day"});
				$(this).text('День').removeClass('night').addClass('day');
				if( api.nowpos )
				{
					api.utils.initNewPlaylist(api.playlists['night'], api.nowpos.replace('Day','Night'));
					$('#closeFly').show();
				} else {
					api.utils.initNewPlaylist(api.playlists['night']);
				}

				if(pano) {
					var scene = pano.get('xml.scene');
					viewParams = document.getElementById('pano').get('view');
					document.getElementById('pano').call("loadscene('" + scene.replace('night','day') + "',view.hlookat="+viewParams.hlookat+"&view.vlookat="+viewParams.vlookat+"&view.fov="+viewParams.fov+",MERGE)");
					$('#closeFly').show();
				}
			}
		}
	});

	$("#frame a.infoPoint, #frame a.forwardPoint").not(".threesixty").mouseover(function(){
		$(this).css({'z-index': '1000'});
		var $label = $("span", $(this));

		if($label.data('oldWidth') == undefined || $label.data('oldWidth') == 0)
		{
			$label.css({visibility: 'visible'});
			$label.data('oldWidth', $label.width());
			$label.css({visibility: 'hidden', overflow: 'hidden'});
		}

		if($label.data('oldWidth') == 0) $label.data('oldWidth', 250);

		if($(this).hasClass('inverse'))
		{
			$label.css({right: 0, left: 'auto', opacity: 0, width: 0, visibility: 'visible'}).animate({width: $label.data('oldWidth'),  marginLeft: -parseInt($label.width()), opacity: 1}, 400);
		} else {
			$label.css({opacity: 0, width: 0, visibility: 'visible'}).animate({width: $label.data('oldWidth'), opacity: 1}, 400);
		}
	}).mouseout(function(){
		var $label = $("span", $(this));
		$label.stop(true, false).animate({width: 0, opacity: 0}, 400);
		$(this).css({'z-index': '13'});
	}).not(".forwardPoint").click(function(e){
		e.preventDefault();
	});
	$("#frame a.infoPoint.threesixty").click(function(e){
		e.preventDefault();
	});

	function literOver() {
		console.log("literOver");
		$(this).unbind("mouseover");
		$(this).find("span.mouseover").stop(true,true).animate({'margin-left': 0}, 250, function(){
			$(this).mouseout(literOut);
		});
		$(this).find("span.mouseout").stop(true,true).animate({'margin-right': '-185px'}, 250);
	}

	function literOut() {
		console.log("literOut");
		$(this).unbind('mouseout');
		$(this).stop(true,true).animate({'margin-left': '-185px'}, 250);
		$(this).siblings("span.mouseout").stop(true,true).animate({'margin-right': 0}, 250, function(){
			$(this).parent().mouseover(literOver);
		});
	}

	$("#frame a.literFly").mouseover(literOver);
	if($("#video_target").length > 0)
	{
		$('body').ivideo_init();
	} else {
		$("#dayNight").hide();
		$("#preloader").hide();
	}
	function getSection(loadUrl)
	{
		$("#flatBox").hide();
		$.getJSON(loadUrl, function(data) {

			var literNum = data['liter'].replace("liter-","");
			var sectionNum = data['section'].replace("section-","");
			var floorNum = data['floor'].replace("floor-","");

			$("#floorHeader > h2").text("Литер " + literNum + "   |   Секция " + sectionNum + "   |   Выберите этаж и квартиру");
			
			$("#floorHeader .x-btn").click(function(event){
				event.preventDefault();
				$("#plansBox, #flatBox").hide();
			});

			//Cufon.replace('#contentBoxHeader h2', { fontFamily: 'Univers Condensed', hover: true });

			$("#floorPlaner").html(data['content']);

			$("#floorSelector").html($("#floorSelect").html());

			$("#floorSelect").remove();

			$("#floorSelector").removeClass('twentyFour');

			$("#floorSelector > li:first").remove();
			$("#floorSelector > li:last").addClass('selected');

			if($("#floorSelector > li").length > 18)
			{
				$("#floorSelector").addClass('twentyFour');
			}

			$("#floorSelector > li > a").click(function(event){
				event.preventDefault();
				if(!$(this).parent().hasClass("selected"))
				{
					getFloor($(this).attr("href").replace("#",""));
					$(this).parent().addClass('selected').siblings().removeClass("selected");
				}
			});

			$('#floorPlan .imagemap_inner').unwrap();

			$('#floorPlaner img').imagemap({
				buildShape: function(papper, shape) {
					var bgColor;
					
					flatNum = String(shape.href.replace("#",""));
					if(data['flats']['flat-'+flatNum] != undefined)
						roomsNum = data['flats']['flat-'+flatNum]['roomsNum'];
					else
						roomsNum = 0;

					switch(roomsNum)
					{
						case "1":
							bgColor = "#FF3333";
							break;
						case "2":
							bgColor = "#99FF00";
							break;
						case "3":
							bgColor = "#9F809F";
							break;
						case "4":
							bgColor = "#0099FF";
							break;
						default:
							bgColor = "#CCCCCC";
							break;
					}

					return {
						opacity: 0.2,
						fill: bgColor,
						'fill-opacity': '0.5',
						stroke: "#000000",
						"stroke-opacity": "1",
						"stroke-width": 2,
						"stroke-linejoin": "round"
					}
				},
				onClick: function(event, shape) {

				},
				onMouseDown: function(event, shape) {
					// event – нативное событие
					// shape - элемент, на котором это событие сработало.
				
					//alert('Мое кастомное клик событие!');
				
					// получить значения аттрибутов areaShape из imagemap-а можно следующим образом:
					//console.log( $(shape.node).data('areaAttrs') ); //href alt
					
					console.log("onMouseDown");

					var areaData = $(shape.node).data('areaAttrs');
					var flatNum = String(areaData.href.replace("#",""));

					if(data['flats']['flat-'+flatNum] != undefined)
					{
						
						flatData = data['flats']['flat-'+flatNum];

						$("#flatBox").hide();
						if(flatData['flatNum'] != "")
						{
							flatNum = flatData['flatNum'].split("-");
							
							sectionNum = flatNum[0];
							floorNum = flatNum[1];
							flatNum = flatNum[2];
						}
						
						$("#flatBox p:eq(0)").text("№ " + sectionNum + "-" + floorNum + "-" + flatNum);
						$("#flatBox p:eq(1)").text("Комнат: " + flatData['roomsNum']);
						$("#flatBox p:eq(2) b").html(flatData['flatArea'] + "<em>м<sup>2</sup></em>");
						$("#flatBox a:first").attr("href","assets/files/plans/s" + sectionNum + "_f" + floorNum + "_" + flatNum + ".pdf");
						
						//coords = shape.getBBox();
						
						$(document).bind("mouseup", function(e) {
							$("#flatBox").show();
							$("#flatBox").css({
								top: (e.pageY - 160) + "px",
								left: (e.pageX - 65) + "px"
							});
							$(document).unbind("mouseup");
						});
					}

				},
				onTouchEnd: function(event, shape) {
					// event – нативное событие
					// shape - элемент, на котором это событие сработало.
				
					//alert('Мое кастомное клик событие!');
				
					// получить значения аттрибутов areaShape из imagemap-а можно следующим образом:
					//console.log( $(shape.node).data('areaAttrs') ); //href alt
					
					console.log("onTouchEnd");

				},
				onTouchStart: function(event, shape) {
					// event – нативное событие
					// shape - элемент, на котором это событие сработало.
				
					//alert('Мое кастомное клик событие!');
				
					// получить значения аттрибутов areaShape из imagemap-а можно следующим образом:
					//console.log( $(shape.node).data('areaAttrs') ); //href alt
					
					console.log("onTouchStart");

					var areaData = $(shape.node).data('areaAttrs');
					var flatNum = String(areaData.href.replace("#",""));

					if(data['flats']['flat-'+flatNum] != undefined)
					{
						
						flatData = data['flats']['flat-'+flatNum];

						$("#flatBox").hide();

						$("#flatBox p:eq(0)").text("№ " + sectionNum + "-" + floorNum + "-" + flatNum);
						$("#flatBox p:eq(1)").text("Комнат: " + flatData['roomsNum']);
						$("#flatBox p:eq(2) b").html(flatData['flatArea'] + " <em>м<sup>2</sup></em>");
						$("#flatBox a:first").attr("href","assets/files/plans/s" + sectionNum + "_f" + floorNum + "_" + flatNum + ".pdf");
						
						//coords = shape.getBBox();
						
						$(document.body).bind("touchend", function(e) {
							console.log("Document onTouchEnd: " + endCoords.pageX + " : " + endCoords.pageY);
							$("#flatBox").show();
							$("#flatBox").css({
								top: (endCoords.pageY - 160) + "px",
								left: (endCoords.pageX - 47) + "px"
							});
							$(document.body).unbind("touchend");
						});
					}

				}
			});

			$("#plansBox").show();
		}); 
	}

	function getFloor(loadUrl)
	{
		$("#flatBox").hide();
		$.getJSON(loadUrl, function(data) {

			var literNum = data['liter'].replace("liter-","");
			var sectionNum = data['section'].replace("section-","");
			var floorNum = data['floor'].replace("floor-","");

			$("#floorPlaner div.imagemap_inner").remove();
			$("#floorPlaner").append("<div>").find(">div:first").addClass("imagemap_inner").html(data['content']);
			
			$('#floorPlaner img').imagemap({
				buildShape: function(papper, shape) {
					var bgColor;
					
					flatNum = String(shape.href.replace("#",""));
					if(data['flats']['flat-'+flatNum] != undefined)
						roomsNum = data['flats']['flat-'+flatNum]['roomsNum'];
					else
						roomsNum = 0;
					
					switch(roomsNum)
					{
						case "1":
							bgColor = "#FF3333";
							break;
						case "2":
							bgColor = "#99FF00";
							break;
						case "3":
							bgColor = "#9F809F";
							break;
						case "4":
							bgColor = "#0099FF";
							break;
						default:
							bgColor = "#FFFFFF";
							break;
					}

					return {
						opacity: 0.2,
						fill: bgColor,
						'fill-opacity': '0.5',
						stroke: "#000000",
						"stroke-opacity": "1",
						"stroke-width": 2,
						"stroke-linejoin": "round"
					}
				},
				onClick: function(event, shape) {

				},
				onMouseDown: function(event, shape) {
					// event – нативное событие
					// shape - элемент, на котором это событие сработало.
				
					//alert('Мое кастомное клик событие!');
				
					// получить значения аттрибутов areaShape из imagemap-а можно следующим образом:
					//console.log( $(shape.node).data('areaAttrs') ); //href alt
					
					console.log("onMouseDown");

					var areaData = $(shape.node).data('areaAttrs');
					var flatNum = String(areaData.href.replace("#",""));

					if(data['flats']['flat-'+flatNum] != undefined)
					{
						
						flatData = data['flats']['flat-'+flatNum];

						$("#flatBox").hide();
						if(flatData['flatNum'] != "")
						{
							flatNum = flatData['flatNum'].split("-");
							
							sectionNum = flatNum[0];
							floorNum = flatNum[1];
							flatNum = flatNum[2];
						}
						
						$("#flatBox p:eq(0)").text("№ " + sectionNum + "-" + floorNum + "-" + flatNum);
						
						$("#flatBox p:eq(1)").text("Комнат: " + flatData['roomsNum']);
						$("#flatBox p:eq(2) b").html(flatData['flatArea'] + " <em>м<sup>2</sup></em>");
						$("#flatBox a:first").attr("href","assets/files/plans/s" + sectionNum + "_f" + floorNum + "_" + flatNum + ".pdf");
						
						//coords = shape.getBBox();
						
						$(document).bind("mouseup", function(e) {
							$("#flatBox").show();
							$("#flatBox").css({
								top: (e.pageY - 160) + "px",
								left: (e.pageX - 47) + "px"
							});
							$(document).unbind("mouseup");
						});
					}

				},
				onTouchEnd: function(event, shape) {
					// event – нативное событие
					// shape - элемент, на котором это событие сработало.
				
					//alert('Мое кастомное тачэнд событие!');
				}
			});
		}); 
	}

	$('#stopkeys .sectionPoint').click(function(event){
		event.preventDefault();
		getSection($(this).attr('href').replace("#",""));
	});

	function scrollPlan()
	{
		$("#frame").scrollLeft(0);
		$("#frame #scrollarea").css('margin-left','0');
		
		console.log($("#stopimgoverlay").width(),  parseInt($("#frame #scrollarea").css('margin-left')), $("#main").width());

		if($("#main").width() + 50 < $("#stopimgoverlay").width())
		{
			$("#frame #scrollarea").css('margin-left',($("#main").width() - $("#stopimgoverlay").width())/2);
			$("#gallery-arrow-right")
				.show()
				.unbind('click')
				.click(function(event){
					event.preventDefault();
					$("#frame #scrollarea").stop(true, true);
					$("#gallery-arrow-left").show();
					var distance = 100;
					if($("#stopimgoverlay").width() + parseInt($("#frame #scrollarea").css('margin-left')) - $("#main").width() - distance < 0 )
					{
						distance = $("#stopimgoverlay").width() + parseInt($("#frame #scrollarea").css('margin-left')) - $("#frame").width();
						$("#gallery-arrow-right").hide();
					}
					$("#frame #scrollarea").animate({'margin-left': "-=" + distance}, 250);
				});

			$("#gallery-arrow-left")
				.show()
				.unbind('click')
				.click(function(event){
					$("#frame #scrollarea").stop(true, true);
					event.preventDefault();
					var distance = 100;
					$("#gallery-arrow-right").show();
					if(parseInt($("#frame #scrollarea").css('margin-left')) + distance >= 0 )
					{
						distance = 0;
						$("#gallery-arrow-left").hide();
					} else {
						distance = "+=" + distance;
					}
					$("#frame #scrollarea").animate({'margin-left': distance}, 250);
				});
		} else {
			$("#gallery-arrow-left").hide();
			$("#gallery-arrow-right").hide();
		}
	}
	
	scrollPlan();
	
	$(window).bind('resize',function(){ scrollPlan(); }); 
});
