/**
 * @author Egloo
 */

var _conf = {};
_conf.currentUser = null;

var _vars = {};
_vars.sectionContainer = null;
_vars.currentPage = 1;
_vars.userId = 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) {
		bindButtonPanelControls(section);
	} else {
		$("a#options").remove();
	}
	if (_pageData[sectionIndex].acl == "private")
	{
		$(".topAlbHeader" , section ).addClass("locked");
	}
	$("#albumTitle", section).text(_pageData[sectionIndex].albumTitle);
	$("#albumTitle", section).get(0).href = "/albumview.html#aid=" + _pageData[sectionIndex].albumId;
	
	$("#dateModified", section).text(getReadableDate(_pageData[sectionIndex].dateModified, true));

	renderPhotos(sectionIndex);
}

function renderPhotos(sectionIndex) {
	// Get all album photos
	var params = {};
	params["albumId"] = _pageData[sectionIndex].albumId;
	params["func"] = "setSectionPhotos-" + String(sectionIndex);
	zwsGetJSON("ListUserPhotosByAlbumServlet", 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) {
	
	
	$("#passing-pane").addClass("hide");
	
	//if (resp.status == 404)
	//{
	 //  $("#album-indicator table").removeClass("hide");
	//}
	
	$("body").removeClass("hide");
	$(".content").removeClass("hide");
	$("html").addClass("htmlbg");
//	$(".pager").trigger("indicator", [false]);
	$($(".pager")[0]).pager({currentPage: _vars.currentPage, changePageCallback : pageChanged, totalItems : resp.total, syncPagers : [$(".pager")[1]]});
	$($(".pager")[1]).pager({currentPage: _vars.currentPage, changePageCallback : pageChanged, totalItems : resp.total, syncPagers : [$(".pager")[0]]});
	
	$("#tagCloud").removeClass("hide");
	
	_pageData = null;
	_pageData = resp.data;
	
	if(resp.data && resp.data.length > 0) {
		_vars.userId = resp.data[0].authorId;
		$("#anotherTags").get(0).href += "#uid=" + _vars.userId;
	}
	
	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");
	$("#count", section).text(data.length);
	
	if(data.length > 0) {
		data.sort(ascPhotosSortHandle);
		$("#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 bindButtonPanelControls(container) {
	$("#photoUpload", container).get(0).href = 
		"/photoupload.html";
	$("#albumEdit", container).get(0).href = 
		"/albumedit.html#aid=" + $(container).attr("albumId");
	$("#photoOrder", container).get(0).href = 
		"/orderpage.html#aid=" + $(container).attr("albumId");
	
	$(".actionPictLink", container).bind("mouseover", function() {
		$("#button-descr", container).text($("img", this).attr("alt"));
		
		var newSrc = $("img", this).get(0).src;
		newSrc = newSrc.replace(/^(.*)_2(\.gif)/, "$1$2");
		$("img", this).get(0).src = newSrc;
	});
	
	$(".actionPictLink", container).bind("mouseout", function() {
		$("#button-descr", container).text("");
		
		var newSrc = $("img", this).get(0).src;
		newSrc = newSrc.replace(/^(.*)(\.gif)/, "$1_2$2");
		$("img", this).get(0).src = newSrc;
	});
	
	$("#options", container).toggle(
		function() {
			$(this).text("отменить");
			$(".action-button-panel", container).parent().slideDown("fast");
		}, 
		function() {
			$(this).text("опции");
			$(".action-button-panel", container).parent().slideUp("fast");
		}
	);
}

function pageChanged(nextPage) {
//	$(".pager").trigger("indicator", [true]);
//	
//	// Get all user albums
//	var params = {};
//	params["page"] = nextPage;
//	params["func"] = "setAllAlbums";
//	params["callback"] = "ZWS_CallbackHandler";
//	$.getJSON(zwsCheckedUrl + "ListUserAlbumsServlet", buildJsonpRequest(params, true));

	if(parseInt(_vars.currentPage) != parseInt(nextPage)) {
		var query = {};
		query["p"] = nextPage;
		$.setQuery(query);
		window.location.reload();
	}
}

function initPage() {
	// Get all user albums
	var params = {};
	params["page"] = _vars.currentPage;
	params["func"] = "setAllAlbums";
	zwsGetJSON("ListUserAlbumsServlet", buildJsonpRequest(params, true), ZWS_CallbackHandler);
	
	// Get user tags
	var params = {};
	params["limit"] = "100";
	params["func"] = "setAllTags";
	zwsGetJSON("ListUserTagsServlet", buildJsonpRequest(params, true), ZWS_CallbackHandler);
}

$(function() {
	window.document.title = "Мои альбомы — Zigzag Photo";
	
	// Check Cookies
	params = {};
	zwsGetJSON("CheckCookieServlet", buildJsonpRequest(params, true), function(data) {
		if(data.status == 200) {
			_conf.currentUser = $.cookie("userName");
			_vars.sectionContainer = $("#sectionContainer");
		
			hashCheck();
		}
	});
});
