﻿function WebApp() {
	this.isIE = navigator.userAgent.indexOf(' MSIE ') > -1;
	this.isFirefox = navigator.userAgent.indexOf(' Firefox/') > -1 || (navigator.userAgent.indexOf(' MSI') > -1 && navigator.userAgent.indexOf(' MSIE ') == -1);
	this.isSafari = navigator.userAgent.indexOf(' Safari/') > -1;

	this._isLocalHost = function() { return location.hostname.indexOf('localhost') != -1; } ();
	this.Root = location.pathname;

	this._msgDeny = function() { return 'Раздел находится в стадии разработки!'; } ();
	this._bhvFeedbackID = 'bhvFeedback';
	this._bhvAuthID = 'bhvAuth';

	this._redirectTo = function(url) { location.href = url; }

	this._tbSearchID = 'tbSearchText';
	this._search = function() {
		var _defaultText = 'Поиск';
		var _tbSearch = $get(App._tbSearchID);
		var _searchText = trim(_tbSearch.value);
		var _searchUrl = __root + 'Pages/Public/Search.aspx?p=' + _searchText + "&host=" + location.pathname;
		if (_searchText == _defaultText) return false;
		if (_searchText != '') App._redirectTo(_searchUrl);
		else _tbSearch.focus();
	}

	this._isKeyPressed = function() { return event.which || event.keyCode; }
	this._isEnterPressed = function() {
		if (this._isKeyPressed()) { return event.which == 13 || event.keyCode == 13; }
	}
	this._isEscPressed = function() {
		if (this._isKeyPressed()) { return event.which == 27 || event.keyCode == 27; }
	}

	this._listenSearch = function() {
		if (this._isEnterPressed()) { this._search(); return false; }
	}
	this._focusSearch = function() {
		var _tbSearch = $get(App._tbSearchID);
		if (_tbSearch.value == 'Поиск') _tbSearch.value = '';
	}
	this._blurSearch = function() {
		var _tbSearch = $get(App._tbSearchID);
		if (!_tbSearch.value) _tbSearch.value = 'Поиск';
	}

	this._showMessage = function(msg) { alert(msg); }
	this._underDevelopment = function() { alert(App._msgDeny); }

	this._callModalWindow = function(behaviourID, toOpen) {
		var modalPopupBehavior = $find(behaviourID);
		if (toOpen) modalPopupBehavior.show();
		else modalPopupBehavior.hide();
	}
	this._callFeedback = function() {
		App._callModalWindow(App._bhvFeedbackID, true);
	}
	this._hideFeedback = function() {
		App._callModalWindow(App._bhvFeedbackID, false);
	}
	this._callAuth = function() {
		App._callModalWindow(App._bhvAuthID, true);
	}
	this._hideAuth = function() {
		App._callModalWindow(App._bhvAuthID, false);
	}
}

