

function isPageAfter(oldPage, activePage)
{
	var oldPage_index = -1;
	var activePage_index = -1;

	for (var n = 0; n < pages.length; n++)
	{
		if (pages[n] == oldPage)
		{
			oldPage_index = n;
		}
		else if (pages[n] == activePage)
		{
			activePage_index = n;
		}
	}
	
	return (activePage_index > oldPage_index);
}

function close_dialog(id)
{
	$(id).dialog("close");
	return;

	if ($(id).dialog('option', 'modal'))
	{
		$('.ui-widget-overlay').fadeOut("fast");
	}

	 $(id).parent().fadeOut("fast", function()
	 {
		$(id).dialog("close");
	 });
}

function open_dialog(id)
{
	$(id).dialog("open");
	return;
	$(id).parent().hide();
	
	if ($(id).dialog('option', 'modal'))
	{
		$('.ui-widget-overlay').hide();
		$('.ui-widget-overlay').fadeIn("fast");
	}

	$(id).parent().fadeIn("fast");
}

var writers = [];
var articles = new Array();

function article_id2index(id)
{
	var index = -1;

	jQuery.each(articles, function(n, article)
	{
		if (article.Id == id)
		{
			index = n;
			return false;
		}
	});
	
	return index;
}

function is_side_tab(page)
{
	return page == "profile";
}

var showing_profile_id = null;

function writer_save_handler(inst, name, value)
{
	writers[UserHandling.current_user_.Id][name] = value;
	
	var args = jQuery.param(writers[UserHandling.current_user_.Id]);

	jQuery.getJSON("functions/save_writer.php?" + args, function(data)
	{
		if (data.Status.Success)
		{
			$('.profile' + name).html(value == "" ? "No value" : value);
			$('#profileEdit' + name).editable("functions/save_writer.php", { "paramName" : name, "submit" : function(inst1, name2, value3) { writer_save_handler(inst1, name2, value3); } });
			update_writers(data, true);
			//setTimeout(function() { update_writers(data); }, 0);
		}
		else
		{
			alert(data.Status.Error);
			$('.profile' + name).html(value == "" ? "No value" : value);
			$('#profileEdit' + name).editable("functions/save_writer.php", { "paramName" : name, "submit" : function(inst1, name2, value3) { writer_save_handler(inst1, name2, value3); } });
		}
	});
}

function set_profile_picture(user)
{
	if (user.Picture)
	{
		$('.profileImage').attr("src", "images/profile/" + user.Id + ".jpg?" + (new Date()).getTime());
	}
	else
	{
		$('.profileImage').attr("src", "images/profile_unknown.png");
	}
}

function ajaxFileUpload()
{

	$.ajaxFileUpload
	(
		{
			url:'functions/upload_file.php',
			secureuri:false,
			fileElementId:'fileToUpload',
			dataType: 'json',
			success: function (data, status)
			{
				if (data.Status.Success)
				{
					update_writers(data);
				}
				else
				{
					alert(data.Status.Error);
				}
			},
			error: function (data, status, e)
			{
				alert(e);
			}
		}
	)
	
	return false;

}

