var newsCurrent = 1
var newsI = 1
var newsTimeout = null

var map;
var map_add;
var geoXml;
var geocoder;
var placemarkControl = null;
var mapPointId;
var mapLatitude = false;
var mapLongitude = false;
var mapZoom = false;

var regions = {
	1  : 'dolnośląskie',
	2  : 'kujawsko-pomorskie',
	3  : 'lubelskie',
	4  : 'lubuskie',
	5  : 'łódzkie',
	6  : 'małopolskie',
	7  : 'mazowieckie',
	8  : 'opolskie',
	9  : 'podkarpackie',
	10 : 'podlaskie',
	11 : 'pomorskie',
	12 : 'śląskie',
	13 : 'świętokrzyskie',
	14 : 'warmińsko-mazurskie',
	15 : 'wielkopolskie',
	16 : 'zachodniopomorskie'
};

$(function () {

	$('.mailto').each(function () {
		var rel = $(this).attr('rel')
		rel = rel.split(';')
		$(this).html(rel[1]+'@'+rel[0])
		$(this).attr('href', 'mailto:'+rel[1]+'@'+rel[0])
	})
	
	
	$('.d-map').each(function () {
		var id = $(this).attr('id')
		id = id.replace('#', '')
		var geo = $(this).attr('rel')
		geo = geo.split(',')
		var contactMap = new google.maps.Map2(document.getElementById(id));
		var point = new google.maps.LatLng(geo[0], geo[1])
		contactMap.setUIToDefault();
		contactMap.setCenter(point, 13)
		
		var fmIcon = new GIcon(G_DEFAULT_ICON);
		/*fmIcon.image = _BASE_URL+"static/images/logo-map.png";
		fmIcon.iconSize = new GSize(80, 46);*/
		markerOptions = { icon:fmIcon };
		//markerOptions = { };
		contactMap.addOverlay(new GMarker(point, markerOptions));
	})
	
	
	$('.cp').hide()
	$('#cp').val('6')

	$('#serce').flash({ src: _BASE_URL+'static/flash/serce.swf', width: 44, height: 33, wmode: 'transparent' }, { version: 8 });
	$('#splash').flash({ src: _BASE_URL+'static/flash/promotion.swf', width: 635, height: 235, wmode: 'transparent' }, { version: 9 });
	
	$('#form-fast-contact').submit(function () {
		
		var form_data = $(this).serializeArray()
		
		$('#form-fast-contact').find('input, select, textarea').attr('disabled', 'disabled')
		$.post(_BASE_URL+'c/kontakt', form_data, function (data) {
			$('#form-fast-contact').html(data)
		})
		
		
		return false;
	})
	
	// IE 6 PNG fixes
	$('#logo a, #menu, #splash-footer, #box-contact div.footer, #regions-selector').ifixpng()
	
	newsSwitcherInit()
	
	$('#block-newsletter form .submit').hover(function () { $(this).addClass('submit-hover') }, function () { $(this).removeClass('submit-hover'); $(this).removeClass('submit-down') })
	$('#block-newsletter form .submit').mousedown(function () { $(this).addClass('submit-down') })
	$('#block-newsletter form .submit').mouseup(function () { $(this).removeClass('submit-down') })
	
	$('.submit').live('mouseover', function () { $(this).addClass('submit-hover') })
	$('.submit').live('mouseout', function () { $(this).removeClass('submit-hover'); $(this).removeClass('submit-down') })
	$('.submit').live('mousedown', function () { $(this).addClass('submit-down') })
	$('.submit').live('mouseup', function () { $(this).removeClass('submit-down') })
	
	$('.reset').hover(function () { $(this).addClass('reset-hover') }, function () { $(this).removeClass('reset-hover'); $(this).removeClass('reset-down') })
	$('.reset').mousedown(function () { $(this).addClass('reset-down') })
	$('.reset').mouseup(function () { $(this).removeClass('reset-down') })
	
	$('#block-news .block-header a').mousedown(function () { $(this).addClass('news-header-down') })
	$('#block-news .block-header a').mouseup(function () { $(this).removeClass('news-header-down') })
	$('#block-news .block-header a').mouseout(function () { $(this).removeClass('news-header-down') })
	
	$('.btn-more').hover(function () { $(this).addClass('btn-more-hover') }, function () { $(this).removeClass('btn-more-hover'); $(this).removeClass('btn-more-down') })
	$('.btn-more').mousedown(function () {
		$(this).addClass('btn-more-down')
	})
	
	$('.btn-print').hover(function () { $(this).addClass('btn-print-hover') }, function () { $(this).removeClass('btn-print-hover'); $(this).removeClass('btn-print-down') })
	$('.btn-print').mousedown(function () {
		$(this).addClass('btn-print-down')
	})
	
	$('.btn-show').hover(function () { $(this).addClass('btn-show-hover') }, function () { $(this).removeClass('btn-show-hover'); $(this).removeClass('btn-show-down') })
	$('.btn-show').mousedown(function () {
		$(this).addClass('btn-show-down')
	})
	
	$('.btn-business-card').hover(function () { $(this).addClass('btn-business-card-hover') }, function () { $(this).removeClass('btn-business-card-hover'); $(this).removeClass('btn-business-card-down') })
	$('.btn-business-card').mousedown(function () {
		$(this).addClass('btn-business-card-down')
	})
	
	$('#btn-fast-contact').hover(function () { $(this).addClass('fast-contact-hover') }, function () { $(this).removeClass('fast-contact-hover'); $(this).removeClass('fast-contact-down') })
	$('#btn-fast-contact').mousedown(function () {
		$(this).addClass('fast-contact-down')
		return false
	})
	
	$('#btn-fast-contact').mouseup(function () {
		$(this).removeClass('fast-contact-down')
		$(this).toggleClass('fast-contact-pressed')
		
		if ($(this).hasClass('fast-contact-pressed'))
		{
			if ($('#box-contact .content:empty').size() > 0) {
				$.get(_BASE_URL+'c/kontakt?fast=true', {}, function (data) {
					$('#box-contact .content').html(data)
					$('#box-contact').data('height', $('#box-contact').height()).css({height: 0})
					$('#box-contact .buttons').hide()
					$('#box-contact').animate({height: $('#box-contact').data('height')}, 900, 'easeOutBounce', function () {
						$('#box-contact .buttons').fadeIn('slow')
					})
				})
			} else {
				$('#box-contact .buttons').hide()
				$('#box-contact').animate({height: $('#box-contact').data('height')}, 900, 'easeOutBounce', function () {
					$('#box-contact .buttons').fadeIn('slow')
				})
			}
		}
		else
		{
			$('#box-contact').fadeOut('slow')
		}
		return false
	})
	
	$('#block-newsletter form .email').val('Twój adres e-mail')
	$('#block-newsletter form .email').click(function () { if ($(this).val() == 'Twój adres e-mail') { $(this).val('') } })
	$('#block-newsletter form .email').blur(function () { if ($(this).val() == '') { $(this).val('Twój adres e-mail') } })
	
	$('#banner-map a span').css({opacity: 0})
	$('#banner-map a').hover(
		function () { $(this).find('span').stop().animate({opacity: 1}, 1200) },
		function () { $(this).find('span').stop().animate({opacity: 0}, 1200) }
	)
	
	mapInit()
	
	var tab = $('#toolbar li.active').find('a').attr('href')
	$('body.mapa_punktow .tab').hide()
	if (tab && tab != '#') {
		$(tab).show()
	}
	
	$('#toolbar li.btnTab a').click(function () {
		switchTab($(this).attr('href'))
		return false
	})
	
	$('.point a.map').click(function () {
		var point = $(this).attr('rel').split(':')
		if (point.length > 0) {
			mapShowPoint(map, point[0], point[1])
		}
		return false
	})
	
	$('.point').hover(
		function () {
			$(this).addClass('hover')
		},
		function () {
			$(this).removeClass('hover')
		}
	)
	
	$('a[href=#tab-add-point]').click(function () {
		pointAddMapInit()
		return false
	})
	
	var tabName = document.location.toString()
	tabName = tabName.split('#')
	if (tabName.length > 1) {
		tabName = tabName[1];
		if (tabName != '') {
			if ($('#'+tabName).size() > 0) {
				switchTab('#'+tabName)
				pointAddMapInit()
			}
		}
	}
	
	$('.in-page-gallery a').prettyPhoto()
	
	$('<div id="about-photo"></div>').css({'text-align': 'center'}).appendTo('.about .page-content')
	//$('#about-photo').flash({ src: _BASE_URL+'static/flash/ofirmie_foto.swf', width: 533, height: 400 }, { version: 8 });
	
})

