/*
 * carousel
 * Author: Lukas Pesl
 * Version : 0.7 
 */

(function($){
	$.fn.extend({ 
		carousel: function(options) {
			var defaults = {
				maxAllowedSteps : {
				'1' : 2,
				'2' : 3,
				'3' : 3,
				'4' : 3,
				'5' : 4,
				'6' : 4,
				'7' : 5
				},
				maxSteps : 5,
				bannerUrl : 'http://ihned.cz/?m=hpbig',
				//bannerUrl : 'http://81.95.101.3/index.php?p=000000_hpbig',
				bannerHash : 'hp'
			};

				// http://81.95.101.3/index.php?p=0M0000_big
				// http://81.95.101.3/index.php?p=000000_big // http://ihned.cz/?m=big
			var options = $.extend(defaults, options);
			var selector = this.selector;
			
			var $this = this;
			var $categories = $(options.categories, this);
			var $categoriesBoxes = $('input', $categories);
			
			var $navigationLeft = $(options.navigationLeft, this);
			var $navigationRight = $(options.navigationRight, this);
			var $navigationSteps = $(options.navigationSteps, this);
			var $navigationStepsLinks = $('a', $navigationSteps);
			var $content = $('.content .page-content', this);
			
			var prevStep = 0;
			var actualStep = 0;
			var maxStep = null;
			var isBanner = [null, null, null, null, null];
			//var isBanner = [true, true, true, true, true];
			var selectedCategories = null;

			var buildSelectedCategories = function() {
				selectedCategories = ',';
				$categoriesBoxes.each(function(){
					var name = $(this).attr('name');
					if (!$(this).attr('checked')) return true;
					if (name != 'all')
					{
						selectedCategories += name + ',';
					} else
					{
						selectedCategories = 'all';
						return false;
					} 
				});
			}
			
			var preloadImages = function(data) {
				$.each(options.data, function(key, val){
					//var path = val.photoURL.toLowerCase().indexOf('http://') == -1 ? : val.photoURL;
					var im = new Image();
					im.src = val.photoURL; 
				});
			}
			
			var buildPages = function() {
				var html = '';
				for (var i=0; i<options.maxSteps; i++)
				{
					html += '<div class="page" id="page-' + i + '">';
					html += '<div class="item hp-item1" id="hp-item1-p' + i + '"></div>';
					html += '<div class="item hp-item2" id="hp-item2-p' + i + '"></div>';
					html += '<div class="item hp-item3" id="hp-item3-p' + i + '"></div>';
					html += '<div class="item hp-item4" id="hp-item4-p' + i + '"></div>';
					html += '<div class="item hp-item5" id="hp-item5-p' + i + '"></div>';
					html += '<div class="item hp-item6" id="hp-item6-p' + i + '"></div>';
					
					//var url = options.bannerUrl + '#' + options.bannerHash;
					var url = '';
					
					if (i == 0)
						html += '<div class="item banner"><span class="r-big-ozn">REKLAMA</span><iframe src="' + url + '" width="300" height="300" frameborder="0" scrolling="no"></iframe></div>';
					else
						html += '<div class="item banner"><span class="r-big-ozn">REKLAMA</span><iframe src="' + '" width="300" height="300" frameborder="0" scrolling="no"></iframe></div>';
					
					html += '</div>';
				}
				$content.html(html);
			}();
			
			var setPagesContent = function() {
				for (var i=0; i < options.maxSteps; i++)
				{
					setContent(1, i, options.viewingData[(i * 6)]);
					setContent(2, i, options.viewingData[(i * 6) + 1]);
					setContent(3, i, options.viewingData[(i * 6) + 2]);
					setContent(4, i, options.viewingData[(i * 6) + 3]);
					setContent(5, i, options.viewingData[(i * 6) + 4]);
					setContent(6, i, options.viewingData[(i * 6) + 5]);
				}
			}

			var setPageContent = function(step, emulateBanner) {
				var bannerCount = 0;
				for (var i=0; i < step; i++)
				{
					if (isBanner[i] || isBanner[i] == null) bannerCount++; 
				}
				var i = (step * 6) - bannerCount;
				
				setContent(1, step, options.viewingData[(i)]);
				setContent(2, step, options.viewingData[(i) + 1]);
				setContent(3, step, options.viewingData[(i) + 2]);
				setContent(4, step, options.viewingData[(i) + 3]);
				setContent(5, step, options.viewingData[(i) + 4]);
				if (isBanner[step] || emulateBanner)
					setContent(6, step, options.viewingData[(i) + 4]);
				else
					setContent(6, step, options.viewingData[(i) + 5]);
			}
			
			var buildViewingDataArray = function(byClick, forceFirstPage) {
				options.viewingData = [];
				buildSelectedCategories();
				var categoriesCount = $categories.find(':checked').length;
				
				var maxAllowedSteps = (selectedCategories == 'all' ? 5 : options.maxAllowedSteps[categoriesCount]);
				
				$.each(options.data, function(key, val){
					var k = key;
					if (selectedCategories == 'all' || selectedCategories.indexOf(',' + options.data[k].category + ',') != -1)
					{
						options.viewingData.push(options.data[k]);
						if (options.viewingData.length == (maxAllowedSteps * 6)) { return false };
					}
				});
				if (!byClick)
				{
					preloadImages(options.data);
				}
				setStepCount(Math.ceil(options.viewingData.length/6), byClick, forceFirstPage);
			}
			
			var buildContentHTML = function(data) {
				if (!data) return false;
				//var html =	'<a href="$moreURL$" class="name $category$">$categoryTitle$</a>' +
				var html =	'<a href="$moreURL$" class="name $category$"></a>' +
						'<a href="$articleURL$" class="image-link"><img src="$photoURL$" width="266" height="150" alt="" /></a>' +
						'<a href="$articleURL$" class="text">$text$</a>' +
						'<div class="author">$author$</div>' +
						'<div class="work-position">$workPosition$</div>' +
						'<a href="$moreURL$" class="more pngfix">více $moreTitle$</a>';
				$.each(data, function(key, val){
					html = html.replace(new RegExp('\\$' + key + '\\$', 'g'), val);
				});
				return html;
			}
			
			var setContent = function(index, step, data) {
				var $item = $(options.item + index + '-p' + step, $this);
				
				if (data && data.category == 'dialog')
					$item.addClass('dialog-item');
				else
					$item.removeClass('dialog-item');
				
				var html = buildContentHTML(data);
				
				if (html != '')
				{
					$item.html(html);
					$item.show();
				} else
				{
					$item.hide();
				}
			}

			var setStepCount = function(count, byClick, forceFirstPage) {
				maxStep = count - 1;
				var html = '';
				for (var i=0; i<count; i++)
				{
					html += '<a class="pngfix2" href=""></a>';
				}
				var size = (($navigationStepsLinks.width() + parseInt($navigationStepsLinks.css('marginLeft')) + parseInt($navigationStepsLinks.css('marginRight'))) * count) + 5;
				$navigationSteps.html(html).width(size).css('marginLeft', '-' + ((size / 2) - 7) + 'px');

				$navigationStepsLinks = $('a', $navigationSteps);
				if (count <= 1 && byClick)
				{
//alert('hidding');
//					$navigationLeft.hide();
//					$navigationRight.hide();
				} else
				{
					$navigationLeft.show();
					$navigationRight.show();
				}
				setPagesContent();
				if (forceFirstPage) setStep(0, byClick);
			}
			
			var setStep = function(step, byClick) {
				actualStep = step;
				if (byClick && isBanner[0] == null)
				{
					//var $banner = $(options.banner, $this);
					//isBanner[0] = $banner.css('display') == 'block' || $banner.css('display') == 'inline';
					buildViewingDataArray(byClick);
				}
				
				setPageContent(step, true);
				var clb = function(){
					var src = options.bannerUrl + '&rn=' + Math.random() + '#' + options.bannerHash; 
					
					$('.page-content IFRAME:eq(' + step + ')').unbind('load').bind('load', function(){
						if ($('embed, object, IMG, #bbContainer', this.contentWindow.document).length < 1)
						{
							isBanner[step] = false;
							$(this).parent().hide();
						} else {
							$(this).parent().show();
							isBanner[step] = true;
						}
						
						if (typeof pp_gemius_hit == 'function') pp_gemius_hit('za0wsmtZy1_ePfV8WLm.9maEP_11QO8mO4Eq3z6r__P.n7');
						
						//buildViewingDataArray(byClick);
						setPageContent(step);
					}).attr('src', src);
					
					$.cookie('hp-carousel-step', step);
				}
				
				$($navigationStepsLinks.removeClass('active').get(step)).addClass('active');
				var pageWidth = $('.page', $this).width();
				$content.animate({marginLeft: '-' + ( pageWidth * step ) + 'px'}, 300, 'swing', clb);
			}
			
			var loadCategoriesFromString = function(string, byClick, forceFirstPage) {
				if (string)
				{
					var checkArray = string.split(',');
					$categoriesBoxes.each(function(){ $(this).attr('checked', false); });
					$.each(checkArray, function(key, val){
						$categoriesBoxes.each(function(){
							var name = $(this).attr('name');
							if (name == val)
							{
								$(this).attr('checked', true);
								if (_gaq)
								{
									_gaq.push(['_trackEvent', 'HP-Carousel-Kategorie-Zaskrtnuto-Pri-Zobrazeni-Stranky', name, '']);
								}
							}
						});
					});
					buildViewingDataArray(byClick, forceFirstPage);
					return true;
				}
			}
			
			$categoriesBoxes.click(function(){
				var name = $(this).attr('name');
				
				if (Boolean($(this).attr('checked')) == true)
				{
					if (_gaq)
					{
						_gaq.push(['_trackEvent', 'HP-Carousel-Kategorie-Prave-Jsem-Zasrktl', name, '']);
					}
				}

				if ($categories.find(':checked').length == 0) $(this).attr('checked', true);
				
				if (name != 'all')
				{
					$categories.find('[name="all"]').attr('checked', false);
				} else
				{
					$categories.find('[name!="all"]').attr('checked', false);
				}

				if (typeof Custom != 'undefined') 
				{
				  Custom.clear();
				}
				
				if (isBanner[0] == null)
				{
					//var $banner = $(options.banner, $this);
					//isBanner[0] = $banner.css('display') == 'block' || $banner.css('display') == 'inline';
				}
				buildViewingDataArray(true, true);
				
				var checkNames = '';
				$categoriesBoxes.each(function(){ if ($(this).attr('checked')) { checkNames += $(this).attr('name') + ','; } });
				checkNames = checkNames.substr(0, checkNames.length-1);
				$.cookie('hp-carousel-categories', checkNames, {expires: 30});
			});

			$navigationLeft.click(function(){
				prevStep = actualStep; 
				if (actualStep == 0) actualStep = maxStep + 1; 
				setStep(--actualStep, true);
				return false; 
			});
			$navigationRight.click(function(){
				prevStep = actualStep; 
				if (actualStep == maxStep) actualStep = -1; 
				setStep(++actualStep, true);
				return false; 
			});
			$navigationStepsLinks.live('click', function(){
				prevStep = actualStep; 
				actualStep = $(this).index(); 
				setStep(actualStep, true);
				return false; 
			});

			var cookieStep = $.cookie('hp-carousel-step');
			var readingCookieStep = cookieStep && cookieStep != '0'; 
			
			if (!loadCategoriesFromString($.cookie('hp-carousel-categories'), false, !readingCookieStep)) 
				buildViewingDataArray(false, !readingCookieStep);
			
			if (readingCookieStep)
			{
				setStep(cookieStep);
			}
			
			return this;
		}
	});
})(jQuery);