function set_profile(user)
{
	if (!user)
	{
		console.log("user is undefined, showing_profile_id=" + showing_profile_id);
		return;
	
	}
	showing_profile_id = user.Id;

	$('.profileName').html(user.Name == "" ? "No value" : user.Name);
	$('.profileLocation').html(user.Location == "" ? "No value" : user.Location);
	$('.profileEmail').html(user.Email == "" ? "No value" : user.Email);
	$('.profileAbout').html(user.About == "" ? "No value" : user.About);
	$('.profileQuote').html(user.Quote == "" ? "No value" : user.Quote);
	
	$('#profilePassword1').val("");
	$('#profilePassword2').val("");
	$('#fileToUpload').val("");
	$('#profilePasswordSubmit').attr("disabled", "disabled");
	
	if (UserHandling.current_user_ != null && user.Id == UserHandling.current_user_.Id)
	{
		$('#profileEditName').editable("functions/save_writer.php", { "paramName" : "Name", "submit" : function(inst, name, value) { writer_save_handler(inst, name, value); } });
		$('#profileEditLocation').editable("functions/save_writer.php", { "paramName" : "Location", "submit" : function(inst, name, value) { writer_save_handler(inst, name, value); } });
		$('#profileEditEmail').editable("functions/save_writer.php", { "paramName" : "Email", "type" : "textarea", "submit" : function(inst, name, value) { writer_save_handler(inst, name, value); } });
		$('#profileEditAbout').editable("functions/save_writer.php", { "paramName" : "About", "type" : "textarea", "submit" : function(inst, name, value) { writer_save_handler(inst, name, value); } });
		$('#profileEditQuote').editable("functions/save_writer.php", { "paramName" : "Quote", "submit" : function(inst, name, value) { writer_save_handler(inst, name, value); } });
		$('#profilePassword').show();
		$('#profileUpload').show();
		
		/*new AjaxUpload($('#profileUpload'), {
			action: 'functions/upload_file.php',
			name: 'profilefile',
			data : { "Id" : showing_profile_id },
			responseType: 'json',
			onSubmit: function(file, ext)
			{
				if (!(ext && /^(jpg|png|jpeg|gif)$/.test(ext)))
				{ 
			// extension is not allowed 
					alert('Only JPG, PNG or GIF files are allowed');
					return false;
				}
				//status.text('Uploading...');
			},
			onComplete: function(file, data)
			{
				if (data.Status.Success)
				{
					update_writers(data);
				}
				else
				{
					alert(data.Status.Error);
				}
			}
		});*/
	}
	else
	{
		$('#profileEditName').unbind("click");
		$('#profileEditLocation').unbind("click");
		$('#profileEditEmail').unbind("click");
		$('#profileEditAbout').unbind("click");
		$('#profileEditQuote').unbind("click");
		$('#profilePassword').hide();
		$('#profileUpload').hide();
	}
	
	set_profile_picture(user);
	
	var found_saved = false;
	var found_published = false;
	
	$('.profileSavedArticles').empty();
	$('.profilePublishedArticles').empty();
	
	jQuery.each(articles, function(n, article)
	{
		if (typeof article == "undefined")
		{
			return;
		}
	
		if (article.WriterId == user.Id)
		{
			if (article.Published == 1)
			{
				$('.profilePublishedArticles').append(format_article_link(article, true));
				found_published = true;
			}
			else
			{
				$('.profileSavedArticles').append(format_article_link(article, true));
				found_saved = true;
			}
		}
	
	});
	
	if (!found_saved)
	{
		$('.profileSavedArticlesContainer').hide();
	}
	else
	{
		$('.profileSavedArticlesContainer').show();
	}
	
	if (!found_published)
	{
		$('.profilePublishedArticles').html("No articles found");
	}
}

function set_page(page)
{
	if (page == "write")
	{
		ArticleHandling.init()
	}
	else
	{
		showing_profile_id = null;
		var writer_id = 0;
		
		if (UserHandling.current_user_ != null)
		{
			writer_id = UserHandling.current_user_.Id;
		}
	
		if (page.indexOf("profile") != -1)
		{
			var id = page.substr(7);
			
			if (id.length > 0)
			{
				writer_id = id;
			}
			
			page = "profile";
		}
	
		var oldPage = activePage;
		activePage = page;
		
		
	
		if (oldPage == activePage && activePage != "profile")
		{
			return;
		}
		
		if ($('#' + oldPage + 'TabButtonSelected').is(":visible"))
		{
			$('#' + oldPage + 'TabButtonSelected').hide("slide", { direction : is_side_tab(oldPage) ? "left" : "down" });
		}
		
		if (UserHandling.current_user_ != null)
		{
			if (writer_id == UserHandling.current_user_.Id)
			{
				$('#' + activePage + 'TabButtonSelected').show("slide", { direction : is_side_tab(activePage) ? "left" : "down" });
			}
		}
		else
		{
			$('#' + activePage + 'TabButtonSelected').show("slide", { direction : is_side_tab(activePage) ? "left" : "down" });
		}
		
		//var pageAfter = isPageAfter(oldPage, activePage);
		$('#' + oldPage + 'Container').fadeOut(function()
		{
			if (activePage == "profile")
			{
				set_profile(writers[writer_id]);
				
			}
			$('#' + activePage + 'Container').fadeIn();
		});//hide("slide", { direction: pageAfter ? "left" : "right" });
		
		/*if (activePage != "profile")
		{
			$('#' + activePage + 'Container').fadeIn();//show("slide", { direction: pageAfter ? "right" : "left" });
		}*/
	}
}

