﻿//dropdown menu

function initDropdown(){
	$('#change-link').click(function(){
		$('#dropdown').animate({opacity: 'toggle'}, 100);
		return false;
	});
}

//albums description popup

function initAlbumsPopup(){
	$("#leftcol ul.albums li").mousemove(function(e){
		$(this).find("div").show().css({
			left: e.pageX + 10 + "px",
			top: e.pageY - $("#header").height() + 18 + "px"
		});
	}).mouseout(function(){
		$(this).find("div").hide();
	})
}

//photo preview

function initCookie(type, value){
	if(type == 'preview'){
		if(value){
			$.cookie("previewSize", value, { path: '/', expires: 365 });
		} else {
			var previewSize = $.cookie("previewSize");
			if(!previewSize){
				previewSize = "middle";
			} 
			return previewSize
		}
	} else if(type == 'info'){
		if(value){
			$.cookie("info", value, { path: '/', expires: 365 });
		} else {
			var info = $.cookie("info");
			if(!info){
				info = "short";
			} 
			return info
		}
	}
}

function photoPreview(){
	//preview image size change

	$("#view a").click(function(){
		$("#view a").removeClass("active");
		$(this).addClass("active");
		
		if($("#view a.active").parent().hasClass("small")){
			$("#images li").css({
				width: 100 + "px",
				height: 114 + "px"
			});
			initCookie("preview", "small");
		} else if($("#view a.active").parent().hasClass("middle")){
			$("#images li").css({
				width: 146 + "px",
				height: 158 + "px"
			});
			initCookie("preview", "middle");
		} else if($("#view a.active").parent().hasClass("big")){
			$("#images li").css({
				width: 250 + "px",
				height: 264 + "px"
			});
			initCookie("preview", "big");
		}
		return false;
	});
	
	$("#view li").each(function(){
		if($(this).hasClass(initCookie("preview"))){
			$(this).find("a").click();
		}
	});
	
	//image description popup
	$("#images li").mousemove(function(e){
		$(this).find("div").show()
		.css({
			left: e.pageX + 10 + "px",
			top: e.pageY - $("#header").height() + 18 + "px"
		});
	})
	.mouseout(function(){
		$(this).find("div").hide();
	});
}

//image review

var firstTimeCall = true;

function imageReview(){
	
	//fucking Safari must die
	
	if ($.browser.safari){
		var scrollWidth = 0;
		if (firstTimeCall) {
			scrollWidth = 20;
		}
		if ($("body:first").hasClass("no-rightcol")){
			var childWidth = $(document).width() - 24 - scrollWidth;
		} else {
			var childWidth = $(document).width() - $("#rightcol").width() - 24 - scrollWidth;
		}
		firstTimeCall = false;
		$("#leftcol div.spacer:first").children("div").width(childWidth);
	}
	
	var imageRealHeight = parseInt($("#img_height").html());
	var imageRealWidth = parseInt($("#img_width").html());
	
	// get size of image block
	
	var imageBlockHeight = $(window).height()
	- $("#header").height()
	- $("#leftcol div.properties").outerHeight(true)
	- $("#description").outerHeight(true)
	- $("#manage-bar").outerHeight(true)
	- parseInt(($("#image").css("marginTop") == "auto") ? 0 : $("#image").css("marginTop"));
	var imageBlockWidth = $("#image").width();
	
	// load image
	
	$("#image img:first").css({
		width: "auto",
		height: "auto",
		marginTop: 0,
		marginBottom: 0
	});
	
	if((imageRealHeight > imageBlockHeight) || (imageRealWidth > imageBlockWidth)){
		var imageWidth = imageBlockHeight / imageRealHeight * imageRealWidth;
		var imageHeight = imageBlockHeight;
		var margin = 0;
		
		if(imageWidth > $("#image").width()){
			imageWidth = $("#image").width();
			imageHeight = imageRealHeight / imageRealWidth * imageWidth;
			margin = (imageBlockHeight - imageHeight) / 2;
			$("#image img:first").css({
				marginTop: margin,
				marginBottom: margin
			});
		}
		
		$("#image img:first").css({
			width: imageWidth,
			height: imageHeight
		});

		initBgLoad(imageWidth, imageHeight);
	} else {
		var margin = (imageBlockHeight - imageRealHeight) / 2;
		$("#image img:first").css({
			marginTop: margin,
			marginBottom: margin
		});
		initBgLoad(imageRealWidth,imageRealHeight);
	}
	
	// preloader
	
	if(!$("#image img:first").get(0).complete){
		$("#preloader").show();
	}
	$("#image img:first").load(function(){
		$("#preloader").hide();
	});
	
	// textarea width
	
	var widthAddComment = $("#image img:first").width();
	if(widthAddComment < 361){
		widthAddComment = 361
	}
	
	$("#add-comment").width(widthAddComment);
	$("#add-comment textarea").width(widthAddComment - 7);
	
	// arrows position
	
	$("#image div.previous, #image div.next").css({
		top: $("#review div.image-wrap").height() / 2
	});
}

