var firsttime = true;
$(function(){
	Cufon.replace('#intro h2');
	$('#blocks').masonry({
		columnWidth: 300,
		itemSelector: '.block',
		animate: true
	})
	$('.slide_nav a').click(function(e){
		var el = $(this);
		next_prev = $(this).data('type')
		if(!$('#slides_images').find('li:animated').length){
			if(next_prev == 'next'){
				last_first_el = $('#slides_content li:last');
			} else {
				last_first_el = $('#slides_content li:first');
			}
			if($('#slides_content').data('more') && last_first_el.is('.current')){
				$('.preloader').show();
				var current = $('#slides_content li.current').data('id');
				$.ajax({
					type: 'post',
					url: '/site/ajax/getSlide.php',
					data: 'current='+current+'&next_prev='+next_prev+'&lan='+$('body').data('lan'),
					dataType: 'json',
					success: function(result){
						if(result.success){
							$('#slides_content').data('more', result.more)
							if(next_prev == 'next'){
								$('#slides_content').append(result.slide_content)
								$('#slides_images').append(result.slide_images)
								$('#slides_images li:last .background').fullBg();
							} else {
								$('#slides_content').prepend(result.slide_content)
								$('#slides_images').prepend(result.slide_images)
								$('#slides_images li:first .background').fullBg();
							}
							$('#slides_images img').load(function(){
								$('.preloader').hide();
								nextSlide(next_prev)
							})
						}
					}
				})
			} else {
				nextSlide(next_prev)
			}				
		}
		e.preventDefault();
	})
	$('.projectblock').live('mouseover', function(){
		$(this).find('.image').stop().animate({'opacity': 1})
	}).live('mouseout', function(){
		$(this).find('.image').stop().animate({'opacity': 0.8})
	})
	$('.block.link:not(.wide)').live('click', function(e){
		var el = $(this)
		if($('#blocks').data('load_internal')){
			if(!el.find('.overlay').length){
				var e = $('<div>').addClass('overlay').css({
					height: el.outerHeight(),
					width: el.outerWidth()
				}).appendTo(el)			
			}
			if(!el.find('.new_content').length){
				el.find('.overlay').fadeIn();
				if(el.is('.newsblock')){
					targetUrl = '/site/ajax/getNewsBlock.php';
				} else if(el.is('.bureaublock')) {
					targetUrl = '/site/ajax/getBureauBlock.php';
				} else if(el.is('.contactblock')){
					targetUrl = '/site/ajax/getContactBlock.php';
				} else {
					targetUrl = '/site/ajax/getProjectBlock.php';
				}
				$.ajax({
					type: 'post',
					url: targetUrl,
					data: 'url='+el.data('url')+'&lan='+$('body').data('lan'),
					dataType: 'json',
					success: function(result){
						if(result.success){
							el.find('.overlay').hide()
							el.append(result.data).addClass('wide')
							$.address.value(el.data('url'))
							el.find('.images').height(0)
							el.find('.images img').each(function(){
								if($(this).closest('.images').height() < $(this).outerHeight()){
									$(this).closest('.images').height($(this).outerHeight())
								}
							})

							el.find('.images').cycle({
								fx: 'fade',
								pager: el.find('.images_pager'),
								next: el.find('.images img'),
								timeout:0,
								speed: 400,
								before: function(){
									if(el.find('.images img:last').index() != 0 && !el.find('.cycling').length){
										el.find('.images').addClass('cycling')
									}
								},
								onPrevNextEvent: function(zeroBasedSlideIndex, slideElement){
									if(el.find('.images div.image_cont').eq(slideElement).find('img').outerHeight() != el.find('.images').height()){
										el.find('.images').animate({
											height: el.find('.images div.image_cont').eq(slideElement).find('img').outerHeight()
										})
									}
								},
								onPagerEvent: function(slideElement){
									if(el.find('.images div.image_cont').eq(slideElement).find('img').outerHeight() != el.find('.images').height()){
										el.find('.images').animate({
											height: el.find('.images div.image_cont').eq(slideElement).find('img').outerHeight()
										})
									}
								}							
							})
							refreshMasonry(el, result)
						}
					}
				})			
			} else {
				el.addClass('wide');
				$.address.value(el.data('url'))
				refreshMasonry(el, '')
			}			
		} else {
			window.location.href = el.find('.item_link').attr('href')
		}
		return false;
	})
	$('.wide.block .icon').live('click', function(e){
		var el = $(this).parents('.wide');
 	 	if($.address.pathNames()[0] == el.data('url')){
			$.address.value('none')
 	 	}
		el.removeClass('wide');
		$('#blocks').masonry()
		e.preventDefault();
	})
	$('#search').validate({
		errorPlacement: function(error, element){
			element.parent().append(error)
		}
	})
	$('#search input[type=text]').focus(function(){
		if($(this).val() == $(this).data('default_value')){
			$(this).val('');
		}
	})
	$('#search input[type=text]').blur(function(){
		if(!$(this).val()){
			$(this).val($(this).data('default_value'));
		}
	})
	$(window).scroll(function(){
		if($('#blocks').data('more') && $(this).scrollTop() > ($(document).height() - $(window).height() - 500)){
			$('#blocks').data('more', false)
			$.ajax({
				type: 'post',
				url: '/site/ajax/getMoreBlocks.php',
				data: 'offset='+$('.block:last').index()+'&source='+$('body').data('source')+'&lan='+$('body').data('lan')+'&offsettop='+$('.block:last').css('top'),
				dataType: 'json',
				success: function(result){
					if(result.success){
						$('#blocks').append(result.data)
						$('#blocks').masonry({
							animationOptions: {
								complete: function(){
									$('#blocks').data('more', result.more)
								}
							}
						});
					}
				}
			})
		}
	})
	if($('#blocks').data('more') && ($(window).height() == $(document).height())){
		$(window).trigger('scroll')
	}
	
/* 	home */
	$('.background').fullBg()
	
	if($('.block.link:last').index() == 0 && !$('#news_home').length){
		$('.block').trigger('click')
	}
});