function showDirection(direction_to) {
	directions = new GDirections(map, document.getElementById("direction_details"));
	directions.load("from: "+$('#direction_from').val()+" to: "+direction_to);
	
	$('#direction_details').addClass('ajax-load')
	$('#direction_details').html('<p class="notify">Wyszukiwanie trasy dojazdu...</p>')
	
	GEvent.addListener(directions, "error", function () {
		$('#direction_details').html('<p class="error">Nie znaleziono trasy dojazdu. Proszę sprawdzić poprawność adresów.</p>')
		$('#direction_details').removeClass('ajax-load')
	})
	
	GEvent.addListener(directions, "load", function() {
		$('#direction_details').html('')
		$('#direction_details').removeClass('ajax-load')
		$('#direction-print').show()
	})
	
	return false;
}

function pointAddMapInit() {
	var forms = $('#form-add-point form').length
	if (forms == 0) {
		$('#form-add-point').load(_BASE_URL+'c/mapa_punktow/dodaj', function () {
			$('#form-add-point').removeClass('ajax-load')
		})
	}
}

function switchTab(tabName) {
	$('#toolbar li.active').removeClass('active')
	$('#toolbar a[href='+tabName+']').parent().addClass('active')
	$('.page-content .tab').hide()
	$(tabName).show()
}

