
var mailForm;
var curtain;

$(AlterHtml)

$(function () {
	$(document.body).append("<div id='curtain'></div>");
	curtain = $('#curtain').css({
		'display': 'none',
		'opacity': 0
	});
	
	spritesImage = new Image();
	spritesImage.src = '/images/sprites.png';
	swatchImage = new Image();
	swatchImage.src = '/images/swatch.png';

	mailForm = 
		$('#mail_form form')
			.ajaxForm({
					beforeSubmit: PrepareFormForSubmition,
					success: function() {
						HideBubble('mail_form');
						$('#mail_form input[type=submit]').val('Отправлено');
						setTimeout(ResetForm, Bubbles['mail_form'].hideDelay + Bubbles['mail_form'].time);
						return true;
					},
					error: ShowErrorNotice
				});
	mailForm.prepend('<p class="close_mail_form">Закрыть</p>');

    $('.bubble_trigger').each(SetBubbleTrigger);


	RenewForm(); // for page reload, do not reset form values
	
	
});



function PrepareFormForSubmition () {
	// local functions
	function _CheckEmail () {
		var email = $(elEmail).val();
		if (!ValidEmail(email))
			elEmail.addClass('error');
		else
			elEmail.removeClass('error');
	}
	function _CheckEmptiness () {
		var elementsToCheck = [this] || requiredInputs;
		$(requiredInputs).each(function() {
			var el = $(this);
			if (el.val() == '')
				el.addClass('error');
			else
				el.removeClass('error');
		})
	}
	// /local functions

	var mailForm = $('#mail_form form');
	$('#mail_form_error_notice').animate({
		opacity: 0,
	}, 100, function() { $(this).hide() });
	
	var elEmail =
		$('input[name="user[email]"]', mailForm)
			.keydown(_CheckEmail)
			.keyup(_CheckEmail);
	_CheckEmail();
	
	var requiredInputs =
		$([$('input[name="user[name]"]', mailForm), $('textarea', mailForm)])
			.each(function() {
				this.keydown(_CheckEmptiness)
				this.keyup(_CheckEmptiness)
			})
	_CheckEmptiness();
	
	if ($('#mail_form input.error').length)
		return false;

	$('input[type=submit]', mailForm)
		.attr('disabled', true)
		.val('Отправляется...');
};

function EnableForm () {
	$('#mail_form input[type=submit]').removeAttr('disabled');
};

function ShowErrorNotice (responseText) {
	EnableForm();
	$('#mail_form_error_notice')
		.html('Не получилось отправить вопрос.')
		.show()
		.animate({
			opacity: 1,
		}, 400)
};

function RenewForm () {
	EnableForm();
	$('.error', mailForm).removeClass('error');
	$('input[type=submit]', mailForm).val('Отправить');
	$('#mail_form_error_notice').hide().css('opacity', 0);
};

function ResetForm () {
	var mailForm = $('#mail_form form').resetForm();
	RenewForm()
};




// Bubbles ////////////////////////////////////////////////

var Bubbles = {}

function SetBubbleTrigger () {
	
	var bubbleId = this.id.substr(4); // trimming "for_" in @id
	
	Bubbles[bubbleId] = {
		bubbleId: bubbleId,
		
		distance: 25,
		triggerBubbleOffset: 10,
	    time: 350,
	    hideDelay: 100,
	    hideDelayTimer: null,
	    beingShown: false,
	    shown: false,
	    trigger: $(this),
	    el: $('#' + bubbleId).css({
			opacity: 0,
			position: 'absolute'
		})
		
	}
    $(this).click(ShowBubble);
	$('.close_mail_form').click(HideBubble);

    $(document)
        .click(HideBubble)
        .keydown(function(e) {
            if (e.keyCode == 27) {
				HideBubble(Bubbles[bubbleId])
				$('.visiblePopup').animate({
					'opacity': 0
				}, animationTime, function() {
					$(this).hide()
				})
			}
        });
    Bubbles[bubbleId].el.click(function(e) {
		if(e.target.type != 'submit')
			return false;
	});
}


function ShowCurtain () {
	curtain
		.css({
			display: 'block',
			opacity: 0
		})
		.animate({ 'opacity': .3 });
}

function HideCurtain () {
	curtain
		.animate({ opacity: .0 }, 200, function() {
			curtain.css('display', 'none')
		});
}

function ShowBubble(bubble) {
	if (!bubble.bubbleId)
		bubble = Bubbles[this.id.substr(4)];
	
    if (bubble.hideDelayTimer) clearTimeout(bubble.hideDelayTimer);
    if (bubble.beingShown || bubble.shown) {
        return;
    } else {
        // reset bubble position
        bubble.beingShown = true;
		
		// explicit position calling in case of font change, page resize
        var triggerPosition = bubble.trigger.offset(); // mouse-over element
        var triggerWidth = bubble.trigger.width();
        var triggerHeight = bubble.trigger.height();
        var bubbleHeight = bubble.el.height();
        var bubbleWidth = bubble.el.width();
    	
		$('.t', bubble.el)
			.css('right', (triggerWidth+90)/2)
			
		ShowCurtain()

		
        bubble.el
			.css({
                top: triggerPosition.top + bubble.distance + bubble.triggerBubbleOffset, // triggerOffsets.top - bubbleHeight + distance
                left: triggerPosition.left + (triggerWidth - bubbleWidth),
                display: 'block'
            }).animate({
                top: '-=' + bubble.distance + 'px',
                opacity: 1
            }, bubble.time, 'swing', function() {
                bubble.beingShown = false;
                bubble.shown = true;
            });
    }
    return false;
}

