(function($) {
  var cache = [];
  $.preLoadImages = function() {
    var args_len = arguments.length;
    for (var i = args_len; i--;) {
      var cacheImage = document.createElement('img');
      cacheImage.src = arguments[i];
      cache.push(cacheImage);
    }
  }
})(jQuery)



readyImages = 0;
var albumLayout = {};
var currentImageData = {};
var ourWidth = 800;
var ourHeight = 600;
var slideShowOn = false;
var animation = false;


setupSlider = function(manual, startIndex) {
	var effect = albumData['Effect'];
	effect = effect.substring(0, 1).toLowerCase() + effect.replace(/ /ig, '').replace(/\+/ig, '').substring(1);
	if (effect == 'random') {
		$('#image_container').cycle({
			fx:'blindX,blindY,blindZ,cover,curtainX,curtainY,fade,fadeZoom,growX,growY,scrollUp,scrollDown,scrollLeft,scrollRight,scrollHorz,scrollVert,shuffle,slideX,slideY,toss,turnUp,turnDown,turnLeft,turnRight,uncover,wipe,zoom',
			randomizeEffects: true,
			speed: 300,
			timeout: manual ? 0 : 3000,
			startingSlide : startIndex ? startIndex : 0,
			after: onAfterSlideChange
		});
	} else {
		$('#image_container').cycle({
			fx: effect,
			randomizeEffects: true,
			speed: 300,
			timeout: manual ? 0 : 3000,
			startingSlide : startIndex ? startIndex : 0,
			after: onAfterSlideChange,
			before: onBeforeSlideChange
		});
	}
}

setRating = function () {
	var percent = 100 - 20 * currentImageData['rating'];
	$(albumLayout['rateStars']).css('background-position', percent + '% 0%');
	$(albumLayout['ratingText']).html(Math.round(currentImageData['rating']*100)/100);
}
startSlideShow = function() {
	$(albumLayout['slideshowStartButton']).css('display', 'none');
	$(albumLayout['slideshowStopButton']).css('display', 'block');
	slideShowOn = true;
	$('#image_container').cycle('destroy').empty();
	for (var i = 0; i < albumData.images.length; i++) {
		formatImage(i);
		albumData.images[i].__div.appendTo('#image_container');
	}
	setupSlider(false, currentImageData.__index);
}
onBeforeSlideChange = function() {
	animation = true;
	resetView(true);
}