$(window).load(function(){
  if ( $.address.pathNames()[0] && $.address.pathNames()[0] != '#none') {
  	destination = $.address.pathNames()[0]
  	if($('.block.link[data-url="'+destination+'"]').length){
		$('.block.link[data-url="'+destination+'"]').trigger('click')
  	} else {
		$.ajax({
			type: 'post',
			url: '/site/ajax/getMoreBlocks.php',
			data: 'offset='+$('.block:last').index()+'&source='+$('body').data('source')+'&lan='+$('body').data('lan')+'&offsettop='+$('.block:last').css('top'),
			dataType: 'json',
			success: function(result){
				if(result.success){
					$('#blocks').append(result.data)
					$('#blocks').masonry({
						animationOptions: {
							complete: function(){
								if($(this).data('url') == destination){
									$(this).trigger('click')									
									$('#blocks').data('more', result.more)
								}
							}
						}
					});
				}
			}
		})
  	}
  }
});

function refreshMasonry(el, result){
	$('.videoblock.wide').each(function(){
		if($(this).data('url') != el.data('url')){
			$(this).removeClass('wide')
		}
	})
	$('#blocks').masonry({
		animationOptions: {
			duration: 400,
			complete: function(){
				if(el.index() === $(this).index() && firsttime){
					firsttime = false;
					$.scrollTo(el.offset().top - 20, 500, {
						axis: 'y',
						onAfter: function(){
							el.find('.new_content').animate({
								backgroundColor: '#E3F7CE'
							}, 300).delay(300).animate({
								backgroundColor: '#ffffff'
							}, 1000)
							if(result.map){
								initialize(result.map.lat,result.map.long, result.map.zoom, el.data('url'));
							} else {
								el.css('z-index', 100);
							}
						}
					})
					if(el.find('.images img:visible').outerHeight() != el.find('.images').height()){
						el.find('.images').height(el.find('.images img:visible').outerHeight())
					}
				}
			}
		}
	}, function(){
		firsttime = true;
	})	
}

function nextSlide(next_prev){
	if(next_prev == 'next'){
		var image_el = $('#slides_images li.current');
		var content_el = $('#slides_content li.current');
		if(image_el.next().length){
			var image_target = image_el.next();
			var content_target = content_el.next();
		} else {
			var image_target = $('#slides_images li:first');
			var content_target = $('#slides_content li:first');
		}
		
	} else {
		var image_el = $('#slides_images li.current');
		var content_el = $('#slides_content li.current');
		if(image_el.prev().length){
			var image_target = image_el.prev();
			var content_target = content_el.prev();
		} else {
			var image_target = $('#slides_images li:last');
			var content_target = $('#slides_content li:last');
		}
		
	}
	image_el.fadeOut(1000)
	image_el.removeClass('current')
	image_target.addClass('current').fadeIn(800)

	$('.slide_nav').fadeOut(400)
	content_el.removeClass('current').fadeOut(400, function(){
		content_target.addClass('current').fadeIn(600);
		$('.slide_nav').fadeIn(600)
	});
}

  var geocoder;
  var map;
  function initialize(lat, long, zoomlevel, url) {
    geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(lat,long);
    var myOptions = {
		zoom: zoomlevel,
		center: latlng,
		mapTypeId: google.maps.MapTypeId.ROADMAP,
		panControl: false,
		zoomControl: true,
		zoomControlOptions: {
			style: google.maps.ZoomControlStyle.SMALL
		}
    }
    map = new google.maps.Map(document.getElementById("map_"+url), myOptions);
    var marker = new google.maps.Marker({
		position: latlng, 
		map: map
	});  
  }