function mapShowPoint(m, lat, lng) {
	switchTab('#tab-map')
	m.setZoom(8)
	m.panTo(new google.maps.LatLng(lat, lng))
	//m.setCenter(new google.maps.LatLng(50.000, 19.900), 7);
}

function newsSwitcherInit() {
	
	var total = $('#block-news .news').size()
	var i = 1
	var j = 1
	
	$('<ul></ul>').attr('id', 'news-switcher').appendTo('#block-news .navigation')
	
	$('#block-news .news').each(function () {
		if (j != 1) { $(this).css({'opacity': 0, 'left': '265px'}) }
		
		$(this).attr('id', 'main-news-'+j)
		
		var item = $('<li><a href="#" title="'+$('.title', this).text()+'"><span>'+j+'</span></a></li>')
			.attr('id', 'news-switch-'+j)
			.appendTo('#news-switcher')
		
		if (j == 1) { $(item).addClass('first') }
		if (j == total) { $(item).addClass('last') }
		
		$(item).find('a').data('num', j)
		
		j++
	})
	
	newsTimeout = setInterval("newsShuffle()", 3000)
	
	$('#news-switcher li#news-switch-1').addClass('active')
	
	$('#news-switcher li a').click(function () {
		var j = $(this).data('num')
		clearInterval(newsTimeout)
		newsChange(j)
		newsTimeout = setInterval("newsShuffle()", 3000)
		return false
	})
	
}

function newsShuffle() { 
	var total = $('#block-news .news').size()
	if (newsI == total) { newsI = 1 }
	else { newsI++ }
	newsChange(newsI)
}

function newsChange(i) {//
	$('#main-news-'+newsCurrent).stop().animate({opacity: 0, left: '+=265px'}, 300, "easeInBack")
	$('#main-news-'+i).stop().animate({left: 17, opacity: 1}, 300, "easeInBack")
	$('#news-switcher li').removeClass('active')
	$('#news-switcher #news-switch-'+i).addClass('active')
	newsCurrent = i
	newsI = i
}

function mapInit() {
	if ($('#map').length == 0) { return false; }
	map = new google.maps.Map2(document.getElementById("map"));
	geocoder = new GClientGeocoder();
	
	queryGeo = '';
	if (mapPointId > 0) {
		queryGeo = '?point_id='+mapPointId;
	}
	
	geoXml = new GGeoXml(_BASE_URL+"c/mapa_punktow_xml" + queryGeo);
	
	/*var fmIcon = new GIcon(G_DEFAULT_ICON);
	fmIcon.image = _BASE_URL+"static/images/marker.png";
	fmIcon.iconSize = new GSize(23, 28);
	markerOptions = { icon:fmIcon };*/
	if (mapLatitude == false) {
	 mapLatitude = 51.919438;
	}
	if (mapLongitude == false) {
	 mapLongitude = 19.145136;
	}
	if (mapZoom == false) {
	 mapZoom = 6;
	}
	
	map.setCenter(new google.maps.LatLng(mapLatitude, mapLongitude), mapZoom);
	map.setUIToDefault();
	map.addOverlay(geoXml);
    
	$('#regions ul li a').click(function () {
		showAddress($(this).attr('title'), map)
		$('#regions li').removeClass('active')
		$(this).parent().addClass('active')
		return false;
	})
	
	$('#regions ul li').hover(
		function () {
			$('#regions-selector').stop().animate({top: $('#regions ul').position().top+$(this).position().top}, 500, 'easeOutElastic')
		},
		function () {
			$('#regions-selector').stop().animate({top: $('#regions ul').position().top+$('#regions li.active').position().top}, 500, 'easeOutElastic')
		}
	)
}