onAfterSlideChange = function(curr,next,opts) {
	$('#image-num-of-num').empty();
	$('#image-num-of-num').html((currentImageData.__index + 1) + " of " + albumData.images.length);
	animation  = false;
	if (slideShowOn) {
		currentImageData = albumData.images[opts.currSlide];
		updateFlimStrip();
	}
}
stopSlideShow = function() {
	$(albumLayout['slideshowStopButton']).css('display', 'none');
	$(albumLayout['slideshowStartButton']).css('display', 'block');
	$('#image_container').cycle('destroy').empty();
	slideShowOn = false;
	formatImage(currentImageData.__index);
	albumData.images[currentImageData.__index].__div.appendTo('#image_container');
}
updateFlimStrip = function() {
	var startIndex = currentImageData.__index - 3;
	if (startIndex < 0) {
		startIndex = 0;
	}
	if (startIndex > (albumData.images.length - 8)) {
		startIndex = albumData.images.length - 8
	}
	for (var i = 0; i < albumData.images.length; i++) {
		if (i >= startIndex && i <= startIndex + 7) {
			albumData.images[i].__stripLink.css('display', 'inline');
		} else {
			albumData.images[i].__stripLink.css('display', 'none');
		}
		if (i == currentImageData.__index) {
			albumData.images[i].__stripLink.find(":nth-child(1)").addClass('viewing');
		//viewing
		} else {
			albumData.images[i].__stripLink.find(":nth-child(1)").removeClass('viewing');
		}
	}
	setRating();
	$(albumLayout['pictureTitle']).html(currentImageData.title);
	$(albumLayout['pictureDescr']).html(currentImageData.description);
	refreshCommentArea();
}
changePhoto = function(index) {
	stopSlideShow();
	if (index == currentImageData.__index || index < 0 || index == albumData.images.length) {
		return;
	}
	$('#image_container').cycle('destroy').empty();
	formatImage(currentImageData.__index);
	albumData.images[currentImageData.__index].__div.appendTo('#image_container');
	formatImage(index);
	albumData.images[index].__div.appendTo('#image_container');
	setupSlider(true);
	$('#image_container').cycle('next');
	currentImageData = albumData.images[index];
	updateFlimStrip();
}
formatImage = function(i) {
		_width = parseInt(albumData.images[i].dimensions[0]);
		paddingVert = 0;
		paddingHor = 0;
		_height = parseInt(albumData.images[i].dimensions[1]);
		albumData.images[i].__index = function(i){return i;}(i);
		if (_width > ourWidth || _height > ourHeight) {
			if (_width / ourWidth > _height / ourHeight) {
				_height *= ourWidth / _width;
				_width   = ourWidth;
			} else {
				_width  *= ourHeight / _height
				_height  = ourHeight;
			}
		}
		paddingVert = (ourHeight - _height) / 2;
		paddingHor = (ourWidth - _width) / 2
		var div = $('<div style="height: ' + ourHeight + '; width: ' + ourWidth + '; background-color: #676767; text-align: center;">' +
			'<div style="height: ' + paddingVert / (ourHeight + _height) * 100 + '% !important; font-size: 0;">&nbsp;</div>' + 
			'<img style="height : ' + _height / ourHeight * 100 + '%; width: ' + _width / ourWidth * 100 + '%;' + 
			//'<img style="height : 600px; width: 800px;' + 
			/*
			'margin-top : ' + paddingVert / (ourHeight + _height) * 100 + '% !important;' +
			'margin-bottom : ' + paddingVert / (ourHeight + _height) * 100 + '% !important;' +
			'margin-left : ' + paddingHor / (ourWidth + _width) * 100 + '% !important;' +
			'margin-right : ' + paddingHor / (ourWidth + _width) * 100 + '% !important;' + /**/
			/*'padding-top : ' + paddingVert / (ourHeight + _height) * 100 + '% !important;' +
			'padding-bottom : ' + paddingVert / (ourHeight + _height) * 100 + '% !important;' +
			'padding-left : ' + paddingHor / (ourWidth + _width) * 100 + '% !important;' +
			'padding-right : ' + paddingHor / (ourWidth + _width) * 100 + '% !important;' +/**/
			'" src="' + albumData.images[i].fullUrl + '" /></div>');
		albumData.images[i].__div = div;
		//var img = $(div).find(":nth-child(1)") 
		//img.css("height",         _height / ourHeight * 100 + "%");
		//img.css("width",          _width / ourWidth * 100 + "%");

		//div.css("height",         ourHeight + "px");
		//div.css("width",          ourWidth  + "px");

		//img.css("margin-top",    paddingVert / (ourHeight + _height) * 100 + "%");
		//img.css("margin-bottom", paddingVert / (ourHeight + _height) * 100 + "%");
		//img.css("margin-left",   paddingHor / (ourWidth + _width) * 100 + "%");
		//img.css("margin-right",  paddingHor / (ourWidth + _width) * 100 + "%");
		//div.css("background-color", "#676767");
}
initCommentForm = function() {
	$("#comment-form-submit").click(function() {
		var name = $("#comment-form-name").val();
		if (name == '') {
			alert("Please, enter your name");
			return false;
		}
		var nLen = encodeURIComponent(name).replace(/\%[0-9A-F]{2}/ig, '!').length;
		if (nLen > 32) {
			alert('Name you entered is too long. Maximum length is 32 symbols');
			return false;
		}
		var comment = $("#comment-form-text").val();
		if (comment == '') {
			alert("Please, enter comment text");
			return false;
		}
		var cLen = encodeURIComponent(comment).replace(/\%[0-9A-F]{2}/ig, '!').length;
		if (cLen > 512) {
			alert('Comment you entered is too long. Maximum length is 512 symbols');
			return false;
		}
		$.ajax({
			url: window.location.href,
			cache: false,
			type: 'POST',
			data: {nocache: '1', action: 'comment', photo_number: currentImageData['__index'], 'value[getXMLResponse]': true, 'value[name]': name, 'value[comment]': comment}, 
			success: function() {
				try {
					if (arguments[0].documentElement.getAttribute('isOk') == '1') { // everything is Ok.
						if (!currentImageData.comments) {
							currentImageData.comments = [];
						}
						var tmp = [];
						name = name.replace(/\<[^\>]+\>/gi, '');
						comment = comment.replace(/\<[^\>]+\>/gi, '');
						tmp[0] = {name: name, comment: comment};
						for (var i in albumData.images[currentImageData.__index].comments) {
							tmp[tmp.length] = albumData.images[currentImageData.__index].comments[i]
						}
						currentImageData.comments = albumData.images[currentImageData.__index].comments = tmp;
						refreshCommentArea();
					} else { //have error code
						alert(arguments[0].documentElement.textContent);
						return;
					}
				} catch (e) {}
			}
		});
		return false;
	});
}
ratePhoto = function(rating) {
	if (albumData.images[currentImageData.__index].photo_is_rated) {
		alert('You\'ve already rated this photo');
		return;
	}
	$.ajax({
		url: window.location.href,
		cache: false,
		type: 'POST',
		data: {nocache: '1', action: 'rating', photo_number: currentImageData['__index'], 'value[value]': rating, 'value[getXMLResponse]': true}, 
		success: function() {
			try {
				if (arguments[0].documentElement.getAttribute('isOk') == '1') { // everything is Ok.
					albumData.images[currentImageData.__index].rating = arguments[0].documentElement.firstChild.nodeValue;
					albumData.images[currentImageData.__index].rating_count++;
					currentImageData.rating = albumData.images[currentImageData.__index].rating;
					currentImageData.rating_count++;
					setRating();
					albumData.images[currentImageData.__index].photo_is_rated = true;
				} else { //have error code
					alert(arguments[0].documentElement.textContent);
					return;
				}
			} catch (e) {}
		}
	});
}
refreshCommentArea = function() {
	$(albumLayout['commentContainer']).empty();
	for (var i in currentImageData.comments) {
		var text = albumLayout['commentTemplate'].replace('%NAME%', currentImageData.comments[i].name).replace('%COMMENT%', currentImageData.comments[i].comment);
		$(text).appendTo(albumLayout['commentContainer']);
	}
}
var lastWidth = -1;
var lastHeight = -1;
viewportChanged = function() {
	var viewportwidth;
	var viewportheight;
	if (typeof window.innerWidth != 'undefined') {
		viewportwidth = window.innerWidth;
		viewportheight = window.innerHeight;
	} else if (typeof(document.documentElement) != 'undefined' &&
			typeof(document.documentElement.clientWidth) != 'undefined' &&
			document.documentElement.clientWidth != 0) {
		viewportwidth = document.documentElement.clientWidth;
		viewportheight = document.documentElement.clientHeight;
	} else {
		viewportwidth = document.getElementsByTagName('body')[0].clientWidth;
		viewportheight = document.getElementsByTagName('body')[0].clientHeight;
	}
	if (lastWidth < 0 && lastHeight < 0) {
		lastWidth = viewportwidth;
		lastHeight = viewportheight;
		return false;
	}
	if (lastWidth != viewportwidth || lastHeight != viewportheight) {
		lastWidth = viewportwidth;
		lastHeight = viewportheight;
		return true;
	}
	return false;
}

