/**
 * @author Egloo
 */

var _conf = {};
_conf.currentUser = null;

var _vars = {};
_vars.userId = null;
_vars.sectionContainer = null;
_vars.currentPage = null;

var currentHash = null;

var tmpl = {};
tmpl.section = null;
tmpl.sectionBody = null;

var _pageData = null;


function renderSectionStruct() {
	var allImages = $("img", _vars.sectionContainer);
	$.each(allImages, function(i) {
		$(allImages[i]).get(0).src = null;
		$(allImages[i]).removeAttr("src");
		$(allImages[i]).remove();
	});
	_vars.sectionContainer.empty();
	
	tmpl.section = $("#section").clone();
	tmpl.sectionBody = $("#albumBody").clone();
	$(tmpl.sectionBody).insertAfter($("#albumHeader", tmpl.section));
	$(tmpl.sectionBody).css("visibility", "visible");
	$(tmpl.sectionBody).show();
	
	if(_pageData) {
		$(_pageData).map(function(i) {
			var section = $(tmpl.section).clone();
			$(section).appendTo($(_vars.sectionContainer));
			renderSection(i);
		});
	}
	
	tmpl.section = null;
	$(">#section", _vars.sectionContainer).removeAttr("style");
}

function renderSection(sectionIndex) {
	var section = $(">#section", _vars.sectionContainer)[sectionIndex];
	$(section).attr("albumId", _pageData[sectionIndex].albumId);
	if(_pageData[sectionIndex].author == _conf.currentUser) {
		$("#post-tattle", section).remove();
	} else {
		$("#post-tattle", section).attr("albumId", _pageData[sectionIndex].albumId);
		$("#breadCrumbs", section).attr("albumId", _pageData[sectionIndex].albumId);
		
		$("#post-tattle", section).bind("click", function() {
			if(confirm("Вы действительно желаете пожаловаться на этот альбом?")) {
				var parentCont = $(this).parents("div[albumId=" + $(this).attr("albumId") + "]");
				
				$(this).fadeOut("fast", function() {
					$("#post-tattle-indicator", parentCont).fadeIn("fast");
				});
				
				params = {};
				params["rtype"] = "album";
				params["targetId"] = $(this).attr("albumId");
				params["title"] = "BlaBlaBla";
				params["func"] = "anotherSlanderPublished-" + $(this).attr("albumId");
				zwsGetJSON("ReportAbuseServlet", buildJsonpRequest(params, true), ZWS_CallbackHandler);
			}
			
			return false;
		});
	}

	$("#albumTitle", section).text(_pageData[sectionIndex].albumTitle);
	$("#albumTitle", section).get(0).href = "album-view.html#aid=" + _pageData[sectionIndex].albumId;
	$("#albIdBg" , section ).get(0).href = "album-view.html#aid=" + _pageData[sectionIndex].albumId;
	$("#author", section).text(_pageData[sectionIndex].author);
	//$("#author", section).get(0).href = 
		//"/album-list.html#uid=" + _pageData[sectionIndex].authorId;
	$("#descr", section).text(_pageData[sectionIndex].descr);

	$("#dateCreated", section).text(getReadableDate(_pageData[sectionIndex].dateCreated, true));
	$("#dateModified", section).text(getReadableDate(_pageData[sectionIndex].dateModified, true));

	if(_pageData[sectionIndex].avatar.status == 200) {
		$("#avatar", section).css("background", "url(" + _pageData[sectionIndex].avatar.url + ") no-repeat center");
	} else {
		$("#avatar", section).css("background", "url(img/no_avatar.gif) no-repeat center");
	}
		
	renderPhotos(sectionIndex);
}

function renderPhotos(sectionIndex) {
	// Get all album photos
	var params = {};
	params["userId"] = "2008091808353055276348";
	params["albumId"] = _pageData[sectionIndex].albumId;
	params["func"] = "setSectionPhotos-" + String(sectionIndex);
	zwsGetJSON("ListPhotosByUserAndAlbumServlet", buildJsonpRequest(params, true), ZWS_CallbackHandler);
}

function hashCheck() {
	initPage();
}

function _thumbClickHandler() {
	window.location = "photo-view.html#pid=" + $(this).attr("photoId");
}

function ZWS_CallbackHandler(func, resp) {
	var re = /^([^-]*)-(.*)$/;
	if(re.test(func)) {
		eval(func.replace(re, "$1('$2', resp)"));
	} else {
		eval(func + "(resp)");
	}
}

function setAllAlbums(resp) {
	$(".pager").trigger("indicator", [false]);
	if(!_vars.currentPage) {
		_vars.currentPage = 1;
		$($(".pager")[0]).pager({changePageCallback : pageChanged, totalItems : resp.total, syncPagers : [$(".pager")[1]]});
		$($(".pager")[1]).pager({changePageCallback : pageChanged, totalItems : resp.total, syncPagers : [$(".pager")[0]]});
		
		$("#tagCloud").removeClass("hide");
	}

	if(resp.data.length > 0) {
		$("span#userName").text("пользователя " + resp.data[0].author);
	}
	
	_pageData = null;
	_pageData = resp.data;
	renderSectionStruct();
}