function save_new_password()
{
	writers[UserHandling.current_user_.Id]["Password"] = $('#profilePassword1').val();
	
	var args = jQuery.param(writers[UserHandling.current_user_.Id]);

	jQuery.getJSON("functions/save_writer.php?" + args, function(data)
	{
		if (data.Status.Success)
		{
			$('#profilePassword1').val("");
			$('#profilePassword2').val("");
			$('#profilePasswordSubmit').attr("disabled", "disabled");
	
			update_writers(data, true);
			alert("New password set successfully!");
		}
		else
		{
			alert(data.Status.Error);
		}
	});
}

function passwordCheck(e)
{
	if ($('#profilePassword1').val() != "" && $('#profilePassword2').val() == $('#profilePassword1').val())
	{
		$('#profilePasswordSubmit').removeAttr("disabled");
	}
	else
	{
		$('#profilePasswordSubmit').attr("disabled", "disabled");
	}
}

$(function()
{
	$('.sideImageContainer').cycle({ "speed" : 2000 });
	
	$('.tabButtonSelected').hide();
	$('#' + activePage + 'TabButtonSelected').show();
	
	$('.mainContainer').hide();
	$('#' + activePage + 'Container').show();
	
	var tabWidth = $('#centerContainer').width()/pages.length;
	$('.tabCell').width(tabWidth);
	$('.tabButtonText').width(tabWidth);

	
	$('.tabButtonClickable').bind("click", function(e)
	{
		set_page(e.target.id.substr(0, e.target.id.indexOf("TabButtonText")));
		e.preventDefault();
	});
	
	$('#profilePassword1').bind("keyup", passwordCheck);
	$('#profilePassword2').bind("keyup", passwordCheck);
	
	$('#profilePasswordSubmit').bind("click", function(e) { save_new_password(); e.preventDefault(); });
	
	$('.articleSearchInput').bind("keydown", function(e)
	{
		if (e.keyCode == 13)
		{
			e.preventDefault();
			
			var value = $(e.target).attr("value");
			
			if (value == "")
			{
				return;
			}
			
			$('#searchDialog').dialog('option', 'title', "Search for <span style=\"font-style: italic\">" + value + "</span>");
			$('#searchDialog').html("<div id=\"searchNoArticlesFound\">No articles found</div>");
			
			var query = value.toLowerCase();
			
			jQuery.each(articles, function(n, article)
			{
				if (typeof article == "undefined")
				{
					return;
				}
			
				var name = article.Name.toLowerCase();
				
				if (name.indexOf(query) != -1)
				{
					var html = format_article_link(article);

					$('#searchDialog').append(html);
			
					$('#searchNoArticlesFound').remove();
				}
			});
			
			open_dialog("#searchDialog");
		}
	});

	$("#searchDialog").dialog({
		width: 600, 
		draggable: false,
		resizable: false,
		autoOpen : false,
		buttons: { "Close" : function() { close_dialog('#searchDialog'); } }
	});

	
	$("#messageDialog").dialog({
		bgiframe: true,
		width: 300, 
		draggable: false,
		resizable: false,
		autoOpen : false
	});
	
	$('#newArticleDialog').dialog({
 		bgiframe: true,
		width: 850, 
		draggable: false,
		resizable: false,
		autoOpen : false,
		modal : true,
		buttons: { 
				"Cancel" : function() { ArticleHandling.hide(); },
				"Publish" : function() { ArticleHandling.save(1); },
				"Save" : function() { ArticleHandling.save(0); } }
	});
	
	$('#articleDialog').dialog({
 		bgiframe: true,
		width: 850, 
		draggable: false,
		resizable: false,
		autoOpen : false,
		modal : true
	});
	
	$('#commentsDialog').dialog({
		bgiframe: true,
		width: 700, 
		draggable: false,
		resizable: false,
		autoOpen : false,
		buttons: { "Close" : function() { close_dialog('#commentsDialog'); } }
	});
	
		
	
	
	$('.libraryListItemPopup').hide();
	$('.libraryListItemLink').popupmenu({ "addStyle" : "libraryListItemLinkHover" });
	
// 	DD_roundies.addRule('.roundTop20', '20px');
	/*
	$('.roundInput').corner("3px");
	$('.mceLayout').corner("3px");*/
	//$('.roundTop20').corner("top 20px keep");
	//$('.roundRight20').corner("right 20px");
	//$('.roundBottom20').corner("bottom 20px");
	//$('.roundLeft400').corner("left 400px");
	//$('.roundRight400').corner("right 400px");
	/*
	$('.ui-dialog').corner("20px");
	*/
	position_side_container();

	$(window).resize(position_side_container);
	
	$('#sideContainer').hide();
	
	UserHandling.init();
	
	update_stuff();
	
	if ($.browser.msie && $.browser.version.substr(0,1)<8)
	{
		$('#warning').show();
	}
	
	$('#loading').hide();

});

