
HOST = 'http://hbp-sa.pl/en';

$(function(){
	
	$.fn.colorbox.settings.opacity = '0.5';
	$.fn.colorbox.settings.previous = '&lt; previous';
	$.fn.colorbox.settings.next = 'next &gt;';
	$.fn.colorbox.settings.close = 'close';
	$.fn.colorbox.settings.current = '';
	
	$('#article a:has(.thumb)').colorbox();
	
	$('.reminder-link').live('click', function() {
		link = $(this);
		$.fn.colorbox({href: function() {
			return link.attr('href') + '?filter=reminder';
		}, width:700});
		return false;
	});
	
	if($('#reminder-confirm').size()) {
		$.fn.colorbox({html: '<div id="article"><p style="font-size:12px;font-weight:700;">Reminder was confirmed.</p></div>'});
	}
	
	/*
	 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('Please fill all required fields.');
			$('.warning:first label').next().focus();
			return false;
		}
		$('#calc-results').remove();
		$this.after('<div id="calc-results" class="processing"></div>');
		$.post(HOST + '/showpage.php?pageID=55', $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: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], dayNamesMin: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'], firstDay: 1 });
	}
	
	/**
	 * Movie on layer
	 
	if (($.cookie('layer-movie') != 1) && ($('.sOverlibDiv').size() < 1)) {
		$.cookie('layer-movie', 1, {path: '/', expires: 365});
		$.fn.colorbox({html: '<div id="layer-movie"></div>', width:670, height:420, onComplete: function() {
			flowplayer(
				"layer-movie",  
				HOST + "/pub/uploadflash/flowplayer-3.1.5.swf", {
					plugins: { 
						pseudo: {
							url: HOST + '/pub/uploadflash/flowplayer.pseudostreaming-3.1.3.swf'
						}
					}, 
					clip: {
						provider: 'pseudo',
						url: 'http://www.pbg-sa.pl/en/pub/uploadvideo/kartka_ang.flv'
					
					}
				
				}
			);
		}});
	}*/
	
	/**
	 * Social icons tracking
	 */
	$('#article #community-logos #cm-1 a').click(function() {
		_gaq.push(['_trackEvent', 'wykop', 'click', 'share']);
	});
	$('#article #community-logos #cm-2 a').click(function() {
		_gaq.push(['_trackEvent', 'flacker', 'click', 'share']);
	});
	$('#article #community-logos #cm-3 a').click(function() {
		_gaq.push(['_trackEvent', 'blip', 'click', 'share']);
	});
	$('#article #community-logos #cm-4 a').click(function() {
		_gaq.push(['_trackEvent', 'digg', 'click', 'share']);
	});
	$('#article #community-logos #cm-5 a').click(function() {
		_gaq.push(['_trackEvent', 'facebook', 'click', 'share']);
	});
	$('#article #community-logos #cm-6 a').click(function() {
		_gaq.push(['_trackEvent', 'twitter', 'click', 'share']);
	});
	
	$('#reminder-form button').live('click', function() {
		$this = $('#reminder-form');
		$this.css('height', $this.height()).find('.warning').removeClass('warning');
		mailFilter = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
		if($this.find('#reminder_email').val() == '' || !mailFilter.test($.trim($('#reminder_email').val()))) {
			$('label[for="reminder_email"]').parent('div').addClass('warning');
			alert('Type a valid e-mail address');
			return false;
		}
		if(!$this.find('.reminder-item input:checked').size()) {
			alert('Choose at least one event');
			return false;
		}
		
		$this.addClass('processing');
		$.post(HOST + '/include/plugins/hbp/reminders/create.php', $this.find('input,select').serialize() + '&ajax=1', function(data){
			if(data == 'ok') {
				$this.removeClass('processing').html('<p>An email with the reminder activating link was sent to this address. If you do not receive the e-mail in up to 10 minutes, check spam folder first and then contact us</p>');
			}
		});
		return false;
	});
	
	
	/**
	 * Popup layer
	 
	if (($.cookie('wielkanoc_20_04_2011_EN') != 1) && ($('#popup-content').html().length > 10) && ($('.sOverlibDiv').size() < 1)) {
		$.cookie('wielkanoc_20_04_2011_EN', 1, {path: '/', expires: 7});
		$('#popup-content')
			.show()
			.before('<div id="overlay"></div>')
			.prepend('<a href="#close" class="close">x</a>')
			.find('.close')
			.click(function(){
				$('#popup-content').hide();
				$('#overlay').hide();
				return false;
			});
		$('#overlay')
			.css({height: $(document).height() + 'px', opacity: '0.6', zIndex: '950'})
			.click(function(){
				$('#popup-content').hide();
				$('#overlay').hide();
			});
	}*/
	
	/**
	* INWEST FLASH SHAREHOLDERS
	*/
	$('#shareholders-ani').append('<div id="flash-ani-shareholders"></div>');
	swfobject.embedSWF(HOST + '/pub/uploadflash/Pie3D.swf', 'flash-ani-shareholders', '310', '177', '9.0.0', HOST + '/pub/uploadflash/expressInstall.swf', {HP_host: HOST, dataURL: 'http://hbp-sa.pl/include/plugins/hbp/akcjonariatDataProvider.php'}, {wmode: 'transparent'});
	
	/*
		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');
				$('.zwz > li')
					.hide()
					.find('.date:contains("' + $(this).text() + '-")')
						.parent()
							.show()
				return false;
			})
			.filter(':first').click();
	}
	
	/*
		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', '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] + '%26FCTime=27%26forceeng=1'}, {});
	
	$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;
		}
	});
	
	$('#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();
	});
	
	/*
		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, 'flash-ani', '448', '264', '9.0.0', '', {dataURL: '/include/plugins/efresh/stockdata/files/hbp_chart_stock_' + flashDetect + '.xml'}, {});
	
	// 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=14#' + 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('#', ''));
	
	/*
	 * FlowPlayer active
	 */
	$('.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_en.f4v'
			],
			plugins: {
        controls: null
			}, 
			onBeforeFinish: function() { 
					return false; 
			} 
		});
	}
	
	/*
		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;
	});
	
});