function setSignedUrl(modData, photoUrl) {
	var modArr = modData.split(";");
	var sectionIndex = parseInt(modArr[0]);
	var photoId = modArr[1];
	var section = $(">#section", _vars.sectionContainer)[sectionIndex];
	
	$("#photos", section).trigger("setSignedUrl", [photoId, photoUrl]);
}

function setSectionPhotos(sectionIndex, data) {
	var section = $(">#section", _vars.sectionContainer)[sectionIndex];
	$("#photo-count-indicator", section).addClass("hide");
	$("#photo-count-pane", section).removeClass("hide");
	
	if(data.length > 0) {
		
		
		data.sort(ascPhotosSortHandle);
		$("#count", section).text(data.length);
		$("#date-modified", section).text(getReadableDate(data.dateModified, true));
									
		if(data.length > 0) {
			$("#albumLeftImage", section).css("background", "url(" + data[0].url + ") no-repeat center");
			
			if(data.length > 1) {
				$("#albumRightImage", section).css("background", "url(" + data[1].url + ") no-repeat center");
			}
		}
	}
	
	$("#photos", section).photoSlider({
		thumbsList : data,
		thumbClickCallback : _thumbClickHandler, 
		getSignedUrlHandler : function(photoId) {
			// Get signed url by photoId
			params = {};
			params["id"] = photoId;
			params["type"] = "thumb";
			params["func"] = "setSignedUrl-" + sectionIndex + ";" + photoId;
			zwsGetJSON("S3SignerServlet", buildJsonpRequest(params, true), ZWS_CallbackHandler);
		}
	});
}

function getRandomizedTagsArray(data) {
	this.getRandomInterval = function(interval) {
		var randNo = Math.random();
		randNo = randNo * interval;
		return Math.ceil(randNo);
	}
	
	this.getRandomIntervalExcept = function(interval, exceptArr) {
		var result;
		
		if(exceptArr.length == 0) {
			result = getRandomInterval(interval);
			
		} else {
			var insetCounter = 0;
			while(insetCounter < exceptArr.length) {
				insetCounter = 0;
				result = getRandomInterval(interval);
				for(var i=0; i<exceptArr.length; i++) {
					if(exceptArr[i] != result - 1) {
						++insetCounter;
					}
				}
			}
		}
		
		result = (result > 0) ? result - 1 : 0;
		return result;
	}
	
	var result = [];

	var iterLimit = (data.length < 80) ? data.length : 80;
	for(var i=0; i<iterLimit; i++) {
		result.push(getRandomIntervalExcept(data.length, result));
	}
	
	return result;
}

function setAllTags(data) {
	var tagsData = getRandomizedTagsArray(data.tags);
	
	var tags = "";
	for(var i=0; i<tagsData.length; i++) {
		var href = "/tag-view.html#";
		href += (_vars.userId) ? "uid=" + _vars.userId + "&" : "";
		href += "tag=" + $.trim(data.tags[tagsData[i]]);
		tags += "<a href=\"" + href + "\" class=\"tag\">" + $.trim(data.tags[tagsData[i]]) + "</a>\n";
	}
	$(tags).appendTo("#tagCloud #content");
}

function anotherSlanderPublished(albumId, data) {
	var parentCont = $("div[albumId=" + albumId + "]");
		
	$("#post-tattle-indicator", parentCont).fadeOut("fast", function() {
		$("#tattle-accepted", parentCont).fadeIn("fast");
	});
}

function pageChanged(nextPage) {
	$(".pager").trigger("indicator", [true]);
	
	// Get all user albums
	var params = {};
	params["userId"] = "2008091808353055276348";
	params["page"] = nextPage;
	params["func"] = "setAllAlbums";
	zwsGetJSON("ListAlbumsByUserServlet", buildJsonpRequest(params, true), ZWS_CallbackHandler);
}

function initPage() {
	// Get all user albums
	var params = {};
	params["userId"] = "2008091808353055276348";
	params["page"] = 1;
	params["func"] = "setAllAlbums";
	zwsGetJSON("ListAlbumsByUserServlet", buildJsonpRequest(params, true), ZWS_CallbackHandler);
	
	// Get user tags
	var params = {};
	params["userId"] = "2008091808353055276348";
	params["limit"] = "100";
	params["func"] = "setAllTags";
	zwsGetJSON("ListTagsByUserServlet", buildJsonpRequest(params, true), ZWS_CallbackHandler);
}

$(function() {
	window.document.title = "Список альбомов — Zigzagz Photo";
	
	// Check Cookies
	params = {};
	zwsGetJSON("CheckCookieServlet", buildJsonpRequest(params, true), function(data) {
		if(data.status == 200) {
			_conf.currentUser = $.cookie("userName");
			_vars.sectionContainer = $("#sectionContainer");
			
			setInterval(hashCheck, 100);	
		}
	});
});