var linksBinded = false;
nextPhoto = function () {
	changePhoto(currentImageData.__index + 1);
	$(albumLayout['nextLinkText']).focus();
	return false;
}
previousPhoto = function() {
	changePhoto(currentImageData.__index - 1);
	$(albumLayout['nextLinkText']).focus();
	return false;
}
resetView = function(forse) {
	if ((!animation && viewportChanged()) || forse) {
		if ($('.pic_left') && $('.pic_left').detach) {
			$('.pic_left').detach();
		}
		if ($('.pic_right') && $('.pic_right').detach) {
			$('.pic_right').detach();
		}
		$('<div id="pic_left"><a href="#" class="previousLink" onclick="previousPhoto(); return false;"><img src="/files/usr/photoskins/javascript_viewer/images/e.gif" border=0 height="600px" width="120px" /></a></div>')
		.appendTo('#viewer_area');
		$('<div id="pic_right"><a href="#" class="nextLink" onclick="nextPhoto(); return false;"><img src="/files/usr/photoskins/javascript_viewer/images/e.gif" border=0 height="600px" width="120px" /></a></div>')
		.appendTo('#viewer_area');
		var tmp = document.getElementById('images_preview')
		var tmp2 = tmp.parentNode;
		tmp2.removeChild(tmp);
		tmp2.appendChild(tmp);
	}
	if ($.browser.msie) {
		setTimeout('resetView()', 200);
	}
}
$(document).ready(function() {
	albumLayout['img'] = '#mainImage'
	albumLayout['prevLink'] = '.previousLink';
	albumLayout['nextLink'] = '.nextLink';
	albumLayout['prevLinkText'] = '.previousLinkText';
	albumLayout['nextLinkText'] = '.nextLinkText';
	albumLayout['pictureTitle'] = '#pic_name';
	albumLayout['pictureDescr'] = '.pic_desc';
	albumLayout['ratingText'] = '#rating_container>strong';
	albumLayout['commentContainer'] = '#comm_block';
	albumLayout['slideshowStartButton'] = '#btn_start';
	albumLayout['slideshowStopButton'] = '#btn_stop';
	albumLayout['rateLinks'] = '#rating-stars>a';
	albumLayout['rateStars'] = '#rating-stars';
	
	
	albumLayout['filmStripTemplate'] = '<a href="#" onclick="return false;"><img src="%IMAGE_SRC%" style="width: 90px; height: 90px;" /></a>';
	albumLayout['commentTemplate'] = '<div class="comment"><span class="c_person">%NAME%</span><span class="c_text">%COMMENT%</span></div>';
	
	
	$(albumLayout['slideshowStartButton']).click(startSlideShow);
	$(albumLayout['slideshowStopButton']).click(stopSlideShow);
	
	$(albumLayout['rateLinks']).mouseover(function(){
		var linkNum = $(this).attr('href');
		var percent = 100 - 20 * linkNum;
		$(albumLayout['rateStars']).css('background-position', percent + '% 0%');
		resetView(true);
	});
	$(albumLayout['rateLinks']).mouseout(function(){
		setRating();
		resetView(true);
	});
	$(albumLayout['rateLinks']).click(function(){
		ratePhoto($(this).attr('href'));
	});
	$(albumLayout['prevLinkText']).click(function(){
		changePhoto(currentImageData.__index - 1);
	});
	$(albumLayout['nextLinkText']).click(function(){
		changePhoto(currentImageData.__index + 1);
	});
	
	//currentImageData['rating'] = '3.22';
	
	 //onmouseover="document.getElementById('stars').style.backgroundPosition='80%';"
	 //onmouseout="document.getElementById('stars').style.backgroundPosition='%RATING_PERCENT%';" 
	
	
	//return;
	//$('<div>start</div>').appendTo("#slider").click(function(){$('#slider').nivoSlider();});
	for (var i = 0; i < albumData.images.length; i++) {
		$.preLoadImages(albumData.images[i].fullUrl);
		var stripLink = false;
		if (albumData.images[i].thumbnail.indexOf('.') < 0) {
			stripLink = $(albumLayout['filmStripTemplate'].replace('%IMAGE_SRC%', albumData.images[i].fullUrl)).appendTo('#images_preview');
		} else {
			stripLink = $(albumLayout['filmStripTemplate'].replace('%IMAGE_SRC%', albumData.images[i].thumbnail)).appendTo('#images_preview');
		}
		albumData.images[i].__stripLink = stripLink;
		if (i > 7) {
			stripLink.css('display', 'none');
		}
		if (stripLink) {
			stripLink.click(function(i) {
				return function() {
					changePhoto(i);
				}
			}(i));
		}
	}
	formatImage(0);
	albumData.images[0].__div.appendTo('#image_container');
	currentImageData = albumData.images[0];
	setRating();
	updateFlimStrip();
	initCommentForm();/*
	//slideshowStartButton
	var offset = $('#thumb_area').offset();
	var left = offset.left;
	var top = offset.top;
	if ($.browser.msie) {
		left += 633;
		top += 130;
	} else {
		left += 660;
		top += 150;
	}
	$(albumLayout['slideshowStopButton']).offset({left: left, top: top});
	$(albumLayout['slideshowStartButton']).offset({left: left, top: top});*/
	resetView(true);
	$('#image-num-of-num').empty();
	$('#image-num-of-num').html((currentImageData.__index + 1) + " of " + albumData.images.length);
});

