
HOST = 'http://hbp-sa.pl';

$(function(){

	/**
	* INWEST FLASH SHAREHOLDERS
	*/
	$('#shareholders-ani').append('<div id="flash-ani-shareholders"></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', '310', '177', '9.0.0', HOST + '/pub/uploadflash/expressInstall.swf', {HP_host: HOST, dataURL: HOST +'/include/plugins/hbp/akcjonariatDataProvider.php'}, {wmode: 'transparent'});

	/*
		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';
	}
	
	$('#financial-chart').append('<div id="financial-chart-ani"></div>');
	swfobject.embedSWF('/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', '448', '260', '9.0.0', '/pub/uploadflash/expressInstall.swf', {HP_host: HOST, dataURL: '/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;
		}
	});
	/*
	 Share Calc Validator
	*/
	$('#share-calc').submit(function() {
		$this = $(this);
		$this.find('.warning').removeClass('warning');
		if ($.trim($('#buy').val()) == ''){
			$('label[for="buy"]').parent('div').addClass('warning');
		}
		if ($.trim($('#sell').val()) == ''){
			$('label[for="sell"]').parent('div').addClass('warning');
		}
		if ($.trim($('#quantity').val()) == ''){
			$('label[for="quantity"]').parent('div').addClass('warning');
		}
		if ($('.warning').size()) {
			alert('Wypełnij poprawnie wszystkie obowiązkowe pola formularza.');
			$('.warning:first label').next().focus();
			return false;
		}
		$('#calc-results').remove();
		$this.after('<div id="calc-results" class="processing"></div>');
		$.post(HOST + '/showpage.php?pageID=68', $this.find('input'), function(data){
			$('#calc-results').removeClass('processing').append(data);
		});
		return false;
	});
	
	/*
		jQUERY Datepicker
	*/
	if ($('#buy').size()) {
		$('#buy, #sell').datepicker({ dateFormat: 'yy-mm-dd', monthNames: ['Styczeń', 'Luty', 'Marzec', 'Kwiecień', 'Maj', 'Czerwiec', 'Lipiec', 'Sierpień', 'Wrzesień', 'Październik', 'Listopad', 'Grudzień'], dayNamesMin: ['Nd', 'Pn', 'Wt', 'Śr', 'Cz', 'Pt', 'So'], firstDay: 1 });
	}
	
	/*
		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('/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', '448', '264', '9.0.0', '', {dataURL: '/include/plugins/efresh/stockdata/files/hbp_chart_stock_' + flashDetect + '.xml'}, {});
	
	/*
		RAPORTY - tables content navigation
	*/
	if ($('#article .section').size() > 1) {
		$('#article').prepend('<ul id="content-nav"><li><a href="#r-1">Roczny<br />jednostkowy</a></li><li><a href="#r-2">Roczny<br />skonsolidowany</a></li><li><a href="#r-3">Kwartalny<br />jednostkowy</a></li><li><a href="#r-4">Kwartalny<br />skonsolidowany</a></li></ul>');
		$('.section').each(function(){
			$('h3', this).remove();
		});
		$('#content-nav li a').click(function(){
			$('#r-' + $(this).attr('href').slice(-1)).show().siblings('.section').hide();
			$(this).addClass('active').parent().siblings().find('a').removeClass('active');
			return false;
		}).filter(':first').click();
	}
	
	/*
		RAPORTY - tables content navigation
	*/
	if ($('#article #wza').size()) {
		$('#content-nav li a')
			.click(function(){
				$('#wza')
					.show();
				$('#content-nav')
					.show();
				$(this)
					.addClass('active')
						.parent()
							.siblings()
								.find('a')
									.removeClass('active');
				$('.zwa > li')
					.hide()
						.filter('.date:contains("' + $(this).text() + '-")')
							.parent()
								.show()
				return false;
			})
			.filter(':first').click();
	}
	
	// INPUT:FOCUS HACK FOR IE
	$('input:text, textarea').focus(function(){
		$(this).addClass('focus');
	})
	.blur(function(){
		$(this).removeClass('focus');
	});
	field = $('#content #main-content #newsletter-mail');
	$('#content #main-content #newsletter form').submit(function(){
		$(field).val($.trim(field.val()));
		if (!(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(field.val()))) {
			alert('Podany adres e-mail jest nieprawidłowy.');
			$(field).focus();
			return false;
		}
	});
	
	//JS-PORTFOLIO
	if ($('.portfolio-map li h3').size()){
		$('.portfolio-map').attr('class', 'js-portfolio-map').after('<div class="js-portfolio-gallery"></div>').show();
		$('.js-portfolio-map li').each(function(i){
			if ($('.coordinates', this).text() == '0/0') {
				$(this).find('h3').hide();
			}
			else {
				markerLocation = $('.location', this).text();
				splitStrPos = $('.coordinates', this).text().indexOf('/');
				markerCoordinatesX = $('.coordinates', this).text().substring(0, splitStrPos);
				markerCoordinatesY = $('.coordinates', this).text().substring(splitStrPos + 1, $('.coordinates', this).text().length);
				if ($('.coordinates', this).text() == '') {
					$(this).find('h3').hide();
				} else {
					$(this).find('h3').css({left: markerCoordinatesX + 'px', top: markerCoordinatesY + 'px'}).wrapInner('<a></a>').find('a').attr({href: '#' + markerLocation, title: markerLocation}).tooltip({track: true, delay: 100, showURL: false, showBody: " - "}).click(function(){
						$('.js-portfolio-map li h3').removeClass('active');
						$(this).parents('h3').addClass('active');
						$('.js-portfolio-gallery').empty().hide();
						$('.js-portfolio-map li .location:contains("' + $(this).parents('li').find('.location').text() + '")').each(function(i){
							gallery = ($(this).parents('li').find('.gallery').size()) ? $(this).parents('li').find('.gallery').html() : '';
							$('<h3></h3>').html($(this).parents('li').find('h3').text()).appendTo('.js-portfolio-gallery');
							$('<div class="description"></div>').html($(this).parents('li').find('.description').html()).appendTo('.js-portfolio-gallery');
							$('<ul></ul>').html(gallery).appendTo('.js-portfolio-gallery').find('a').lightBox({overlayOpacity:0.7, imageLoading: '/pub/uploadimages/lightbox-ico-loading.gif', imageBtnPrev: '/pub/uploadimages/lightbox-btn-prev.png', imageBtnNext: '/pub/uploadimages/lightbox-btn-next.png', imageBtnClose: '/pub/uploadimages/lightbox-btn-close.png', imageBlank: 'images/lightbox-blank.gif', txtImage: 'Zdjęcie', txtOf: 'z'});
						});
						$('.js-portfolio-gallery').fadeIn('fast');
					});
				}
			}
		});
	}
	
	if ($('#investments').size()){
		$('#investments').show();
		clickText = $('#investments p').html();
		$('.portfolio-map-small li').each(function(i){
			if ($('.coordinates', this).text() == '0/0') {
				$(this).find('h3').hide();
			}
			else {
				markerLocation = $('.location', this).text();
				splitStrPos = $('.coordinates', this).text().indexOf('/');
				markerCoordinatesX = Math.round($('.coordinates', this).text().substring(0, splitStrPos) / 1.65) + 10;
				markerCoordinatesY = Math.round($('.coordinates', this).text().substring(splitStrPos + 1, $('.coordinates', this).text().length) / 1.7) + 9;
				if ($('.coordinates', this).text() == '') {
					$(this).find('h3').hide();
				}
				$(this).find('h3').css({left: markerCoordinatesX + 'px', top: markerCoordinatesY + 'px'}).wrapInner('<a></a>').find('a').attr({href: HOST + '/showpage.php?pageID=47#' + markerLocation, title: markerLocation}).tooltip({track: true, delay: 100, showURL: false, showBody: " - "}).click(function(){
					showGallery($(this).parents('h3').siblings('.location').text());
				}).mouseover(function(){
					$(this).parents('.content').siblings('.thumb').fadeIn().find('img[src$="gtx/"]').hide();
					$('#investments p').html($(this).html());
				}).mouseout(function(){
					$('.portfolio-map-small li .thumb').fadeOut();
					$('#investments p').html(clickText);
				});
			}
		});
	}

	var showGallery = function(loc){
		$('.js-portfolio-map li .location:contains("' + loc + '"):eq("0")').siblings('h3').find('a').trigger('click');
	};
	
	showGallery(location.hash.replace('#', ''));
	
	$('#article .zsz-politic a').eq(0).lightBox({overlayOpacity:0.7, imageLoading: '/pub/uploadimages/lightbox-ico-loading.gif', imageBtnPrev: '/pub/uploadimages/lightbox-btn-prev.png', imageBtnNext: '/pub/uploadimages/lightbox-btn-next.png', imageBtnClose: '/pub/uploadimages/lightbox-btn-close.png', imageBlank: 'images/lightbox-blank.gif', txtImage: 'Zdjęcie', txtOf: 'z'});
	$('#article .zsz-politic a').eq(1).lightBox({overlayOpacity:0.7, imageLoading: '/pub/uploadimages/lightbox-ico-loading.gif', imageBtnPrev: '/pub/uploadimages/lightbox-btn-prev.png', imageBtnNext: '/pub/uploadimages/lightbox-btn-next.png', imageBtnClose: '/pub/uploadimages/lightbox-btn-close.png', imageBlank: 'images/lightbox-blank.gif', txtImage: 'Zdjęcie', txtOf: 'z'});
	
	$('#show-selected-year #filter').change(function() {
		var s = ($('#show-selected-year').attr('action').indexOf('?') > -1) ? '&' : '?';
		document.location.href = $('#show-selected-year').attr('action') + s + 'filter=' + $('option:selected', this).val();
	});
	
	/*
	 * FlowPlayer active
	 */
	$('#content .portfolio-video-small a').lightBox();
	$('.flow-player-link').bgiframe();
	if($('.flow-player-link').size()) {
		$('#main-picture').append('<div id="main-picture-flash"></div>');
		flowplayer('main-picture-flash', {src: HOST + '/pub/uploadflash/flowplayer-3.0.5.swf', wmode: 'transparent'}, {
			clip : {
        autoPlay: true, 
        baseUrl: HOST + '/pub/uploadflash/'
			}, 
			playlist: [
        'banner_hbp.flv'
			],
			plugins: {
        controls: null
			}, 
			onBeforeFinish: function() { 
					return false; 
			} 
		});
	}
		
	/*
		TEXT INPUTS value show/hide
	*/
	var $dir = $('#directions input:text[value]');
	var startVal = $dir.focus(function(){(this.value == startVal) && $dir.val('')}).blur(function(){(!this.value) && $dir.val(startVal)}).val();
	
	/*
		Calendar archive show/hide
	*/
	$('a.calendar-archive').click(function() {
		$this = $('#calendar-archive');
		if ($this.attr('class') == 'entries active') {
			$this.hide().removeClass('active');
		}
		else {
			$('#calendar-archive').show().addClass('active');
		}
		return false;
	});
	
	/*
		GOOGLE MAPS
	*/
	if ($('#map').size() && GBrowserIsCompatible()) {
		
		var path = [];
		path[0] = '';
		var map = new GMap2(document.getElementById("map"));
		map.addControl(new GSmallMapControl());
		map.addControl(new GMapTypeControl());
		var hbpIcon = new GIcon(G_DEFAULT_ICON);
		hbpIcon.image = HOST + "/pub/uploadimages/marker.png";
		bounds = new GLatLngBounds();
		$('.latlng').each(function(index){
			var center = GLatLng.fromUrlValue($(this).val().slice(1, -1));
			path.push(center);
			marker = new GMarker(center, {icon: hbpIcon});
			GEvent.addListener(marker, "click", function() {
				this.openInfoWindowHtml('<div class="info"><h3>' + $('#map-entries h3:eq("' + index + '")').html() + '</h3>' + $('#map-entries .address:eq("' + index + '")').html() + '</div>');
			});
			bounds.extend(marker.getPoint());
			map.setCenter(center);
			map.addOverlay(marker);
		});
		map.setZoom(map.getBoundsZoomLevel(bounds) - 1);
		map.setCenter(bounds.getCenter());
		
		$('#branches').change(function(){
			path[1] = GLatLng.fromUrlValue($('option:selected', this).val().slice(1, -1));
		});
		
		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){
			if (startpoint != null){
				map.removeOverlay(startpoint);
				map.setCenter(path[1], 12);
				bounds = new GLatLngBounds();
			}
			startpoint = new GMarker(point,{dragable:true, icon:icon1});
			
			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(){
			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 = $('#search').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').submit(function(){
			showAddress();
			return false;
		});
	}
	
});