function HideBubble(bubbleOrEvent) {
	if(bubbleOrEvent.originalEvent && bubbleOrEvent.target.type == 'submit')
		return true;

	// local functions
	function _AnimateHidingBubble (bubble) {
	    if (bubble.hideDelayTimer) clearTimeout(bubble.hideDelayTimer);
	    bubble.hideDelayTimer = setTimeout(function () {
	        bubble.hideDelayTimer = null;
			HideCurtain();
	        bubble.el
				.animate({
	                top: '-=' + bubble.distance + 'px',
	                opacity: 0
	            }, bubble.time, 'swing', function () {
	                bubble.shown = false;
	                bubble.el.css('display', 'none');
					curtain.css('display', 'none')
	            });
	    }, bubble.hideDelay);
	}
	// /local functions

	$.each(Bubbles, function(bubbleId, bubble) {
		_AnimateHidingBubble(bubble)
	})
    // return false;
}


function ValidEmail(email) {
	var emailPattern = /^[a-zA-Z0-9._\-]+[a-zA-Z0-9._\-\+]*@[a-zA-Z0-9.-]+(\.[a-zA-Z]{2,})+$/;
	return emailPattern.test(email);
}



var animationTime = 150;

function AlterHtml () {
	$('.mapLink').click(ToggleMap)
	$('#mapHeaderContainer').append('<a href="" class="dashed" id="closeMap">Закрыть</a>')
	

	$(document).click(function(ev) {
		var shops = $('#shopsContainer:visible');
		if (shops.length) {
			shops.hide();
			var scrollable = shops.data('scrollable');
			scrollable.seekTo(0);
		}
			
		
		
		if($(ev.target).parents('#map').length)
			return;
		
		HideMap()
		return
	})
	
	$('#aboutLink').click(function() {
		var text = $('#about').text();
		$('#about').html('').css({opacity: 0}).show().animate({opacity: 1}, 1000);
		
		function _UpdateText () {
			var lettersToPrint = 6;
			if (text.length) {
				$('#about')[0].innerHTML += text.substring(0, lettersToPrint-1);
				text = text.substring(lettersToPrint-1)
			} else {
				clearInterval(aboutInterval)
			}
		}

		var aboutInterval = setInterval(_UpdateText, 1)
		return false
	})
}

function ToggleMap () {
	if ($('#mapContainer').css('display') == 'block') {
		HideMap()
	} else {
		ShowMap()
	}
	
	return false;
}

function HideMap () {
	var mapContainer = $('#mapContainer');
	
	if (mapContainer.css('display') != 'block')
		return;
		
	HideCurtain()
	mapContainer.animate({
		'opacity': 0
	}, animationTime, function() {
		mapContainer.css('display', 'none')
	})
}

function ShowMap () {
	$('#mapContainer')
		.css({
			'display': 'block',
			'top': ($(window).height() - $(this).height()/2) /3 + 'px'
		})
		.addClass('visiblePopup')
	
	ShowCurtain()
	CreateMap();
	// var container = YMaps.jQuery("#YMapsID-180"), map = new YMaps.Map(container[0]);
	// map.redraw();
	
	$('#mapContainer').animate({
		'opacity': 1
	}, animationTime * 3)
}


// Yandex API Map
function CreateMap () {
	
    YMaps.load(function () {
        var map = new YMaps.Map(YMaps.jQuery("#YMapsID-180")[0]);
        map.setCenter(new YMaps.GeoPoint(30.433841,60.043539), 13, YMaps.MapType.HYBRID);
        map.addControl(new YMaps.Zoom());
        map.addControl(new YMaps.ToolBar());
//        YMaps.MapType.PMAP.getName = function () { return "Народная"; }
        map.addControl(new YMaps.TypeControl([
            YMaps.MapType.MAP,
            YMaps.MapType.SATELLITE,
            YMaps.MapType.HYBRID,
            YMaps.MapType.PMAP
        ], [0, 1, 2, 3]));

        YMaps.Styles.add("constructor#pmormPlacemark", {
            iconStyle : {
                href : "http://api-maps.yandex.ru/i/0.3/placemarks/pmorm.png",
                size : new YMaps.Point(28,29),
                offset: new YMaps.Point(-8,-27)
            }
        });


        YMaps.Styles.add("constructor#FF3732c85Polygon", {
            polygonStyle : {
                strokeColor : "FF3732c8",
                strokeWidth : 5,
              	fill : true,
                fillColor : "FF3732c8",
                outline : true
            }
        });
       map.addOverlay(createObject("Placemark", new YMaps.GeoPoint(30.444979,60.051223), "constructor#pmormPlacemark", "Садово-фермерский центр «Дача-сервис»"));
       map.addOverlay(createObject("Polyline", [], "constructor#FF3732c85Polyline", ""));
       map.addOverlay(createObject("Polygon", [new YMaps.GeoPoint(30.445359,60.051091),new YMaps.GeoPoint(30.44449,60.051264),new YMaps.GeoPoint(30.446368,60.054033),new YMaps.GeoPoint(30.448251,60.053679),new YMaps.GeoPoint(30.447929,60.053226),new YMaps.GeoPoint(30.446921,60.053394)], "constructor#FF3732c85Polygon", "Садово-фермерский центр"));

        function createObject (type, point, style, description) {
            var allowObjects = ["Placemark", "Polyline", "Polygon"],
                index = YMaps.jQuery.inArray( type, allowObjects),
                constructor = allowObjects[(index == -1) ? 0 : index];
                description = description || "";

            var object = new YMaps[constructor](point, {style: style, hasBalloon : !!description});
            object.description = description;

            return object;
        }
    });
}

