/**
 * ABC = Comments Pagination and Display Object
 * 
 * @author Avery
 */

var ABC = {
	init : function(options) {

		// Start Me Up
		ABC.wrap = $(options.wrap);
		ABC.commentpane = $(options.display);
		ABC.pagination = $(options.pager);
		ABC.first = $(options.first);
		ABC.last = $(options.last);
		ABC.uuid = options.uuid;
		ABC.comments_per_page = options.per_page;

		// do we have an alternate data source or data model?
		if (options.data_source) ABC.data_source = options.data_source;
		if (options.data_model) ABC.data_model = options.data_model;

		if (options.max_pages) ABC.max_pages = options.max_pages;

		// do we have alternate template info
		if (options.comment_template) ABC.comment_template = options.comment_template;
		if (options.comment_image) ABC.comment_image = options.comment_image;

		// Load first batch
		ABC.get_page(1);
	},

	show : function() {
		ABC.wrap.show();
	},
	
	hide : function() {
		ABC.wrap.hide();
	},

	refresh : function() {
		ABC.pages = Math.ceil( ABC.total_comments / ABC.comments_per_page );

		// make pagers
		ABC.pagination.each(function(){
			$(this).empty();

			if (ABC.max_pages > 0) {

				var half = Math.floor(ABC.max_pages / 2);

				if (ABC.page - half < 0) {
					var startpage = 1;
					var endpage = ABC.max_pages;
				} else if (ABC.page + half < ABC.pages) {
					var startpage = ABC.page - half;
					var endpage = ABC.page + (ABC.max_pages - half);

				} else {
					var endpage = ABC.pages;
					var startpage = ABC.pages - (ABC.max_pages - 1);
				}

				// safety first			
				if (startpage < 1) startpage = 1;
				if (endpage > ABC.pages) endpage = ABC.pages;

			} else {
				var startpage = 1;
				var endpage = ABC.pages;
			}

			if (startpage > 1) $(this).append("...&nbsp;&nbsp;");

			for(var i = startpage; i <= endpage; i++) {
				var pageLink = $("<a href='#Page_" + i + "'>" + i + "</a>").bind(
					"click",
					function(){
						ABC.get_page(parseInt($(this).html()));
					});

				if (ABC.page == i) pageLink.addClass("selected");

				var curLink = $("<li/>").append(pageLink);
				if (i == endpage) curLink.addClass("last");
				$(this).append(curLink);
			}
			
			if (endpage < ABC.pages) $(this).append("...");
			
		});

		// bind first / last

		try {
			$(ABC.first).unbind("click");
			$(ABC.last).unbind("click");
		} catch (e) {
		}

		$(ABC.first).bind(
			"click",
			function(){ABC.get_page(1);}
		);
		$(ABC.last).bind(
			"click",
			function(){ABC.get_page(ABC.pages);}
		);

		// handle first / last selection

		if (ABC.page == 1) {
			$(ABC.first).addClass("selected");
		} else {
			$(ABC.first).removeClass("selected");
		}
		
		if (ABC.page == ABC.pages) {
			$(ABC.last).addClass("selected");
		} else {
			$(ABC.last).removeClass("selected");
		}

	},

	show_last : function() {
		ABC.get_page(ABC.pages);
	},

	get_page : function(_page) {
		// if (ABC.page == _page) return false; // we're already on that one
		ABC.page = _page;
		ABC.load();
	},

	load : function() {
		
		var off = ((ABC.pages > 1) ? (ABC.page - 1) * ABC.comments_per_page : 0);

		var source = ABC.data_source
						.replace("{uuid}",ABC.uuid)
						.replace("{offset}",off)
						.replace("{limit}",ABC.comments_per_page);

		$.getJSON(
			source,
			{},
			function(data) {

				ABC.total_comments = data.data[0].value.Count; // refresh our master comment count

				ABC.clear(); // empty container of last batch of stories
				ABC.refresh(); // update counts, interface selection

				if (ABC.total_comments > 0) {
					ABC.show();
				} else {
					ABC.hide();
				}

				if (data.data[0].value.Count > 0) { // && data.data[0].value.Comments[0].MessageBody.length > 0) {

					// loop thru and add comments
					for (var i = 0; i < data.data[0].value[ABC.data_model.type].length; i++) {
						var com_com = data.data[0].value[ABC.data_model.type][i];
						com_com.CommentNum = ABC.comments_per_page * (ABC.page - 1) + i + 1;
						ABC.add(com_com);
					}
				}
			}
		);

		return;
		
	},

	add : function(CommentRow) {
		ABC.commentpane.append(
			ABC.format(CommentRow)
		);
	},

	clear : function() {
		ABC.commentpane.empty();
	},

	format : function(CommentRow) {

		var html_block = ABC.comment_template;

		if (CommentRow[ABC.data_model.vault_id] != null && CommentRow[ABC.data_model.vault_id] != 0) {
			var _comment_image = ABC.comment_image
										.replace("{VAULT_ID}",""+CommentRow[ABC.data_model.vault_id]);
		} else {
			var _comment_image = ABC.comment_image_novault;
		}
 
		return html_block
			.replace(/\{IMAGE\}/g,_comment_image)
			.replace(/\{USERNAME\}/g,CommentRow.UserName)
			.replace(/\{COMMENT_ID\}/g,CommentRow[ABC.data_model.object_id])
			.replace(/\{TOTAL\}/g,ABC.total_comments)
			.replace(/\{NUM\}/g,CommentRow.CommentNum)
			.replace(/\{DATE\}/g,ABC.fixDate(CommentRow.InsertedTS))
			.replace(/\{BODY\}/g,ABC.safetext(CommentRow[ABC.data_model.body]));
	},

	safetext : function(text) {
		var _text = new String(text);
		return _text.replace(/<(?:.|\s)*?>/g,"");
	},

	fixDate : function(str) {
		
		if (str.length != 19) return str;
		
		var y,m,d,time; // h,m,s;

		y = str.substr(0,4);
		m = str.substr(5,2);
		d = str.substr(8,2);
		time = str.substr(11,8);
		
		return d + "." + m + "." + y + " " + time;
		
	},
	
	kill : function(CommentID,me) {
		if (confirm('Are You Sure?')) {
			var target = ABC.kill_target.replace(/\{COMMENT_ID\}/g,CommentID);
			alert(target);
			$.get(target);
			$(me).parent().parent().parent().remove();
		}
	},

	kill_target : "/API/CMS/Comment/Delete?{COMMENT_ID}",
	post_target : "/API/Story/Comment/Post?{uuid}",
	data_source : "/API/Story/Comment/GetAll?{uuid}&{limit}&{offset}",

	uuid : "",

	page : 1,
	pages : 1,

	comments_per_page : 5, // comments in interface / page
	max_pages : -1, // max pages in pager at once, -1 means no limit

	total_comments : 0,

	comment_image : "/API/CMS/User/GetProfilePhoto?{VAULT_ID}&D&134&100",
	comment_image_novault : "/images/thumbnail_no_border.jpg",

	comment_template : "<div class='Comment'><div class='ImagePane'><a href='/userprofile.php?un={USERNAME}'><img src='{IMAGE}' /></a><p>Von: <a href='/userprofile.php?un={USERNAME}'>{USERNAME}</a> </p></div><div class='CommentPane'><p class='datePosted'>{DATE} Uhr, Kommentar {NUM} von {TOTAL}</p><p>{BODY}</p></div><div class='clearBoth'></div><br /><br /></div>",
	pagination_label : "",
	pagination_template : "",

	commentpane : "",
	firstlast : "",
	pagination : "",

	data_model : {
		type : "Comments",
		image_ref_id : "VaultID",
		vault_id : "VaultID",
		object_id : "CommentID",
		body : "MessageBody"
	}

}
