/*
	DOCUMENT READY
*/
$(document).ready(function(){
	HOST = 'http://tesgas.pl';
	
	$('#promo #reports ul li a').tooltip({
		track: true,
		delay: 0,
		showURL: false,
		opacity: 1
	});
	
	$('#current-rep p a').tooltip({
		track: true,
		delay: 0,
		showURL: false,
		opacity: 1
	});
	
	/*
		CONTACT form ajax submit
	*/
	$('form#kontaktowy').css('visibility', 'visible').submit(function(){
		$this = $(this);
		$this.find('.warning').removeClass('warning');
		mailFilter = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
		if ($.trim($('#f_name').val()) == ''){
			$('label[for="f_name"]').parent('div').addClass('warning');
		}
		if (!mailFilter.test($.trim($('#f_mail').val()))){
			$('label[for="f_mail"]').parent('div').addClass('warning');
		}
		if ($.trim($('#f_msg').val()) == ''){
			$('label[for="f_msg"]').parent('div').addClass('warning');
		}
		if ($('.warning').size()) {
			alert('Wypełnij poprawnie wszystkie obowiązkowe pola formularza.');
			$('.warning:first label').next().focus();
			return false;
		}
		$this.addClass('processing').find('#unique_id').val((Math.random()) * 10);
		$.post(HOST + '/admin/forms/form_submit.php', $this.find('input, textarea').serialize(), function(){
			$this.removeClass('processing').html('<p><strong>Formularz kontaktowy został wysłany, dziękujemy.</strong></p>');
		});
		return false;
	});
	
	/*
		JOB APPLY form submit
	*/
	$('form#zgloszeniowy').css('visibility', 'visible').submit(function(){			
		$this = $(this);
		$this.find('.warning').removeClass('warning');
		if ($.trim($('#f_name').val()) == ''){
			$('label[for="f_name"]').parent('div').addClass('warning');
		}
		if ($.trim($('#f_job').val()) == ''){
			$('label[for="f_job"]').parent('div').addClass('warning');
		}
		if ($.trim($('#f_file1').val()) == ''){
			$('label[for="f_file1"]').parent('div').addClass('warning');
		}
		if ($('.warning').size()) {
			alert('Wypełnij poprawnie wszystkie obowiązkowe pola formularza.');
			$('.warning:first label').next().focus();
			return false;
		}
		function completeCallback(response) {
			alert(response);
        }
		$this.addClass('processing').find('#unique_id').val((Math.random()) * 10);
		AIM.submit($this.get(0), {
			'onComplete': function(){
				$this.removeClass('processing').html('<p><strong>Formularz zgłoszeniowy został wysłany, dziękujemy.</strong></p>');
			}
		});
		$this.unbind('submit').submit();
		return false;
	});

	/*
		AJAX IFRAME METHOD (AIM) http://www.webtoolkit.info/
	*/
	AIM = {
		frame : function(c) {
			var n = 'f' + Math.floor(Math.random() * 99999);
			var d = document.createElement('DIV');
			d.innerHTML = '<iframe style="display:none" src="about:blank" id="'+n+'" name="'+n+'" onload="AIM.loaded(\''+n+'\')"></iframe>';
			document.body.appendChild(d);
			var i = document.getElementById(n);
			if (c && typeof(c.onComplete) == 'function') {
				i.onComplete = c.onComplete;
			}
			return n;
		},
		form : function(f, name) {
			f.setAttribute('target', name);
		},
		submit : function(f, c) {
			AIM.form(f, AIM.frame(c));
			if (c && typeof(c.onStart) == 'function') {
				return c.onStart();
			} else {
				return true;
			}
		},
		loaded : function(id) {
			var i = document.getElementById(id);
			if (i.contentDocument) {
				var d = i.contentDocument;
			} else if (i.contentWindow) {
				var d = i.contentWindow.document;
			} else {
				var d = window.frames[id].document;
			}
			if (d.location.href == "about:blank") {
				return;
			}
			if (typeof(i.onComplete) == 'function') {
				i.onComplete(d.body.innerHTML);
			}
		}
	}
	
	/*
	* FLASH EMBED
	*/
	if ($('#index').size()) {
		fvars = {HP_host: HOST, section: 'index'};
	}
	else {
		fvars = {HP_host: HOST};
	}
	$('#main-ani').css('visibility', 'visible');
	swfobject.embedSWF(HOST + '/pub/uploadflash/tesgas_top_2_3_2big.swf', 'main-ani', '970', '200', '8', '', fvars, {wmode: 'opaque'}, '');//, {id: 'main-ani-flash'}
	
	/*
	*GALLERY lightbox
	*/
	if ($('#article #uprawnienia').size()){
		$('#article #uprawnienia').show().find('li a').lightBox({imageLoading: HOST + '/pub/uploadimages/lightbox-ico-loading.gif', imageBtnPrev: HOST + '/pub/uploadimages/lightbox-btn-prev.png', imageBtnNext: HOST + '/pub/uploadimages/lightbox-btn-next.png', imageBtnClose: HOST + '/pub/uploadimages/lightbox-btn-close.png', imageBlank: HOST + '/pub/uploadimages/lightbox-blank.gif'});
	}
	/*
	* INWEST FLASH EMBED
	*/
	flash = 'Line.swf';
	var flashDetect = '01month_onedata_mini';
	
	if ($('#chart-select').size()) {
		flashDetect = $('#chart-select').attr('class');
		if(!(flashDetect.match(/onedata_(.*)/))) {
			flash = 'MSCombiDY2D.swf';
		}
	}
	
	$('#inwest-flash').append('<div id="flash-ani"></div>');
	swfobject.embedSWF(HOST + '/pub/uploadflash/' + flash + '?PBarLoadingText=Wczytywanie wykresu&XMLLoadingText=Wczytywanie danych&ParsingDataText=Wczytywanie danych&ChartNoDataText=Brak danych&RenderingChartText=Tworzenie wykresu&LoadDataErrorText=Brak danych&InvalidXMLText=B%C5%82%C4%85d pobierania danych', 'flash-ani', '600', '264', '9.0.0', HOST + '/pub/uploadflash/expressInstall.swf', {HP_host: HOST, dataURL: HOST + '/include/plugins/efresh/stockdata/files/chart_stockdata_tesgas_' + flashDetect + '.xml'}, {});
	
	/*
	* INWEST FLASH EMBED INDEX
	*/
	$('#graph').append('<div id="flash-ani-graph"></div>');
	swfobject.embedSWF(HOST + '/pub/uploadflash/Line.swf?PBarLoadingText=Wczytywanie wykresu&XMLLoadingText=Wczytywanie danych&ParsingDataText=Wczytywanie danych&ChartNoDataText=Brak danych&RenderingChartText=Tworzenie wykresu&LoadDataErrorText=Brak danych&InvalidXMLText=B%C5%82%C4%85d pobierania danych', 'flash-ani-graph', '200', '156', '9.0.0', HOST + '/pub/uploadflash/expressInstall.swf', {HP_host: HOST, dataURL: HOST + '/include/plugins/efresh/stockdata/files/notowaniaCiagleDataProvider.php'}, {});
	
	/*
	* INWEST FLASH SHAREHOLDERS by Shares
	*/
	if($('#shareholders-ani-shares').size()) { 
		$('#shareholders-ani-shares').append('<div id="flash-ani-shareholders-shares"></div>');
		swfobject.embedSWF(HOST + '/pub/uploadflash/Pie3D.swf?PBarLoadingText=Wczytywanie wykresu&XMLLoadingText=Wczytywanie danych&ParsingDataText=Wczytywanie danych&ChartNoDataText=Brak danych&RenderingChartText=Tworzenie wykresu&LoadDataErrorText=Brak danych&InvalidXMLText=B%C5%82%C4%85d pobierania danych', 'flash-ani-shareholders-shares', '280', '160', '9.0.0', HOST + 'pub/uploadflash/expressInstall.swf', {HP_host: HOST, dataURL: HOST + '/include/plugins/efresh/stockdata/files/akcjonariatDataProvider.php?type=0 '}, {});
	}
	
	/*
	* INWEST FLASH SHAREHOLDERS by Votes
	*/
	if($('#shareholders-ani-votes').size()) { 
		$('#shareholders-ani-votes').append('<div id="flash-ani-shareholders-votes"></div>');
		swfobject.embedSWF(HOST + '/pub/uploadflash/Pie3D.swf?PBarLoadingText=Wczytywanie wykresu&XMLLoadingText=Wczytywanie danych&ParsingDataText=Wczytywanie danych&ChartNoDataText=Brak danych&RenderingChartText=Tworzenie wykresu&LoadDataErrorText=Brak danych&InvalidXMLText=B%C5%82%C4%85d pobierania danych', 'flash-ani-shareholders-votes', '280', '160', '9.0.0', HOST + 'pub/uploadflash/expressInstall.swf', {HP_host: HOST, dataURL: HOST + '/include/plugins/efresh/stockdata/files/akcjonariatDataProvider.php?type=1 '}, {});
	}
	
	/*
	* FINANCIAL CHART FLASH
	*/
	
	params = new Array();
	$this = $('#financial-chart-form');
	
	if ($this.attr('class')) {
		params = $('#financial-chart-form').attr('class').split('_');
	}
	else {
		params[0] = 'show';
		params[1] = '1';
		params[2] = '4';
		params[3] = '1';
	}
	if($('#financial-chart').size()) { 
		$('#financial-chart').append('<div id="financial-chart-ani"></div>');
		swfobject.embedSWF(HOST + '/pub/uploadflash/MSCombiDY2D.swf?PBarLoadingText=Wczytywanie wykresu&XMLLoadingText=Wczytywanie danych&ParsingDataText=Wczytywanie danych&ChartNoDataText=Brak danych&RenderingChartText=Tworzenie wykresu&LoadDataErrorText=Brak danych&InvalidXMLText=B%C5%82%C4%85d pobierania danych', 'financial-chart-ani', '625', '260', '9.0.0', HOST + '/pub/uploadflash/expressInstall.swf', {HP_host: HOST, dataURL: HOST + '/include/plugins/efresh/stockdata/files/xmlDataProvider.php?l=' + params[1] + '%26p=' + params[2] + '%26t='+ params[3]}, {});
	}
	
	$this.find('select').change(function() {
		$(this).siblings().find('option:not(:contains("Wybierz")):contains(' + $('option:selected', this).text() + ')').hide().siblings().show();
	});
	
	$this.submit(function() {
		$this.find('.warning').removeClass('warning');
		if ($.trim($('#l').val()) == -1){
			$('label[for="l"]').addClass('warning');
		}
		if ($.trim($('#p').val()) == -1){
			$('label[for="p"]').addClass('warning');
		}
		if ($('.warning').size()) {
			alert('Wybierz rodzaj danych do porównania.');
			$('.warning:first label').next().focus();
			return false;
		}
	});
	
	/*
	*GOOGLE MAPS
	*/
	if ($('#map').size()) {
		if (GBrowserIsCompatible()) {
			$('#map, #map-second').css('visibility', 'visible');
			infoText = $('#map-content').html();
			$('#map-content').remove();
			var map = new GMap2(document.getElementById("map"));
			map.addControl(new GSmallMapControl());
			map.setCenter(new GLatLng(52.405355, 16.740895), 12);
			var latlng = new GLatLng(52.405355, 16.740895);
			marker = new GMarker(latlng);
			
			//marker.addListener('load', function() { alert('loaded'); });
			GEvent.addListener(marker, "click", function(){
				map.openInfoWindowHtml(latlng, infoText);
			});
			map.addOverlay(marker);
			//setTimeout("GEvent.trigger(marker, 'click')", 1000);
			GEvent.trigger(marker, 'click');

			
			infoText2 = $('#map-content-second').html();
			$('#map-content-second').remove();
			var map2 = new GMap2(document.getElementById("map-second"));
			map2.addControl(new GSmallMapControl());
			map2.setCenter(new GLatLng(52.409435, 16.783333), 12);
			var latlng2 = new GLatLng(52.409435, 16.783333);
			marker2 = new GMarker(latlng2);
			GEvent.addListener(marker2, "click", function(){
				map2.openInfoWindowHtml(latlng2, infoText2);
			});
			map2.addOverlay(marker2);
			setTimeout("GEvent.trigger(marker2, 'click')", 5000);
		}
	}

	
	var directionsFromInitValue = $('#directions-from').val();
	$('#directions-from')
		.focus(function(){
			if ($(this).val() == directionsFromInitValue) {
				$(this).val('');
			}
		})
		.blur(function(){
			if ($(this).val() == '') {
				$(this).val(directionsFromInitValue);
			}
		});
	/**
	 * Google Maps Directions embedding
	 */
	if ($('#map-departments').size() && GBrowserIsCompatible()) {
	
		$(window).unload(function(){
			GUnload();
		});
		
		var map = new GMap2(document.getElementById('map-departments'));
		map.setUIToDefault();
		map.addControl(new GMapTypeControl());
		
		
		function getTargetPoint(){
			return GLatLng.fromUrlValue($('#directions-to option:selected').val().slice(1, -1));
		}
		var latlng = getTargetPoint();
		
		var gmarkers = [];
		if ($('.latlng').size() > 1) {
		bounds = new GLatLngBounds();
			$('.latlng').each(function(index){
			var center = GLatLng.fromUrlValue($(this).val().slice(1, -1));
			marker = new GMarker(center);
			gmarkers.push(marker);
			GEvent.addListener(marker, "click", function() {
				text = $('#map-entries li').eq(index).find('.address').html();
				this.openInfoWindowHtml('<h4>' + $('#map-entries li').eq(index).find('h4').text() + '</h4>' + text);
			});
			bounds.extend(marker.getPoint());
			map.setCenter(center);
			map.addOverlay(marker);
		});
		map.setZoom(map.getBoundsZoomLevel(bounds));
		map.setCenter(bounds.getCenter());
		//showInfo(document.URL);
		}
		
		//map.setCenter(latlng, 14);
		//GEvent.trigger(marker, 'click');
		
		var path = [];
		var bounds = new GLatLngBounds();
		var geo = new GClientGeocoder(new GGeocodeCache());
		var reasons=[];
		reasons[G_GEO_SUCCESS]            = "Success";
		reasons[G_GEO_MISSING_ADDRESS]    = "Nierozpoznany adres.";
		reasons[G_GEO_UNKNOWN_ADDRESS]    = "Nierozpoznany adres - spróbuj wpisać tylko nazwę miejscowości.";
		reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Niedostępny adres - nie można pokazać tej trasy.";
		reasons[G_GEO_BAD_KEY]            = "Błędny klucz API.";
		reasons[G_GEO_TOO_MANY_QUERIES]   = "Bład - za dużo zapytań. Spróbuj ponownie za jakiś czas.";
		reasons[G_GEO_SERVER_ERROR]       = "Błąd serwera. Spróbuj ponownie za jakiś czas.";
		reasons[G_GEO_BAD_REQUEST]        = "A directions request could not be successfully parsed.";
		reasons[G_GEO_MISSING_QUERY]      = "Brak lokalizacji w polu wyszukiwania.";
		reasons[G_GEO_UNKNOWN_DIRECTIONS] = "Nie można ustalić połączenia między punktami.";
		
		var baseIcon = new GIcon(G_DEFAULT_ICON);
		baseIcon.iconSize=new GSize(24,38);
		
		var icon1 = G_START_ICON;
		var icon3 = G_END_ICON;
		var addresses = [];
		var startpoint = null;
		
		function doStart(point){
			path[1] = getTargetPoint();
			if (startpoint != null){
				map.removeOverlay(startpoint);
				map.setCenter(path[1], 12);
				bounds = new GLatLngBounds();
			}
			startpoint = new GMarker(point,{dragable:true, icon:icon1}); 

			GEvent.addListener(startpoint, 'dragend', function(){
				path[0] = startpoint.getPoint();
				addresses[0] = '';
			});
			map.addOverlay(startpoint);

			path[0] = point;
			bounds.extend(path[0]);
			bounds.extend(path[1]);
			map.setZoom(map.getBoundsZoomLevel(bounds));
			map.setCenter(bounds.getCenter());
			directions();
		}

		var gdir = new GDirections(null, document.getElementById('path'));

		GEvent.addListener(gdir,'error', function(){
			var code = gdir.getStatus().code;
			var reason = 'Kod ' + code;
			if (reasons[code]){
				reason = "Kod " + code + ': ' + reasons[code]
			}
			alert('Failed to obtain directions, ' + reason);
		});

		var poly;
		GEvent.addListener(gdir, 'load', function(){
			if (poly)
				map.removeOverlay(poly);
			poly = gdir.getPolyline();
			map.addOverlay(poly);
		});
		
		GEvent.addListener(gdir, 'addoverlay', function(){
			$('#article tr td:has("a")').each(function(){
				$(this).html($(this).text());
			});
			$('#article tr td').css('cursor', 'default');
		});

		function directions(){
		//alert(latlng);
			if (addresses[0]){
				var a = addresses[0] + "@" + path[0].toUrlValue(6)
			}
			else {
				var a = path[0].toUrlValue(6)
			}
			var b = path[1].toUrlValue(6)
			var a = 'from: ' + a + ' to: ' + b;
			gdir.load(a, {getPolyline:true});
			map.removeOverlay(marker);
			marker = new GMarker(path[1], {icon:icon3});
			map.addOverlay(marker);
		}
		
		function showAddress(){
			var search = $('#directions-from').val();
			addresses[0] = search;
			geo.getLatLng(search, function (point){ 
				if (point){
					doStart(point);
				}
				else {
					var result = geo.getCache().get(search);
					if (result){
						var reason = 'Kod ' + result.Status.code;
						if (reasons[result.Status.code]){
							reason = reasons[result.Status.code]
						}
					}
					else {
						var reason = '';
					}
					alert('Nie można odnaleźć "' + search + '". ' + reason);
				}
			});
		}
		
		$('#directions')
			.show()
			.submit(function(){
				if($('#directions-to option:selected').val() == -1) {
					alert('Wybierz oddział.');
					return false;
				}
				showAddress();
				return false;
			});
		
		$('#directions-to')
			.change(function(){
				$('#map-entries li:contains("' + $('option:selected', this).text() + '")').addClass('active').siblings().removeClass('active');
				if (startpoint != null){
					showAddress();
				} else {
					map.setCenter(getTargetPoint(), 14);
				}
			});
		
	}
	
});