function position_side_container()
{
	var offset = $('#mainContainer').offset();

	offset["top"] = offset["top"] + "px";
	offset["left"] = (offset["left"] + $('#mainContainer').width() + 1) + "px";
	
	$('#sideContainer').height($('#mainContainer').outerHeight());
	$('#sideContainer').css(offset);
}

function open_article(article_id)
{
	var article = articles[article_id2index(article_id)];

	$('#articleDialog').dialog('option', 'title', article.Name + "<span class=\"articleTitleName\">by " + writers[article.WriterId].Name + "</span>");
	
	var html = "";//"<img class=\"articleImage\" src=\"images/comment_platta.png\" alt=\"\"/>";
	html += article.Text;
	html = linkify(html);
	
	$('#articleDialog').html("<div class=\"articleScroll\">" + html + "</div>");
	
	
	$('#articleDialog').dialog('option', 'buttons', { "Close" : function() { close_dialog('#articleDialog'); }, "Printable version" : function() { document.location.href = "print.php?Id=" + article_id; }, "Show comments" : function() { open_comments(article); } });
		
	open_dialog('#articleDialog');
}

function open_comments(article)
{
	jQuery.getJSON("functions/get_comments.php?ArticleId=" + article.Id, function(data)
	{
		if (data.Status.Success)
		{
			$('#commentsDialog').dialog('option', 'title', "Comments on \"" + article.Name + "\"");
			var content_html = "<div class=\"commentScroll\">";
			
			content_html += "<div class=\"commentPost\"><form id=\"commentForm\">";
			content_html += "<input style=\"display: none;\" id=\"commentArticleIdInput\" name=\"ArticleId\" type=\"hidden\" value=\"" + article.Id + "\"/>";
			
			if (UserHandling.current_user_ == null)
			{
				content_html += "<div class=\"commentNameContainer roundInput\"><span class=\"commentNameTitle\">Name:</span><input class=\"commentNameInput\" name=\"Name\" id=\"commentNameInput\" type=\"text\"/></div>";
			}
			else
			{
				content_html += "<input style=\"display: none;\" name=\"Name\" id=\"commentNameInput\" type=\"hidden\" value=\"" + UserHandling.current_user_.Name + "\"/>";
			}
			
			content_html += "<textarea class=\"commentTextInput roundInput\" name=\"Text\" id=\"commentTextInput\"></textarea>";
			content_html += "<div class=\"commentSubmitContainer\"><input class=\"roundInput\" id=\"commentSubmit\" value=\"Post comment\" type=\"submit\"/></div";
			content_html += "<div class=\"clear\"></div>";
			content_html += "</form></div>";
			
			if (data.Data)
			{
				jQuery.each(data.Data, function(n, comment)
				{
					var img = "images/profile_unknown.png";
					var name = comment.Name;
				
					if (comment.WriterId != null && comment.WriterId != "")
					{
						if (writers[comment.WriterId].Picture)
						{
							img = "images/profile/" + comment.WriterId + ".jpg";
						}
					
						name = writers[comment.WriterId].Name;
					}
				
					content_html += "<div class=\"commentItem\"><img src=\"" + img + "\" alt=\"\"/><div class=\"commentItemTitle\">Posted by <span class=\"emphBold\">" + name + "</span> on " + comment.CreatedTime + "</div><div class=\"commentItemText\">" + nl2br(comment.Text) + "</div></div>";
				});
			}
			else
			{
				content_html += "<div class=\"commentNone\">No comments posted yet</div>";
			}
			
			content_html += "</div>";
			
			$('#commentsDialog').html(content_html);
			
			CommentHandling.init(article);
		}
		else
		{
			$('#commentsDialog').dialog('option', 'title', "Error");
			$('#commentsDialog').html(data.Status.Error);
		}
		
		open_dialog('#commentsDialog');
	});
}