/*
window.onload = function() {
window.viewer = function() {
	this.selectImage = function(imageNum) {
		this.loadImage(albumData.images[imageNum]);
	}
	this.applyImageDimensions = function(width, height) {
		this.image.style.width = width;
		this.image.style.height = height;
	}
	this.loadImage = function(image) {
		_width = parseInt(image.dimensions[0]);
		_height = parseInt(image.dimensions[1]);
		width = '';
		height = '';
		if (_width > 800 || _height > 600) {
			if (_width > _height) {
				width = '800px';
				height = (800 * (_height / _width)) + 'px';
			} else {
				height = '600px';
				width = (600 * (_width / _height)) + 'px';
			}
		}
		this.image.setAttribute('src', image.fullUrl);
		this.image.setAttribute('onload', 'viewer.applyImageDimensions("' + width + '", "' + height + '");');
	}
	this.parent = document.getElementById('user_content');
	this.image = this.parent.appendChild(document.createElement('img'));
	this.loadImage(albumData.images[0]);
	this.imageList = this.parent.appendChild(document.createElement('div'));
	this.imageList.style.width = '100%';
	this.imageList.style.height = '90px';
	this.imageItems = [];
	for (var i = 0; i < albumData.images.length; i++) {
		this.imageItems[i] = this.imageList.appendChild(document.createElement('img'));
		this.imageItems[i].style.width = '90px';
		this.imageItems[i].style.height = '90px';
		this.imageItems[i].setAttribute('src', albumData.images[i].thumbnail);
		this.imageItems[i].setAttribute('onclick', 'viewer.selectImage(' + i + ');');
	}
	return this;
}();
};
*/