//background load of image

function initBgLoad(imageWidth, imageHeight){
	
	var imageSrc = $("#image img:first").attr("src");

	if((imageWidth <= 500) || (imageHeight <= 500)){
		var pattern = /f600|f700|f800|f900|f1000/;
		imageSrc = imageSrc.replace(pattern,'f500');
	}
	if((imageWidth > 500 && imageWidth <= 600) || (imageHeight > 500 && imageHeight <= 600)){
		var pattern = /f500|f700|f800|f900|f1000/;
		imageSrc = imageSrc.replace(pattern,'f600');
	}
	if((imageWidth > 600 && imageWidth <= 700) || (imageHeight > 600 && imageHeight <= 700)){
		var pattern = /f500|f600|f800|f900|f1000/;
		imageSrc = imageSrc.replace(pattern,'f700');
	}
	if((imageWidth > 700 && imageWidth <= 800) || (imageHeight > 700 && imageHeight <= 800)){
		var pattern = /f500|f600|f700|f900|f1000/;
		imageSrc = imageSrc.replace(pattern,'f800');
	}
	if((imageWidth > 800 && imageWidth <= 900) || (imageHeight > 800 && imageHeight <= 900)){
		var pattern = /f500|f600|f700|f800|f1000/;
		imageSrc = imageSrc.replace(pattern,'f900');
	}
	if((imageWidth > 900) || (imageHeight > 900)){
		var pattern = /f500|f600|f700|f800|f900/;
		imageSrc = imageSrc.replace(pattern,'f1000');
	}
	
	$("#image img:first").attr("src", imageSrc);
}

//upload popup

function initPopup(){
	//load the form from the server
	$.ajax({
		url: "/webupload/get_form/",
		cache: false,
		ajaxSend: $("#upload span").show(),
 		success: function(data){
			$("#upload span").hide();
			
			$("#upload-popup").html(data);
			initFader();
			$("#upload-popup").show();
		
			$("#fader").click(function(){
				$("#fader").hide();
				$("#upload-popup").hide();
			});
			$("#close-popup").click(function(){
				$("#fader").hide();
				$("#upload-popup").hide();
			});

			selectAlbum();
			
			$("#link-select-album").click(function(){
				$("#create-album").hide();
				$("#select-album").show();
				selectAlbum();
			});
		
			$("#link-create-album").click(function(){
				$("#select-album").hide();
				$("#create-album").show();
				selectAlbum(true);
			});
			
			$("#select-album ul li").dblclick(function(){
				if ($(this).find("p.slug").html()){
					var url = "/webupload/upload/?album=" + $(this).find("p.slug").html();
					window.location = url;
				}
			});
			
			$("#submit-select-album").click(function(){
				if ($('li.active > p.slug').html()) {
					var url = "/webupload/upload/?album=" + $('li.active>p.slug').html();
					window.location = url;
				}
			});
		}
	});
}

//init album edit popup