function update_stuff()
{
	$('.articleWriters').html("Loading...");
	$('.articleList').html("Loading...");
	$('.libraryListItemPopup').html("Loading...");

	jQuery.getJSON("functions/get_writers.php", update_writers_and_load_articles);
	
	
	
	if (UserHandling.current_user_ == null)
	{
		$('#sideContainer').hide("slide", { direction: "left" });
		
	}
	else
	{
		$('#sideContainer').show("slide", { direction: "left" });
	}
}

function update_writers_and_load_articles(data)
{
	update_writers(data);
	
	if (activePage == "profile")
	{
		if (showing_profile_id != null)
		{
			set_page("profile" + showing_profile_id);
		}
	}
	else
	{
		set_page(activePage);
	}
	
	jQuery.getJSON("functions/get_articles.php", update_articles);
}

function update_writers(data, no_update_profile)
{
	$('.articleWriters').empty();

	if (data.Status.Success)
	{
		writers = [];
	
		jQuery.each(data.Data, function(n, writer)
		{
			writers[writer.Id] = writer;
			$('.articleWriters').append("<div onclick=\"set_page('profile" + writer.Id + "')\" class=\"writerLink\">" + writer.Name + "</div>");
		});
		
		if (typeof no_update_profile == "undefined" && showing_profile_id != null)
		{
			set_profile(writers[showing_profile_id]);
		}
	}
	else
	{
		$('.articleWriters').html("Error loading, " + data.Status.Error);
	}
}

var months = [ "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec" ];

function article_compare(a, b)
{
	var x = a.CreatedTime;
	var y = b.CreatedTime;
	
	return ((x > y) ? -1 : ((x < y) ? 1 : 0));
}

function update_articles(data)
{
	$('.articleList').empty();
	$('.libraryListItemPopup').html("<div class=\"libraryNoArticlesFound\">No articles found</div>");

	if (data.Status.Success)
	{
		articles = new Array();
	
		if (data.Data)
		{
			articles = data.Data;
			articles.sort(article_compare);
		
			var count = 0;
			/*jQuery.each(data.Data, function(n, article)
			{
				articles[article.Id] = article;
			});
			*/
			//articles.sort(article_compare);
			
			jQuery.each(articles, function(n, article)
			{
				if (typeof article == "undefined")
				{
					delete articles[n];
					return;
				}
			
				if (article.Published == 1)
				{
					var date = new Date();
					date.setTime(article.CreatedTime * 1000);

					var html = format_article_link(article);

					if (count <= 9)
					{
						$('.articleList').append(html);
					}
					
					var popup_id = '#' + months[date.getMonth()] + '_' + date.getFullYear() + '_target';
					
					$(popup_id + " .libraryNoArticlesFound").remove();
					
					$(popup_id).append(html);
					count++;
				}
			});
		}
		
		if (showing_profile_id != null)
		{
			set_profile(writers[showing_profile_id]);
		}
	}
	else
	{
		$('.articleList').html("Error loading, " + data.Status.Error);
	}
}


