﻿function startGallery(){
	var VERY_HUGE_WIDTH = 999999999999;
	var ALIGNMENT_POSITION = 300;
	var SCROLL_TO_ELEMENT_LUFT = 0;
	var SHOWCASE_MAX = 565;
	/*  ELEMENTS
	---------------------*/
	var gallery = $('DIV.gallery')
	
	var slider = $('DIV.gallery_slider', gallery)
	var handle = $('DIV.gallery_handle', slider);
	var handle_visual = $('DIV.gallery_handle_visual', slider);
	//var sliderSpots = $('SPAN', slider);
	
	var container = $('DIV.gallery_container', gallery);
	var showcase = $('.gallery_showcase', container);
	var showcase_cells = $('TD > DIV', showcase)
	var fake = $('DIV.gallery_content_fake', container);
	var buttons = $('.gallery_buttn', gallery);
	
	var content = $('DIV.gallery_content', container);
	var objects = $('> *', content).css({float: 'left'});
	/*  VARIABLES
	---------------------*/
	var totalWidth = 0;
	var screenWidth = 0;
	var expandedWidth = 0;
	var cellWidth = 0;
	var isShowcaseBlocked = false;
	var currPerc = 0;
	var elementsPos = {};

window.showcases = function(selector, cells){
	$(selector).each(function(){
		var s = $(this);
		var s_cells = $(cells, s);
		var cWidth = Math.floor(screenWidth/s_cells.length);
		var expWidth = SHOWCASE_MAX;
		s_cells.width(cWidth);
		s_cells.unbind('hover').hover(function(){
			s_cells.stop().not(this).animate({width: Math.floor((screenWidth - expWidth) / (s_cells.length - 1))});
			$(this).animate({width: expWidth});
		}, function(){
			s_cells.stop().animate({width: cWidth});
		});

	});
};
	var checkShowcase = function(){
		return isShowcaseBlocked = (showcase.offset().left != gallery.offset().left);
		if(!isShowcaseBlocked) {
			showcase_cells.stop().width(cellWidth);
		}
	};
	var init = function(){
		container.width(VERY_HUGE_WIDTH);
		screenWidth = gallery.width();
		$('DIV.gallery_element_showcase').width(screenWidth);
		var w = 0;
		objects.each(function(){
			w += $(this).width();
		});
		totalWidth = showcase.width(screenWidth).width() 
					+ content.width(w).width() 
					//+ fake.show().width(Math.floor((screenWidth - objects.eq(objects.length-1).width()) / 2)).width();
		objects.eq(objects.length - 1).css({marginRight: '-100%'});
		container.width(totalWidth);
		/*
		$('SPAN.gallery_button_reposition', slider).each(function(){
			var containerPos = container.offset().left;
			var elm = $('#' + $(this).attr('rel'))
			var elmPos = elm.offset().left + elm.width()/2;
			$(this).css({left: (elmPos - containerPos) * handleMax() / contentMax() - $(this).width()/2});
		});
		/**/
		showcases('DIV.gallery_element_showcase', 'TD > DIV');
		showcaseInit();
		$('SPAN', handle_visual).each(function(){
			var elm = $('#' + $(this).attr('rel'));
			if(elm.length) {
				elementsPos[$(this).attr('rel')] = Math.abs(elm.offset().left - container.offset().left);
			}
			
		});
	};
	var showcaseInit = function(){
		showcase.width(screenWidth);
		cellWidth = Math.floor(screenWidth/showcase_cells.length);
		expandedWidth = SHOWCASE_MAX;
		showcase_cells.width(cellWidth).unbind('hover').hover(function(){
			if(!isShowcaseBlocked) {
				showcase_cells.not(this).stop().animate({width: Math.floor((screenWidth - expandedWidth) / (showcase_cells.length - 1))});
				$(this).stop().animate({width: expandedWidth});
			}
		}, function(){
			showcase_cells.stop().animate({width: cellWidth});
		});
		checkShowcase();
	};
	var scrollToElement = function(elm, toStart){
		if(!elm || !elm.length){
			return;
		}
		contentAnimate((toStart || elm.attr('class').indexOf('showcase') > -1 ? 0 : ALIGNMENT_POSITION) - (elm.offset().left - container.offset().left) + SCROLL_TO_ELEMENT_LUFT);
	};
	var scrollBy = function(pos){
		contentAnimate(container.offset().left - gallery.offset().left + pos);
	}
	var handleMax = function(){
		return slider.width() - handle.width();
	};
	var contentMax = function(){
		return totalWidth - screenWidth;
	};
	var getHandlePercent = function(xPos){
		if(xPos === undefined) {
			xPos = parseInt(handle.offset().left - slider.offset().left);
			currPerc = Math.abs(xPos / handleMax());
		}
		return Math.abs(xPos / handleMax());
	};
	var getContentPercent = function(xPos){
		if(xPos === undefined) {
			xPos = parseInt(container.offset().left);
			currPerc = Math.abs(xPos / contentMax());
		}
		return Math.abs(xPos / contentMax());
	};
	
	var normalizeHandlePos = function(xPos){
		if(xPos < 0)
			xPos = 0;
		if(xPos > handleMax())
			xPos = handleMax();
		return xPos;
	};
	var normalizeContentPos = function(xPos){
		if(xPos > 0) {
			xPos = 0;
		}
		if(xPos < -contentMax()) {
			xPos = -contentMax();
		}
		return xPos;
	};
	var updateContentPosition = function(){
		handle_visual.css({left:handle.css('left')});
		container.css({left: -contentMax() * getHandlePercent()});
	};
	var updateHandlePosition = function(){
		handle_visual.add(handle).css({left: handleMax() * getContentPercent()});
	};
	var contentAnimate = function(xPos){
		xPos = normalizeContentPos(xPos);
		container.stop().animate({left: xPos}, {duration:'fast', start: checkShowcase,  step: updateHandlePosition, complete: function(){updateHandlePosition();updateGalleryInfo();}});
	};
	var handleAnimate = function(xPos){
		xPos = normalizeHandlePos(xPos);
		handle.stop().animate({left:xPos}, {duration:'fast', start: checkShowcase, step: updateContentPosition, complete: function(){updateContentPosition();updateGalleryInfo();}});
	};
	var updateGalleryInfo = function(){
		var cPos = container.offset().left - gallery.offset().left;

		if(Math.abs(cPos) < 5) {
			$('.gallery_button_left', gallery).hide();
		} else {
			$('.gallery_button_left', gallery).show();
		}
		if(Math.abs(contentMax()) == Math.abs(cPos)) {
			$('.gallery_button_right', gallery).hide();
		} else {
			$('.gallery_button_right', gallery).show();
		}
		var nowPos = Math.abs(container.offset().left - gallery.offset().left) + ALIGNMENT_POSITION;
		var nearest = null;
		var nearestPos = 0;
		for(var i in elementsPos){
			if(elementsPos[i] <= nowPos) {
				nearestPos = Math.max(nearestPos, elementsPos[i]);
				if(nearestPos == elementsPos[i]){
					nearest = i;
				}
			}
		}
		var id = nearest;
		handle_visual.find('SPAN').hide().filter('[rel='+id+']').show();
		updateTexts(id);
	};
	var updateTexts = function(id){
		$('#header_texts').html($('#txt_'+id).html());
		startScroll();
		checkShowcase();
	};
	var nearestToPointAtRight = function(){
		var nearest = null;
		var nearestPos = container.width();
		objects.add(showcase).each(function(){
			var pos = $(this).offset().left - gallery.offset().left - (($(this).attr('class').indexOf('showcase') > -1) ? ALIGNMENT_POSITION : 0);
			if(pos > ALIGNMENT_POSITION && pos < nearestPos) {
				nearest = $(this);
				nearestPos = pos;
			}
		});
		return nearest;
	};
	var nearestToPointAtLeft = function(){
		var nearest = null;
		var nearestPos = -container.width();
		objects.add(showcase).each(function(){
			var pos = $(this).offset().left - gallery.offset().left + (($(this).attr('class').indexOf('showcase') > -1) ? ALIGNMENT_POSITION : 0);
			if(pos < ALIGNMENT_POSITION && pos > nearestPos) {
				nearest = $(this);
				nearestPos = pos;
			}
		});

		return nearest;
	};	
	setInterval(updateGalleryInfo, 1000);
	updateGalleryInfo();
	///////////////////////////
	/**/
	handle.draggable({
		containment:slider,
		//refreshPositions:true,
		drag:updateContentPosition,
		axis: "x"
	});
	window.scrollToId = function (id){
		scrollToElement($('#'+id));
		updateTexts(id);
	}
	window.scrollToIdAtStart = function (id){
		scrollToElement($('#'+id), true);
		updateTexts(id);
	}
	$(window).resize(function(){
		init();
		handle.css({left: handleMax() * currPerc});
		updateContentPosition();
	});
	
	buttons.add('.gallery_button').click(function(){
		scrollToElement($('#' + $(this).attr('rel')));
	});
	init();
	$('.gallery_button_left', gallery).click(function(){
		scrollToElement(nearestToPointAtLeft());
		return false;
	})
	$('.gallery_button_right', gallery).click(function(){
		scrollToElement(nearestToPointAtRight());
		return false;
	})
};
function openModal(elm, o){
	$('html,body').animate({scrollTop: 0}, 50)
	var elm = $(elm);
	if(!elm.length)
		return null;
	var tmr = null;
	$('#map,#plan').appendTo('body').hide();
			try{
	$('#modal')
	.find('DIV.modal_content').empty().append(elm.show()).end()
	.modal($.extend({
		close: false,
		overlay: 80,
		closeClass: 'modal_close',
		containerId: 'modal_container',
		overlayId: 'modal_overlay',
		onOpen: function (dialog) {
			dialog.overlay.fadeIn('fast', function () {
				dialog.data.show();
				dialog.container.slideDown('fast');
			});
		},
		onClose: function (dialog) {
			dialog.container.slideUp('fast', function () {
				dialog.data.hide();
				dialog.overlay.fadeOut('fast', function () {
					$('#map,#plan').appendTo('body').hide();
					$.modal.close();
				});
			});
		}
	}, o));
			}catch(e){alert(e.message)}
	return $('#modal');
};
function openImg(src, w, h, title){
	openModal($('<img class="modal_close"' + (w ? ' width="' + w + '"' : '') + (h ? 'height="' + h + '"' : '') +' src="' + src + '" alt="' + title + '" title="' + title + '"/>'));
};
var isMapInited = false;
function openMap(){
	var map = $('#map');
	openModal(map.show());
	if(isMapInited)
		return;
	isMapInited = true;
	var map_overlay = $('#map_overlay');
	var types_container = $('DIV.types', map);
	var types = $('SPAN.type', types_container);
	var houses = $('DIV.houses > DIV > *', map);
	var tooltip = $('DIV.tooltip', map);
	var tooltip_content_selector = 'DIV.tooltip_text'
	var tooltipHTML = tooltip.html();
	var isTooltipHovered = false;
	var hoverTimeout = 500;
	var hoverTimer = null;
	var xDelayEffect = 15;
	
	var prepareTooltipHTML = function(o){
		var html = tooltipHTML;
		for(var i in o) {
			html = html.split('${' + i + '}').join(o[i]);
		}
		return html;
	};
	tooltip.hover(function(){
		$(tooltip_content_selector, this).one('mouseover', function(){
		clearTimeout(hoverTimer);
		});
	}, function(){
		$(this).hide();
	});
	window.houseClick = function(elm){
		house.click();
	}
	/**/
	var house = null;
	houses.click(function(){
		openPlan(this.params.floor_1, this.params.floor_2);
		return false;
	}).hover(function(){
		clearTimeout(hoverTimer);
		house = $(this);
		var o = this.params;
		var top = parseInt($(this).css('top')) - tooltip.height();
		tooltip.hide().html(prepareTooltipHTML(o))
			.css({
				left: parseInt($(this).css('left')) + ($(this).width() - tooltip.width()) / 2, 
				top: top - xDelayEffect
			}).stop().animate({
				top: top
			}, 'fast').show();
		map_overlay.addClass($(this).parent().attr('rel')).fadeIn('fast');
	}, function(){
		var clazz = $(this).parent().attr('rel')
		hoverTimer = setTimeout(function(){
			tooltip.animate({top: parseInt(tooltip.css('top')) - xDelayEffect}, 'fast', function(){$(this).hide()});
			house = null;
		}, hoverTimeout);
		map_overlay.removeClass(clazz).hide();
	});
	/**/
	types.hover(function(){
		map_overlay.addClass($(this).attr('rel')).fadeIn('fast');
	}, function(){
		map_overlay.removeClass($(this).attr('rel')).hide();
	});
};
function openPlan(floor_1, floor_2, openOn2nd){
	var plan = $('#plan');
	var div = $('DIV.image', plan).show().html(
		'<img src="' + floor_1.src + '" alt="" style="display:none;" />'
		+'<img src="' + floor_2.src + '" alt="" />');
	openModal(plan).find('.floor_switch').unbind('click').click(function(){
		$('IMG', div).toggle(); 
		plan.find('.floor_switch').toggleClass('to_floor_2');
	});
	if(openOn2nd) {
		plan.find('.floor_switch').click();
	}
	plan.show()
};

