var Filmweb = {

	globals: {},

	start: function() {
		var root = this;
		jQuery('html').addClass('js');
		Artshow.start();
		root.showFullGallery();
	},

	isLoggedUser: function() {
		var logged = (jQuery.cookie('_artuser_sessionId') || jQuery.cookie('_artuser_rememberMe')) ? true : false;
		this.globals.logged = logged;
	},

	enhanceNavigation: function() {
		// executed from document
		jQuery('#navigation').removeClass('css-nav').addClass('js-nav');

		var $navTabs = jQuery('#tabs > li'),
				$navPanels = $navTabs.find('ul'),
				$navCurrent,
				overInterval,
				outInterval,
				resetClasses = function() {
					var item = (typeof arguments[0] != 'undefined') ? arguments[0] : -1;
					$navPanels.removeClass('current').eq(item).addClass('current');
					$navTabs.removeClass('current').eq(item).addClass('current');
				}

		$navTabs.each(function(i) {
			var $this = jQuery(this);
			$navCurrent = ($this.is('.current')) ? $this : $navCurrent;
			$this.bind('mouseover', i, function(e) {
				var self = this,
						i = e.data;
				clearTimeout(outInterval);
				overInterval = setTimeout(function() {
					resetClasses(i);
				}, 300)
			}).bind('mouseout', i, function(e) {
				var self = this,
						i = e.data;
				clearTimeout(overInterval);
				outInterval = setTimeout(function() {
					resetClasses();
					jQuery($navCurrent).addClass('current');
				}, 500)
			});
		});
	},
	
	enhanceFilmAnticipation: function(){
		var $filmAnticipation = jQuery('ul.film-anticipation'),
				$filmAnticipateItems = $filmAnticipation.find('li'),
				$anticipationCaption = $filmAnticipation.prev();
				filmId = 0;

				
		$filmAnticipateItems.each(function() {
		
			var $this = jQuery(this),
				$link = $this.find('a'),
				$prev = $this.prevAll().not('.anticipation-delete');
			
			if (this.className == 'anticipation-delete') {
					$link.bind('click', deleteAnticipation);
				} else {
					if (!filmId) {
						filmId = $link.attr('href').split('/')[2];
					}
					$link
						.bind('click', anticipateElement).hover(function() {
							$prev.addClass('hover')
						}, function() {
							$filmAnticipateItems.removeClass('hover');
						});
				}

				
			function removeAnticipationElements() {
				$filmAnticipation.find('li').filter(function() {
					if ((this.className == 'anticipation-delete') || (this.className == 'anticipation-rating')) {
						return this
					}
				}).remove();
			}
			
			function anticipateElement(e) {
				jQuery('#film-intro-loader').show();
				var self = this;
				jQuery.ajax({
					type: 'POST',
					data: {}, 
					cache: false,
					url: self.href,
					success: function() {
						$filmAnticipateItems.removeClass('anticipated');
						$prev.add($this).addClass('anticipated');
						removeAnticipationElements();
						var anticipation = $filmAnticipateItems.not('.anticipation-delete').index(self.parentNode) + 1;
						var $deleteButton = jQuery('<li class="anticipation-delete"><a href="/filmActions/' + filmId + '/setAnticipation/0">Kasuj</a></li>');
						$deleteButton.find('a').bind('click', deleteAnticipation).end().prependTo($filmAnticipation);
						text = $filmAnticipateItems.find('span')[anticipation - 1].innerHTML;
						$anticipationCaption.text(text.substring(0,text.length - 3));
						$filmAnticipation.append('<li class="anticipation-rating"><strong>' + anticipation + '</strong>/5</li>')
						jQuery('#film-intro-loader').hide();
						Filmweb.calculateAnticipationCounter(anticipation);
					}
				})
				e.preventDefault();
			}
			
			function deleteAnticipation(e) {
				jQuery('#film-intro-loader').show();
				var self = this;
				jQuery.ajax({
					type: 'POST',
					data: {}, 
					cache: false,
					url: this.href,
					success: function() {
						$filmAnticipateItems.removeClass('anticipated');
						removeAnticipationElements();
						var anticipation = $filmAnticipateItems.not('.anticipation-delete').index(self.parentNode) + 1;
						jQuery('#film-intro-loader').hide();
						Filmweb.calculateAnticipationCounter(0);
						$anticipationCaption.text('Jak bardzo chcę obejrzeć:');
					}
				})
				$filmAnticipateItems.removeClass('anticipated')
				e.preventDefault();
			}
		})
	},

	calculateAnticipationCounter: function(anticipation){
		if (anticipation == 0 && Filmweb.globals.filmUserAnticipation > 0){
			Filmweb.globals.filmCurrentAnticipation = Filmweb.globals.filmCurrentAnticipation - 1;
		} else if (Filmweb.globals.filmUserAnticipation == 0){
			Filmweb.globals.filmCurrentAnticipation++;
		}
		$anticipationHolder = jQuery('#filmAnticipationCount');
		if (Filmweb.globals.filmCurrentAnticipation == 0) {
			$anticipationHolder.hide();
		} else {
			$anticipationHolder.show();
		}
		var personFlex = '';
    	if ( Filmweb.globals.filmCurrentAnticipation == 1)
    	{
    		personFlex = Filmweb.globals.filmCurrentAnticipationPersons[0];
    	}
    	else if(Filmweb.globals.filmCurrentAnticipation == 0 || Filmweb.globals.filmCurrentAnticipation %10 <= 1 || Filmweb.globals.filmCurrentAnticipation % 10 >= 5)
    	{
    		personFlex = Filmweb.globals.filmCurrentAnticipationPersons[1];
    	}
    	else
    	{
    		personFlex = Filmweb.globals.filmCurrentAnticipationPersons[2];
    	}
	
		$anticipationHolder.find('span.value').empty().append( "<strong>"+Filmweb.globals.filmCurrentAnticipation+"</strong> " + personFlex );
		Filmweb.globals.filmUserAnticipation = anticipation;
	},

	enhanceFilmVoting: function() {
		var $filmRate = jQuery('ul.film-rate'),
				$filmRateItems = $filmRate.find('li'),
				$rateCaption = $filmRate.prev();
				filmId = 0;

		$filmRateItems.each(function() {

			var $this = jQuery(this),
					$link = $this.find('a'),
					$prev = $this.prevAll().not('.vote-delete');

			function removeVoteElements() {
				$filmRate.find('li').filter(function() {
					if ((this.className == 'vote-delete') || (this.className == 'vote-rating')) {
						return this
					}
				}).remove();
			}

			function clearAnticipationVisuals(){
				var $filmAnticipation = jQuery('ul.film-anticipation');
				$filmAnticipateItems = $filmAnticipation.find('li');
				if ($filmAnticipateItems.length == 0) {
					return;
				}
				$filmAnticipateItems.removeClass('anticipated');
				if ($filmAnticipateItems[0].className == 'anticipation-delete') {
					$filmAnticipateItems[0].hide();
				}
				if ($filmAnticipateItems[$filmAnticipateItems.length - 1].className == 'anticipation-rating') {
					$filmAnticipateItems[$filmAnticipateItems.length - 1].hide();
				}
				jQuery('ul.film-anticipation').prev().text('Jak bardzo chcę obejrzeć:');
			}			

			function voteElement(e) {
				jQuery('#film-intro-loader').show();
				var self = this;
				jQuery.ajax({
					type: 'POST',
					data: {},
					cache: false,
					url: self.href,
					success: function() {
						$filmRateItems.removeClass('voted');
						$prev.add($this).addClass('voted');
						removeVoteElements();
						var rate = $filmRateItems.not('.vote-delete').index(self.parentNode) + 1;
						if (Filmweb.globals.filmCurrentRate == 0) {
							if (Filmweb.globals.filmUserAnticipation > 0) {
								clearAnticipationVisuals();
								Filmweb.calculateAnticipationCounter(0);
							}
							jQuery('#anticipationHolder').hide();
						}
						if (Filmweb.globals.filmCurrentRate == 0) {
							jQuery('ul.film-favorite').show();
						}
						calculateVotes(rate);
						var $deleteButton = jQuery('<li class="vote-delete"><a href="/filmActions/' + filmId + '/vote/0">Kasuj</a></li>');
						$deleteButton.find('a').bind('click', deleteVote).end().prependTo($filmRate);
						text = $filmRateItems.find('span')[rate - 1].innerHTML;
						$rateCaption.text(text.substring(0,text.length-3));
						$filmRate.append('<li class="vote-rating"><strong>' + ($filmRateItems.not('.vote-delete').index(self.parentNode) + 1) + '</strong>/10</li>')
						jQuery('#film-intro-loader').hide();						
					}
				})
				e.preventDefault();
			}

			function deleteVote(e) {
				jQuery('#film-intro-loader').show();
				var self = this;
				jQuery.ajax({
					type: 'POST',
					data: {}, 
					cache: false,
					url: this.href,
					success: function() {
						$filmRateItems.removeClass('voted');
						removeVoteElements();
						var rate = $filmRateItems.not('.vote-delete').index(self.parentNode) + 1;
						calculateVotes(rate);
						$rateCaption.text('Zagłosuj:');
						jQuery('#anticipationHolder').show();
						jQuery('ul.film-favorite').hide();
						jQuery('#film-intro-loader').hide();
					}
				})
				$filmRateItems.removeClass('voted')
				e.preventDefault();
			}			

			function calculateVotes(rate) {
				Filmweb.globals.filmPreviousRate = Filmweb.globals.filmCurrentRate;				
				Filmweb.globals.filmCurrentRate = rate;								

				var
					previousRate = Filmweb.globals.filmPreviousRate,
					count = Number ( jQuery('.film-votes strong').text() ),
					sum = Filmweb.globals.filmCurrentVotesSum,
					previousSum = sum,
					previousCount = count;
				
				if(previousRate == 0) {
					count++;
				} else {
					sum = sum - previousRate;
				}
				if(rate == 0){
					count--;
				}
				jQuery('.film-votes strong').text(count);

				sum = sum + rate;
				Filmweb.globals.filmCurrentVotesSum = sum;
				if(count > 0)
				{
					var rating = (sum / count),
						r = rating.toFixed(2).toString();
	
					jQuery('.film-rating-fill').css('width', parseInt(sum / count * 11) + '%').find('strong').text(r.replace('.',','));
					jQuery('.film-rating .average-rate strong').text( Filmweb.globals.rateDictionary[ Math.round(r) ] );
					
					jQuery('.film-overal .film-rating .average-rate').show();
					jQuery('.film-overal .film-rating .film-rating-precise').show();
					jQuery('.film-overal .film-votes').show();
				}
				else
				{
					jQuery('.film-overal .film-rating .average-rate').hide();
					jQuery('.film-overal .film-rating .film-rating-precise').hide();
					jQuery('.film-overal .film-votes').hide();
				}
			}

			if (this.className == 'vote-delete') {
				$link.bind('click', deleteVote);
			} else {
				if (!filmId) {
					filmId = $link.attr('href').split('/')[2];
				}
				$link
					.bind('click', voteElement).hover(function() {
						$prev.addClass('hover')
					}, function() {
						$filmRateItems.removeClass('hover');
					});
			}
		})
	},

	appendLoader: function() {
		jQuery('#film-content div.film-intro').append('<div id="film-intro-loader"><p>Poczekaj moment/u0133</p></div>');
	},

	enhanceSetFavourite: function() {
		var $scope = jQuery('#film-content div.film-stats');
		var $list = $scope.find('.film-fav-list');
		var $loader = jQuery('#film-intro-loader');

		function addFav(e){
			$this = jQuery(this);
			$loader.show();
			var $url = '/filmActions/' + Filmweb.globals.filmId + '/addFavourite';
			jQuery.ajax({
				type: 'POST',
				url: $url,
				cache: false,
				data: {}, 
//				data: '&ieSucks=' + new Date().getTime(),
				success: function(){
					PerformGemiusHit;
					var $ulParent = $scope.find('ul.film-favorite');
					var del = $ulParent.find('.film-fav-del a');
					if($del.length==0){
						$ulParent.prepend('<li class="film-fav-del"><a href="#linkOther($user \'userFilmFavorites\')">usuń z ulubionych</a></li>');
						$ulParent.find('.film-fav-del a').bind('click',deleteFav);
					}else{
						$del.show();
					}
					$this.hide();
					$list.show();
					$loader.hide();
				},
				error: function(){$loader.hide();}
			});
			e.preventDefault();
		}

		function deleteFav(e) {
			$this = jQuery(this);
			$loader.show();
			$url = '/filmActions/' + Filmweb.globals.filmId + '/removeFavourite';
			jQuery.ajax({
				type: 'POST',
				url: $url,
				data: {}, 
				cache: false,
//				data: '&ieSucks=' + new Date().getTime(),
				success: function(){
					PerformGemiusHit;
					var $ulParent = $scope.find('ul.film-favorite');
					var $add = $ulParent.find('.film-fav-add a');
					if($add.length==0){
						$ulParent.prepend('<li class="film-fav-add"><a href="/AddFilmFavourite?film.id=' + Filmweb.globals.filmId + '" >dodaj do ulubionych</a></li>');
						$ulParent.find('.film-fav-add a').bind('click',addFav);
					}else{
						$add.show();
					}
					$this.hide();
					$list.hide();
					$loader.hide();
				},
				error: function(){$loader.hide();}
			});
			e.preventDefault();
		}

		var $add = $scope.find('.film-fav-add a');
		if ($add.length > 0) {
			$list.hide()
		}
		var $del = $scope.find('.film-fav-del a');
		if ( $add.attr('href') != "/Login")
			$add.bind('click', addFav);
		$del.bind('click', deleteFav);
	},

	shiftAdsPosition: function() {

	},

	filmRatingSwitch: function() {
		var root = this;
		this.isLoggedUser();
		if (this.globals.logged) {
			jQuery('.film-submit').html(jQuery('#film-intro-loader'));
			jQuery.ajax({
				type: 'GET',
				cache: false,
				url: '/parts/film/' + root.globals.filmId + '/userSpecific/new',
				success: function(response) {
					jQuery('.film-submit').replaceWith( jQuery(response) );
					root.enhanceFilmVoting();
					root.enhanceFilmAnticipation();
					root.enhanceSetFavourite();
				}
			});
		}
	},

	showFullGallery: function() {
		var root = this;

		jQuery('.artshow-incomplete').each(function() {

			var $this = jQuery(this),
					$firstRowThumbs = $this.find('a'),
					$showGallery = $this.next().filter('.film-more').find('a');

			function downloadGallery(e) {
				var launchArtshow = (typeof e.data == 'undefined') ? true : false,
						self = this;
				jQuery.ajax({
					url: '/parts/film/' + root.globals.filmId + '/gallery',
					method: 'GET',
					cache: false,
					success: function(response) {
						$this.append(response).removeClass('artshow-incomplete').addClass('artshow');
						$firstRowThumbs.add($showGallery).unbind('click');
						$showGallery.bind('click', function(e) {
							$firstRowThumbs.eq(0).click();
							e.preventDefault();
						});
						Artshow.start();
						if (launchArtshow) {
							jQuery(self).click();
						} else {
							$firstRowThumbs.eq(0).click();
						}
					}
				})
				e.preventDefault();
			}

			$firstRowThumbs.bind('click', downloadGallery);
			$showGallery.bind('click', true, downloadGallery);
		});


	}
}

jQuery(function() {
	Filmweb.start()
})