function showAddress(address, m) {
	geocoder.getLatLng(
		address,
		function(point) {
			if (!point) {
				alert(address + " nie znaleziono");
			} else {
				m.setZoom(8);
				m.panTo(point);
				//var marker = new GMarker(point);
				//m.addOverlay(marker);
				//marker.openInfoWindowHtml(address);
			}
		}
	);
}

function initMapContact() {
	if ($('#map-contact').length == 0) { return false; }
	
	var contactMap = new google.maps.Map2(document.getElementById("map-contact"));
	var point = new google.maps.LatLng(49.922341, 19.975449)
	contactMap.setUIToDefault();
	contactMap.setCenter(point, 13)

	var fmIcon = new GIcon(G_DEFAULT_ICON);
	fmIcon.image = _BASE_URL+"static/images/logo-map.png";
	fmIcon.iconSize = new GSize(80, 46);
	markerOptions = { icon:fmIcon };
	//markerOptions = { };
	contactMap.addOverlay(new GMarker(point, markerOptions));
}

function mapAddInit() {
	if ($('#map-add').length == 0) { return false; }
	map_add = new google.maps.Map2(document.getElementById("map-add"));
	map_add.setCenter(new google.maps.LatLng(51.919438, 19.145136), 6);
	geocoder.getLatLng(
		'województwo dolnośląskie',
		function(point) {
			if (point) {
				map_add.setZoom(8);
				map_add.panTo(point);
				
				placemarkControl = new GMarker(point, {draggable: true});

				GEvent.addListener(placemarkControl, "dragstart", function() {
					
				});

				GEvent.addListener(placemarkControl, "dragend", function() {
					placemarkControl.openInfoWindowHtml("Wypełnij dane po lewej stronie okna<br /> a następnie podnieś wskaźnik i upuść<br /> w dokładniejszym punkcie.");
					$('#latitude').val(placemarkControl.getLatLng().lat())
					$('#longitude').val(placemarkControl.getLatLng().lng())
				});

				var fmIcon = new GIcon(G_DEFAULT_ICON);
				fmIcon.image = _BASE_URL+"static/images/marker.png";
				fmIcon.iconSize = new GSize(23, 28);
				markerOptions = { icon:fmIcon };
				
			    map_add.addOverlay(placemarkControl, markerOptions);
			    placemarkControl.openInfoWindowHtml("Wypełnij dane po lewej stronie okna<br /> a następnie podnieś wskaźnik i upuść<br /> w dokładniejszym punkcie.");
			    $('#latitude').val(placemarkControl.getLatLng().lat())
				$('#longitude').val(placemarkControl.getLatLng().lng())
			}
		}
	);
	map_add.setUIToDefault();
	
	$('#region_id').change(function () {
		var region_name = '';
		if ($('#city').val() == '') {
			region_name = 'województwo ' + regions[$(this).val()];
		} else {
			region_name = 'województwo ' + regions[$('#region_id').val()] + ', ' + $('#city').val();
		}
		geocoder.getLatLng(
			region_name,
			function(point) {
				if (point) {
					map_add.setZoom(8);
					map_add.panTo(point);
					if (placemarkControl !== null) {
						placemarkControl.setPoint(point)
					}
				}
			}
		);
	})
	
	$('#city').blur(function () {
		var region_name = 'województwo ' + regions[$('#region_id').val()] + ', ' + $(this).val();
		geocoder.getLatLng(
			region_name,
			function(point) {
				if (point) {
					map_add.setZoom(8);
					map_add.panTo(point);
					if (placemarkControl !== null) {
						placemarkControl.setPoint(point)
					}
				}
			}
		);
	})
	
	$('#form-add-point form').submit(function () {
		
		var form_data = $(this).serializeArray()
		
		$('#form-add-point').find('input, select, textarea').attr('disabled', 'disabled')
		$.post(_BASE_URL+'c/mapa_punktow/dodaj', form_data, function (data) {
			$('#form-add-point').html(data)
		})
		
		
		return false;
	})
}