(function($){
$.fn.scroll = function(o){
if(this.length)
this.each(function(){
	var scroll = $(this).css({overflow: 'hidden'});
	var content = $(o.content, scroll).css({position:'absolute', right:0, left:0, top:0, zIndex:1});
	var track = $(o.track, scroll).show();
	var handle = $(o.handle, track);
	var maxContent = content.height() - scroll.height();
	if(maxContent <= 0) {
		track.hide();
		return null;
	}
	var maxTrack = track.height() - handle.height();
	var updatePosition = function(){
		var pos = -Math.ceil( (handle.offset().top - track.offset().top) / maxTrack * maxContent )
		content.css('top', pos);
	};
	handle.draggable('destroy').draggable({
		containment: track,
		drag: updatePosition,
		axis: 'y'
	});
	updatePosition();
});
return this;
};
})(jQuery);
function startScroll(){
$('DIV.scroll').scroll({
	track: '.track', 
	handle: '.handle', 
	content: '.scroll_content'
});
}
/* EASYALL
--------------------*/
function send_mail(form, href) {
	var val = function(elm){
		return $.trim($(elm).val());
	};
	var f = function(elm, message){
		var v = val(elm);
		if(v == '' || v == elm.defaultValue) {
			alert(message);
			elm.focus();
			return false;
		}
		return true;
	};
	if(
		!f(form.ename, 'Введите имя') || 
		!f(form.email, 'Введите e-mail') || 
		!f(form.etheme, 'Введите тему') || 
		!f(form.etext, 'Введите текст') 
	)
		return;
	$.post(href, 
		{
			ename: val(form.ename),
			email: val(form.etheme),
			etheme: val(form.etheme),
			etext: val(form.etext)
		},
		function(data, textStatus) {
			openModal($(data))
			form.reset();
		});
}
(jQuery);