function editAlbumPopup(album){
	//load the form from the server
	$.ajax({
		url: "/webupload/edit/"+album+"/",
		cache: false,
 		success: function(data){
			$("#upload-popup").html(data);
			initFader();
			$("#upload-popup").show();
			$("#create-album").show();
			$("#fader").click(function(){
				$("#fader").hide();
				$("#upload-popup").hide()
			});
			$("#close-popup").click(function(){
				$("#fader").hide();
				$("#upload-popup").hide()
			});
		}
	});
}

function initFader(){
	if($("#fader").is(":hidden")){
		$("#fader").show();
		$("#fader").css({
			width: $(document).width(),
			height: $(document).height()
		});
	} else {
		if($("#upload-popup").get(0)){
			$("#upload-popup").before("<div id='fader'>&nbsp;</div>");
		} else {
			$("#login-popup").before("<div id='fader'>&nbsp;</div>");
		}
		$("#fader").css({
			position: "absolute",
			left: 0,
			top: 0,
			width: $(document).width(),
			height: $(document).height(),
			background: "#000",
			opacity: 0.5
		});
	}
}

//select album

function selectAlbum(listWidth){
	//scroll fix
	if (!listWidth){
		var scrollContainer  = $("#select-album div").height();
		var albumListHeight = $("#select-album ul").innerHeight();
		var albumListWidth = $("#select-album ul").width();
		if(albumListHeight < scrollContainer){
			$("#select-album ul").width(albumListWidth + 16)
		}
	} else {
		$("#select-album ul").width(560)
	}
	//hover effect
	$("#select-album li").mouseover(function(){
		$(this).addClass("hover");
	});
	$("#select-album li").mouseout(function(){
		$(this).removeClass("hover");
	});
	//select
	$("#select-album li").click(function(){
		$("#select-album li").removeClass("active");
		$(this).addClass("active");
	});
}

//launch onload

$(document).ready(function(){
	if($('#change').is(":visible")){
		initDropdown();
	}
	if($('#images').is(":visible")){
		photoPreview();
	}
	if($('#image').is(":visible")){
		imageReview();
	}
	initEventListeners();
});

//launch onresize

$(window).resize(function(){
	if($('#image').is(":visible")){
		imageReview();
	}
});

//launch event listeners

function initEventListeners(){
	$("#upload").click(function(){
		initPopup();
		return false
	});
	$("#link-select-album").click(function(){
		$("#create-album").hide();
		$("#select-album").show();
		selectAlbum();
	});
	$("#link-create-album").click(function(){
		$("#select-album").hide();
		$("#create-album").show();
	});
	$("#change_caption").click(function(){
		$("#caption_edit").show();
	});
	togglePhotoInfo();
	$("#desc_change").click(function(){
		addImageDescr();
	});
	$("#desc_add").click(function(){
		addImageDescr();
	});
	$("#desc_remove").click(function(){
		removeImageDescr();
	});

	initLoginPopup();
	initAlbumsPopup();
}

//toggle photo info

function togglePhotoInfo(){
	var info = initCookie("info");
	$("#rightcol div.info ul").addClass(info);
	
	function toggleLinkContent(){
		if($("#rightcol div.info ul").hasClass("full")){
			$("#toggle-photoinfo").html("краткая информация");
		} else {
			$("#toggle-photoinfo").html("полная информация");
		}
	}
	
	toggleLinkContent();
	
	$("#toggle-photoinfo").click(function(){
		$("#rightcol div.info ul").toggleClass("full");
		toggleLinkContent();
		if($("#rightcol div.info ul").hasClass("full")){
			initCookie("info", "full");
		} else {
			initCookie("info", "short");
		}
		return false;
	});
}

//add image description

