(function($){
	var URL_ROOT = $('script[url-root]').attr('url-root');
	$.CMS = {
		URL_ROOT : URL_ROOT,
		URL_DATA : URL_ROOT+'cms-data/'
	};
})(jQuery);

jQuery.fn.sortElements = (function(){
	var sort = [].sort;
	return function(comparator, getSortable) {
		getSortable = getSortable || function(){return this;};
		var placements = this.map(function(){
			var sortElement = getSortable.call(this),
				parentNode = sortElement.parentNode,
				nextSibling = parentNode.insertBefore(
				    document.createTextNode(''),
				    sortElement.nextSibling
				);
			return function() {
				if (parentNode === this) {
				    throw new Error(
				        "You can't sort elements if any one is a descendant of another."
				    );
				}
				parentNode.insertBefore(this, nextSibling);
				parentNode.removeChild(nextSibling);
			};
		});
		return sort.call(this, comparator).each(function(i){
			placements[i].call(getSortable.call(this));
		});
	};
})();


jQuery(function($){
	var BOX = {
			speed : 300,
			slideSpeed : 300,
			animation : {
				queue : false,
				duration : 300
			},
			colors : {
				def : {
					border : ['#121212', '#fff'],
					text : ['#979797', '#646464'],
					span : ['#fff', '#000']
				},
				collection : {
					border : ['#121212', '#fff'],
					text : ['#979797', '#000'],
					span : ['#fff', '#000']
				},
				investments : {
					border : ['#000', '#fff'],
					text : ['#979797', '#000'],
					span : ['#646464', '#000']
				}
			}
		};
	
	$(document).delegate('.box.hoverable, .box .hoverer', 'mouseenter mouseleave', function(e) {
		var that = $(this).closest('.box')[0], hover = e.type == 'mouseenter', colors = BOX.colors[$(that).data('type') || 'def'], color = hover ? colors.border[1] : colors.border[0];
		$('.cover', that).stop().fadeTo(BOX.speed, hover ? 0 : .5);
		$('.logo-normal', that).stop().fadeTo(BOX.speed, hover ? 0 : 1);
		$('.logo-hover', that).stop().fadeTo(BOX.speed, hover ? 1 : 0);
		$('.border', that).stop().animate({
			borderLeftColor : color,
			borderRightColor : color,
			borderTopColor : color,
			borderBottomColor : color
		}, BOX.animation);
		$('.content', that).stop().animate({
			backgroundColor : color,
			color : hover ? colors.text[1] : colors.text[0]
		}, BOX.animation);
		$('.content span', that).stop().animate({
			color : hover ? colors.span[1] : colors.span[0]
		}, BOX.animation);
		$('.extender', that).stop().animate({
			color : hover ? colors.border[1] : colors.text[0]
		}, $.extend(true, {complete : function() {
			if(!hover) {
				$(this).css('color', '');
			}
		}}, BOX.animation));
	}).delegate('.collection-item', 'mouseenter mouseleave', function(e) {
		var hover = e.type == 'mouseenter', color = hover ? '#fff' : '#121212';
		$(this).stop().animate({
			backgroundColor : color
		}, BOX.animation);
		$('.text', this).animate({
			color : hover ? '#646464' : '#979797'
		}, BOX.animation);
		$('h1', this).animate({
			color : hover ? '#000' : '#fff'
		}, BOX.animation);
	}).delegate('.investment-item', 'mouseenter mouseleave', function(e) {
		var hover = e.type == 'mouseenter', color = hover ? '#fff' : '#121212';
		$('.text', this).stop().animate({
			backgroundColor : color,
			color : hover ? '#646464' : '#979797'
		}, BOX.animation);
		$('h1', this).animate({
			color : hover ? '#000' : '#fff',
			borderBottomColor : hover ? '#979797' : '#4A4A4A'
		}, BOX.animation);
	}).delegate('.om-collection .item:not(.open)', 'mouseenter mouseleave', function(e) {
		var hover = e.type == 'mouseenter', color = hover ? '#fff' : '#1d1d1d';
		$(this).stop().animate({
			backgroundColor : color,
			color : hover ? '#646464' : '#979797'
		}, BOX.animation);
		$('h3', this).animate({
			color : hover ? '#000' : '#fff',
			borderBottomColor : hover ? '#979797' : '#4A4A4A'
		}, BOX.animation);
	}).delegate('.om-title a[data-sort]', 'click', function() {
		var that = $(this), sorter = that.data('sort'), dir = !that.data('direction');
		that.data('direction', dir);
		$(this).addClass('active').siblings().removeClass('active');
		$(this).closest('.om-column').find('.om-collection .item').sortElements(function(a, b) {
			return ($(a).data(sorter) > $(b).data(sorter) ? 1 : -1) * (dir ? 1 : -1);
		});
		return false;
	}).delegate('#off-market .item .contact', 'click', function() {
		var item = $(this).closest('.item'),
			container = $('#om-form').find('.form-content').show().end().find('.form-thanks').hide().end().fadeIn(),
			form = container.find('form'),
			id = item.attr('data-id'),
			formHeight = form.height(),
			containerTop = container.offset().top,
			wind = $(window),
			scrollTop = wind.scrollTop(),
			containerHeight = container.height(),
			windowHeight = wind.height(),
			visibleTop = Math.max(0, containerTop - scrollTop),
			visibleBottom = Math.min(windowHeight, containerTop + containerHeight),
			top = Math.max(0, (visibleBottom - visibleTop - formHeight) / 2 - containerTop + scrollTop);
		form.css({
			top : top
		});
		$('#omf-property').val(id);
		$('#omf-property-id').text(id);
		$('#omf-property-name').text(item.data('name'));
		return false;
	}).delegate('#om-form .close', 'click', function() {
		$('#om-form').fadeOut();
	}).delegate('#om-form form', 'submit', function(e) {
		var form = $(this);
		e.preventDefault();
		$.post(form.attr('action')+'.json', form.serialize(), function(data) {
			if(data) {
				form.find('.form-content').fadeOut();
				form.find('.form-thanks').fadeIn();
				setTimeout(function() {
					$('#om-form').fadeOut();
				}, 3000);
			} else {
				alert('There was some error. Please check e-mail address and try again.');
			}
		}, 'json');
		return false;
	}).delegate('.box .extender', 'click', function() {
		var content = $(this).closest('.content');
		if(content.is('.extended')) {
			content.find('.extended-content').slideUp(BOX.slideSpeed, function() {
				content.removeClass('extended');
			});
		} else {
			content.addClass('extended').find('.extended-content').slideDown(BOX.slideSpeed);
		}
	}).delegate('.box .select .option', 'click', function() {
		var that = $(this), form = that.closest('form'), items = form.data('items'), type = that.data('type'), data;
		that.addClass('selected').siblings().removeClass('selected');
		
		data = {
			region : form.find('.option[data-type="region"].selected').data('region'),
			country : form.find('.option[data-type="country"].selected').data('country'),
			range : form.find('.option[data-type="range"].selected').data('range')
		};
		
		if(type == 'region') {
			form.find('.option[data-country]:not(.all),.option[data-range]:not(.all)').hide();
			$.each(items, function() {
				if(
					this.region == data.region || !data.region
				) {
					form.find('[data-country="'+this.country+'"]').show();
					form.find('[data-range="'+this.range+'"]').show();
				}
			});
		}
		if(type == 'country') {
			form.find('.option[data-range]:not(.all)').hide();
			$.each(items, function() {
				if(
					(this.region == data.region || !data.region) &&
					(this.country == data.country || !data.country)
				) {
					form.find('[data-range="'+this.range+'"]').show();
				}
			});
		}
		form.find('input[name="'+type+'"]').val(data[type]);
	});
	$('.om-title a[data-sort].active').click();
	
	
	if($('#property-gallery-pics-inner a').length) {
		var container = $('#property-gallery-pics-inner'),
			pics = container.find('a'),
			n = pics.length,
			delta = 0,
			target = 0,
			l = container.offset().left,
			left = 0,
			tmp = [],
			i = 1,
			nrField = $('#property-gallery-current');
		$.each(pics, function() {
			tmp.push($('<img>').attr('src', $(this).attr('href')));
			$(this).data('nr', i++);
		});
		while(n < 10) {
			i = 1;
			container.append(pics.clone().each(function() {
				$(this).data('nr', i++);
			}));
			n += pics.length;
		}
		container.find('a').bind('click', function() {
			var that = $(this), img = $('<img>').attr('src', that.attr('href'));
			img.appendTo('#property-pic').hide().fadeIn(500, function() {
				if(!$(this).hasClass('old')) {
					$(this).siblings('img').remove();
				}
			}).click(function() {
				that.next().click();
				target = 0;
				delta = -12;
			});
			img.siblings('img').addClass('old');
			$(this).addClass('open').stop().fadeTo(300, 1);
			that.siblings().removeClass('open').stop().fadeTo(300, 0.4);
			nrField.text(that.data('nr'));
			return false;
		}).mouseenter(function() {
			$(this).stop().fadeTo(300, 1);
		}).mouseleave(function() {
			$(this).parent().children(':not(.open)').stop().fadeTo(300, 0.4);
		}).first().click();
		setInterval(function() {
			if(delta === 0 && target === 0) {
				return;
			}
			if(delta < target) {
				delta++;
			} else if(delta > target) {
				delta--;
			}
			left += delta;
			if(left < -74) {
				left += 74;
				container.find('a:first').appendTo(container);
			} else if(left > 0) {
				left -= 74;
				container.find('a:last').prependTo(container);
			}
			container.css('left', left);
		}, 40);
		
		$('#property-gallery-pics').mousemove(function(e) {
			var that = $(this), x = (e.pageX - l) << 0, w = that.width();
			if(x < w / 3) {
				target = (w - 3 * x) / w;
			} else if(x > w * 2 / 3) {
				target = 2 - 3 * x / w;
			}
			target = (target * 20) << 0;
			if(target > 1000 ||target < -1000) {
				target = 0;
			}
		}).mouseleave(function() {
			target = 0;
		});
	}
	
	// Form validation
	$('form.validate').submit(function(e) {
		var ok = true, focus = false;
		// Check required fields
		$('.form-field.required', this).each(function() {
			var that = $(this);
			if(!that.find(':input').val()) {
				ok = false;
				if(!focus) {
					that.find(':input').focus();
					focus = true;
				}
				that.addClass('error');
			} else {
				that.removeClass('error');
			}
		});
		// Check e-mail fields
		$('.form-field-email', this).each(function() {
			var that = $(this);
			if(!that.find(':input').val().match(/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/)) {
				ok = false;
				if(!focus) {
					that.find(':input').focus();
					focus = true;
				}
				that.addClass('error');
			} else {
				that.removeClass('error');
			}
		});
		if(!ok) {
			return false;
		}
	});
	
	// Google Plus
	var timeout;
	$('.google-plus').mouseenter(function() {
		var that = $(this).closest('.google-plus'), timeout = that.data('timeout');
		if(timeout) {
			clearTimeout(timeout);
			that.data('timeout', 0);
		}
		$('.google-button', that).animate({
			top : 0
		});
	}).mouseleave(function() {
		var that = $(this).closest('.google-plus'), timeout = that.data('timeout');
		if(timeout) {
			clearTimeout(timeout);
		}
		that.data('timeout', setTimeout(function() {
			$('.google-button', that).animate({
				top : -40
			});
		}, 500));
	});
	
	$('.scrollable').jScrollPane({
		showArrows : false,
		verticalGutter : 10,
		speed : 60
	});
	
	$('form[data-action]').attr('action', function() {
		return $(this).data('action');
	});
});