function PhotoGalleryManager() {
	this.IDs = new Array();
	this.Captions = new Array();
	this.Widths = new Array();
	this.Heights = new Array();
	this.Likes = new Array();
	this.Votes = new Array();

	this._elImageID;
	this._elCaptionID;
	this._elRatingID;
	this._elVoteID;

	this._isAuthentificated;
	this._userID;

	this.panelState;
	this._animating;

	this.Init = function(imgID, captionID, ratingID, voteID, isAuth) {
		this._elImageID = imgID;
		this._elCaptionID = captionID;
		this._elRatingID = ratingID;
		this._elVoteID = voteID;
		this._isAuthentificated = isAuth;

		this.initSliding();
		this.initCloseHover();
		this.catchEsc();
	}

	this.getImage = function() {
		if ($('#' + this._elImageID)) return $('#' + this._elImageID)[0];
		else return document.getElementById(this._elImageID);
	}

	this.getCaption = function() {
		if ($('#' + this._elCaptionID)) return $('#' + this._elCaptionID)[0];
		else return document.getElementById(this._elCaptionID);
	}

	this.getRating = function() {
		if ($('#' + this._elRatingID)) return $('#' + this._elRatingID)[0];
		else return document.getElementById(this._elRatingID);
	}

	this.getVote = function() {
		if ('#' + $(this._elVoteID)) return $('#' + this._elVoteID)[0];
		else return document.getElementById(this._elVoteID);
	}

	this.calculateSize = function(img) {
		if (this.panelState == "dock") {
			img.height = Math.min($(window).height() - 90, this.Heights[img.index]);
			//			img.width = Math.round(this.Widths[img.index] * img.height / this.Heights[img.index]);
		}
		else {
			img.height = Math.min($(window).height() - 17, this.Heights[img.index]);
			//img.width = Math.round(this.Widths[img.index] * img.height / this.Heights[img.index]);
		}
	}

	this.fitThumbnailPhoto = function(sender) {
		return;
		if (sender.height > sender.width) {
			sender.height = 200;
		}
		else {
			sender.width = 200;
		}
		//sender.style.visibility = 'visible';
	}

	this.updateIndexes = function(idx) {
		var _length = this.IDs.length;
		this.currentPhotoIndex = idx;
		if (idx < _length - 1)
			this.nextPhotoIndex = idx + 1;
		else this.nextPhotoIndex = 0;

		if (idx > 0)
			this.previousPhotoIndex = idx - 1;
		else this.previousPhotoIndex = _length - 1;
	}

	this.updateVote = function(idx) {
		var Photo_id = parseInt(this.getImage().src.split('=')[1]);
		PhotoService.Vote(this._userID, Photo_id, onSuccess, onFailed);
	}

	function onSuccess(result) {
		if (result != 1) return;
		idx = this.PhotoManager.currentPhotoIndex;
		this.PhotoManager.Likes[idx] = true;
		this.PhotoManager.Votes[idx] = this.PhotoManager.Votes[idx] + 1;
		this.PhotoManager.setVote(idx);
		this.PhotoManager.setRating(idx);
	}

	function onFailed(error) {
	}

	this.setCaption = function(idx) {
		this.getCaption().innerHTML = this.Captions[idx];
	}

	this.setVote = function(idx) {
		if (this._isAuthentificated) {
			if (this.Likes[idx]) {
				$('.post-like-wrapper a').html('<span class="post-like-hover"></span>Мне понравилось');
				$('.post-like-wrapper a').css({ 'cursor': 'default' });
				$('.post-like-wrapper a').unbind().click(function() { return false; });
			}
			else {
				$('.post-like-wrapper a').html('<span class="post-like"></span>Мне нравится');
				$('.post-like-wrapper a').css({ 'cursor': 'pointer' });
				$('.post-like-wrapper a').unbind().click(function() { PhotoManager.updateVote(); });
			}
		}
		else {
			$('.post-like-wrapper a').html('<span class="post-like"></span>Мне нравится');
			$('.post-like-wrapper a').css({ 'cursor': 'pointer' });
			$('.post-like-wrapper a').unbind().click(function() { App._callAuth(); });
		}
	}

	this.setRating = function(idx) {
		var Photo_id = parseInt(this.getImage().src.split('=')[1]);
		this.getRating().innerText = '+' + parseInt(this.Votes[idx]);
		if (this.Votes[idx] > 0)
			$('.photo-gallery-thumbnail-caption .img' + Photo_id)[0].innerText = '(+' + parseInt(this.Votes[idx]) + ')';
	}

	this.setVK = function() {
		var eTitle = encodeURI("Виртуальная художественная галерея пермского образования");
		var eDescription = encodeURI(this.Captions[this.currentPhotoIndex]);
		$('#vkAnchor')[0].href = "http://vkontakte.ru/share.php?url=" + location.href + "&title=" + eTitle + "&description=" + eDescription + "&image=" + this.getImage().src;
	}

	this.currentPhotoIndex = 0;
	this.nextPhotoIndex = 0;
	this.previousPhotoIndex = 0;

	this.displayPhoto = function(idx) {
		var img = this.getImage();
		img.index = idx;
		img.src = this.IDs[idx];
		img.onclick = function() { PhotoManager.displayNext() };

		this.updateIndexes(idx);

		img.onload = function() {
			PhotoManager.calculateSize(img);
		}
		PhotoManager.setCaption(idx);
		PhotoManager.setVote(idx);
		PhotoManager.setRating(idx);
		PhotoManager.setVK();

		this.cacheSiblingsImages();
	}

	this.displayNext = function() {
		this.displayPhoto(this.nextPhotoIndex);
	}

	this.displayPrevious = function() {
		this.displayPhoto(this.previousPhotoIndex);
	}

	this.cacheSiblingsImages = function() {
		var prevImg = new Image(1,1);
		prevImg.src = this.IDs[this.previousPhotoIndex];
		$('#prevImg').src = this.IDs[this.previousPhotoIndex];
		var nextImg = new Image(1,1);
		nextImg.src = this.IDs[this.nextPhotoIndex];
		$('#nextImg').src = this.IDs[this.nextPhotoIndex];
	}

	this.animatePanels = function(sender) {
		if (this.panelState == "dock") {
			$('.photo-viewer-header').animate({ 'top': '-35px' }, 500);
			$('.photo-viewer-footer').animate({ 'bottom': '-35px' }, 500, function() {
				PhotoManager.calculateSize(PhotoManager.getImage());
			});
			this.panelState = "float";
			sender.className = "photo-viewer-cliper-float";
		}
		else {
			$('.photo-viewer-header').animate({ 'top': '0px' }, 500);
			$('.photo-viewer-footer').animate({ 'bottom': '0px' }, 500, function() {
				PhotoManager.calculateSize(PhotoManager.getImage());
			});
			this.panelState = "dock";
			sender.className = "photo-viewer-cliper-dock";
		}
	}

	this.initSliding = function() {
		this.panelState = "dock";
		$('.photo-viewer-header, .photo-viewer-footer').mouseover(function() { PhotoManager.slidePanels('over') });
		$('.photo-viewer-header, .photo-viewer-footer').mouseout(function() { PhotoManager.slidePanels('out') });

		$('.photo-viewer-cliper-float, .photo-viewer-header-close, .photo-viewer-left, .photo-viewer-right, .photo-viewer-footer span.info').mouseover(
			function() { PhotoManager.stopSliding(); })
		$('.photo-viewer-container').mouseover(function() { PhotoManager._animating = 'off'; });
	}

	this.slidePanels = function(state) {
		if (this.panelState == "dock") return;
		if (PhotoManager._animating == "on") return;

		if (state == "over") {
			PhotoManager._animating = "on";
			$('.photo-viewer-header').animate({ 'top': '0px' }, 300);
			$('.photo-viewer-footer').animate({ 'bottom': '0px' }, 300, function() { PhotoManager._animating = "off"; });
		}
		else if (state == "out") {
			PhotoManager._animating = "on";
			$('.photo-viewer-header').animate({ 'top': '-35px' }, 300);
			$('.photo-viewer-footer').animate({ 'bottom': '-35px' }, 300, function() { PhotoManager._animating = "off"; });
		}
	}

	this.stopSliding = function() {
		if (PhotoManager.panelState == 'dock') return;
		$('.photo-viewer-header, .photo-viewer-footer').stop();
		PhotoManager._animating = "off";
	}

	this.catchEsc = function() {
		document.onkeydown = function() { if (App._isEscPressed()) PhotoManager.Close(); }
	}

	this.initCloseHover = function() {
		$('.photo-viewer-header-close').mouseover(function() {
			//if ($(this)[0].className == 'photo-gallery-header-close-hover') return;
			$(this)[0].className = 'photo-viewer-header-close-hover';
			$('.photo-viewer-header-close-text').fadeIn("fast");
		});
		$('.photo-viewer-header-close-text').mouseout(function() {
			if ($('.photo-viewer-header-close-hover')[0])
				$('.photo-viewer-header-close-hover')[0].className = 'photo-viewer-header-close';
			$(this).fadeOut("fast");
		});
		$('.photo-viewer-container').mouseover(function() {
			if ($('.photo-viewer-header-close-hover')[0])
				$('.photo-viewer-header-close-hover')[0].className = 'photo-viewer-header-close';
			$('.photo-viewer-header-close-text').fadeOut("fast");
		});
	}

	this._bhv = function() { return $find('bhvPhotoGallery'); }

	this.Show = function() { App._callModalWindow('bhvPhotoGallery', true); }
	this.Close = function() {
		$('.photo-viewer-header-close-text').css('display', 'none');
		if ($('.photo-viewer-header-close-hover')[0])
			$('.photo-viewer-header-close-hover')[0].className = 'photo-viewer-header-close';
		App._callModalWindow('bhvPhotoGallery', false);
	}
}

var App = new WebApp();
var PhotoManager = new PhotoGalleryManager();