function format_article_link(article, edit)
{
	var date = new Date();
	date.setTime(article.CreatedTime * 1000);

	var html = "<div class=\"articleListItem\"><span class=\"articleDate\">" + date.formatDate("yyyyMMdd") + "</span> <span class=\"articleListItemTitle\" onclick=\"open_article(" + article.Id + ")\">" + article.Name + "</span>";
	
	if (edit && UserHandling.current_user_ != null && article.WriterId == UserHandling.current_user_.Id)
	{
		html += "<span class=\"articleEdit\" onclick=\"ArticleHandling.init(" + article.Id + ");\">[edit]</span>";
		html += "<span class=\"articleEdit\" onclick=\"ArticleHandling.remove(" + article.Id + ");\">[delete]</span>";
	}
	else if (!edit)
	{
		html += "<span class=\"articleEdit\" onclick=\"set_page(profile" + article.WriterId + ");\">by " + writers[article.WriterId].Name + "</span>";
	}
	
	return html + "</div>";
}

Date.prototype.formatDate = function(format)

{

    var date = this;

    if (!format)

      format="MM/dd/yyyy";               

 

    var month = date.getMonth() + 1;

    var year = date.getFullYear();    

 

    format = format.replace("MM",month.toString().padL(2,"0"));        

 

    if (format.indexOf("yyyy") > -1)

        format = format.replace("yyyy",year.toString());

    else if (format.indexOf("yy") > -1)

        format = format.replace("yy",year.toString().substr(2,2));

 

    format = format.replace("dd",date.getDate().toString().padL(2,"0"));

 

    var hours = date.getHours();       

    if (format.indexOf("t") > -1)

    {

       if (hours > 11)

        format = format.replace("t","pm")

       else

        format = format.replace("t","am")

    }

    if (format.indexOf("HH") > -1)

        format = format.replace("HH",hours.toString().padL(2,"0"));

    if (format.indexOf("hh") > -1) {

        if (hours > 12) hours - 12;

        if (hours == 0) hours = 12;

        format = format.replace("hh",hours.toString().padL(2,"0"));        

    }

    if (format.indexOf("mm") > -1)

       format = format.replace("mm",date.getMinutes().toString().padL(2,"0"));

    if (format.indexOf("ss") > -1)

       format = format.replace("ss",date.getSeconds().toString().padL(2,"0"));

    return format;

}

String.repeat = function(chr,count)

{    

    var str = ""; 

    for(var x=0;x<count;x++) {str += chr}; 

    return str;

}

String.prototype.padL = function(width,pad)

{

    if (!width ||width<1)

        return this;   

 

    if (!pad) pad=" ";        

    var length = width - this.length

    if (length < 1) return this.substr(0,width);

 

    return (String.repeat(pad,length) + this).substr(0,width);    

}    

String.prototype.padR = function(width,pad)

{

    if (!width || width<1)

        return this;        

 

    if (!pad) pad=" ";

    var length = width - this.length

    if (length < 1) this.substr(0,width);

 

    return (this + String.repeat(pad,length)).substr(0,width);

} 

function nl2br(str)
{
	return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1<br/>$2');
}

function linkify(string, options)
{
    if(!options) options = {};
    if(!options.limit) options.limit = 10;
    if(!options.tagFill) options.tagFill = '';
    
    var regex = /((http\:\/\/|https\:\/\/|ftp\:\/\/)|(www\.))+(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/gi;
    
    string = string.replace(regex, function(value)
    {
        var matchTag = /<(?:.|\s)*?>/g;
        value =  value.replace(matchTag, "");
    
       // value = value.toLowerCase();
        var m = value.match(/^(([a-z]|[A-Z])+:\/\/)/);
        var nice;
        var url;
        
        if(m)
        {
            nice = value.replace(m[1],'');
            url = value;
        }
        else
        {
            nice = value;
            url = 'http://' + nice;
        }
        
       
        return '<a href="' + url + '"' + (options.tagFill != '' ? (' ' + options.tagFill) : '')+ '>' + url + '</a>';
    });
    
    return string;
};