function addImageDescr(){
	var description = $("#description p").html();
	var photo = $("#photo_id").val();
	
	if (description == '&nbsp;') {
		description = '';
	}
	
	$("#description p").hide();
	$("#description a").hide();
	$("#description form").show();
	$("#description-text").val(description);
	imageReview();
	
	$("#description form input[@type=reset]").click(function(){
		if (description == '') {
			$("#desc_add").show();
		} else {
			$("#desc_change").show();
			$("#desc_remove").show();
		}
		$("#description p").show();
		$("#description form").hide();
		imageReview();
	});
	
	$("#add-description-button").click(function(){
		var new_description = jQuery.trim($("#description-text").val());
		$.post('/manage/', {'action': 'set-caption', 'photo': photo, 'caption': new_description},
			function(data){
				if (data == 'success') {
					$("#description p").html(new_description);
				}
				$("#description p").show();
				if (new_description == '') {
					$("#desc_add").show();
				} else {
					$("#desc_change").show();
					$("#desc_remove").show();
				}
				$("#description form").hide();
				imageReview();
			});
	})
}

function removeImageDescr() {
	var photo = $("#photo_id").val();
	$.post('/manage/', {'action': 'set-caption', 'photo': photo, 'caption': ''},
		function(data){
			if (data == 'success') {
				$("#description p").html('');
			}
			$("#description p").show();
			$("#description a").hide();
			$("#desc_add").show();
			$("#description form").hide();
			imageReview();
		});
}

//login popup

function initLoginPopup(){
	$("#login").click(function(){
		initFader();
		if(!$("#login_form").length){
			$.ajax({
				url: "/accounts/get_login_form/",
				cache: false,
				success: function(data) {
					var startHtml = $("#login-popup div.background").html();
					$("#login-popup div.background").html(data + startHtml);
					initLocalEvents();
				}
			});
		}
		$("#login-popup").show();
		
		function initLocalEvents(){
			$("#fader").click(function(){
				$("#login-popup").hide();
				$("#fader").hide();
			});
			
			$("#close-login").click(function(){
				$("#login-popup").hide();
				$("#fader").hide();
			});
		}
		return false
	});
}

var toggleRightcol = {
	options: {
		rightcol: "#rightcol",
		toggleBtn: "#toggle-rightcol",
		cookieName: "isRightcol",
		cookieOptions: {
			expires: 7,
			path: "/"
		}
	},
	setStartPosition: function(){
		var self = this;
		var cookie = $.cookie(self.options.cookieName);
		if (cookie == "false"){
			self.body.addClass("no-rightcol");
		}
	},
	openRightcol: function(){
		var self = this;
		self.body.removeClass("no-rightcol");
		
		if ($.browser.safari) 
			imageReview();
		$.cookie(self.options.cookieName, "true", self.options.cookieOptions);
	},
	closeRightcol: function(){
		var self = this;
		self.body.addClass("no-rightcol");
		
		if ($.browser.safari) 
			imageReview();
		$.cookie(self.options.cookieName, "false", self.options.cookieOptions);
	},
	addEvent: function(){
		var self = this;
		self.toggleBtn.click(
			function(){
				if (self.body.hasClass("no-rightcol")){
					self.openRightcol();
				} else {
					self.closeRightcol();
				}
				return false;
			}
		);
	},
	init: function(){
		var self = this;
		self["body"] = $("body").eq(0);
		self["rightcol"] = $(self.options.rightcol);
		self["toggleBtn"] = $(self.options.toggleBtn);
		
		if (self.body.length && self.rightcol.length && self.toggleBtn.length) {
			self.setStartPosition();
			self.addEvent();
		}
	}
}

var captionsForm = {
	options: {
		parent: "#captions_form",
		checkboxes: "input[type=checkbox]",
		selectAllBtn : "input.selectall"
	},
	addEvent: function(){
		var self = this;
		self.selectAllBtn.click(
			function(){
				self.checkboxes.attr("checked", "checked");
			}
		);
	},
	init: function(){
		var self = this;
		self["parent"] = $(self.options.parent);
		self["checkboxes"] = $(self.options.checkboxes, self.parent)
		self["selectAllBtn"] = $(self.options.selectAllBtn, self.parent)
		
		self.addEvent();
	}
}

$(function(){
	toggleRightcol.init();
	captionsForm.init();
});
