dojo.require("dojo.fx");

if (!cheapblog) {
	var cheapblog={};
}

cheapblog.edit=function(instance,module,view) {
	var edit, p=new lop.Page(), name, entryForm, settingsForm, entryTab, settingsTab, nameField, author="", head=dojo.html.getElementsByClass("head",view,"div")[0], title="";
	
	edit=dojo.html.getElementsByClass("edit",module,"div")[0];
	edit.style.width="530px";

/* Getting form fields and elements to do stuff with! */
	
	entryForm=dojo.byId("cheap-blog-entries");
	settingsForm=dojo.byId("cheap-blog-settings");
	entryTab=dojo.byId("cheap-blog-entries-tab");
	settingsTab=dojo.byId("cheap-blog-settings-tab");
	
	entrySelect=dojo.html.getElementsByClass("cheap-blog-existing-entries",entryForm,"select")[0];
	titleField=dojo.html.getElementsByClass("cheap-blog-title",settingsForm,"input")[0];
	authorField=dojo.html.getElementsByClass("cheap-blog-author",settingsForm,"input")[0];
	perPageSelect=dojo.html.getElementsByClass("cheap-blog-nentries",settingsForm,"select")[0];
	cheapblog.dbg(perPageSelect);
	entryItems=dojo.html.getElementsByClass("hentry",view,"li");
	nExistingEntries=entryItems.length;
	
/* Getting existing settings */

	author=p.getModuleData(module,"author");
	if (!author) {
		author=pub.visitor.getScreenName();
	}
	authorField.value=author;
	title=dojo.dom.textContent(head);
	titleField.value=title;
	perPage=p.getModuleData(module,"perPage");
	if (!perPage) {
		perPage=4;
	}
	cheapblog.changeSelected(perPageSelect,perPage);
	
/* Setting up Events */	

	dojo.event.connect(entrySelect,"onchange",function(evt) {
		var select=evt.currentTarget, entryId=select[select.selectedIndex].value;
		cheapblog.dbg("entrySelect:"+select);
		cheapblog.dbg("entryId:"+entryId);
		if (entryId.length<1) {
			cheapblog.clearFields();
			cheapblog.dbg("entryID is empty... returning")
			return;
		}
		cheapblog.loadEntry(entryId);
	})

	dojo.event.connect(entryTab,"onclick",function(evt) {
		var tab=dojo.byId("cheap-blog-entries-tab"), entryForm=dojo.byId("cheap-blog-entries"), settingsForm=dojo.byId("cheap-blog-settings"), entryTab=evt.currentTarget;
		dojo.fx.fadeHide(settingsForm,150,function() {
			dojo.fx.fadeShow(entryForm,150);
			entryTab.setAttribute("class","active");
			dojo.html.removeClass(dojo.byId("cheap-blog-settings-tab"),"active");
		})
	});

	dojo.event.connect(settingsTab,"onclick",function(evt) {
		var tab=dojo.byId("cheap-blog-entries-tab"), entryForm=dojo.byId("cheap-blog-entries"), settingsForm=dojo.byId("cheap-blog-settings"), settingsTab=evt.currentTarget;
		dojo.fx.fadeHide(entryForm,150,function(evt) {
			dojo.fx.fadeShow(settingsForm,150);
			settingsTab.setAttribute("class","active");
			dojo.html.removeClass(dojo.byId("cheap-blog-entries-tab"),"active");
		})
	});

	dojo.event.connect(entryForm,"onsubmit",function(evt) {
		cheapblog.savePost(evt.currentTarget);
	}) 

	dojo.event.connect(settingsForm,"onsubmit",function(evt) {
		cheapblog.saveSettings(evt.currentTarget);
	})
	
/* Getting previous entries */

	var out="", feed, existingEntries,nEntries,entryID;
	feed=dojo.html.getElementsByClass("hfeed",view,"ul")[0];

	for (i=0;i<nExistingEntries;i++) {
		entry=entryItems[i];
		titleElement=dojo.html.getElementsByClass("entry-title",entry,"h4")[0];
		title=dojo.dom.textContent(titleElement);
		out+="<option value='"+entry.id+"'>"+title+"</option>";
	}
	
	entrySelect.innerHTML="<option value=''>or choose this option to create a new entry</option>"+out;
	
/* We're done setting up events now! */

/* Setting the feed URL */

	var sn=pub.visitor.getNormalizedScreenName(), pageURL="http://dev.lawver.net/ajax-experience/profile.php?sn="+sn+"&instance="+escape(module.id);
	var feedURL="http://dev.lawver.net/ajax-experience/cheap-feed.php?sn="+escape(sn)+"&instance="+escape(instance);


/* if (!headFeedLink) {
	headFeedLink=document.createElement("link");
	headFeedLink.setAttribute("rel","alternate");
	headFeedLink.setAttribute("pub:from","cheap-blog");
	headFeedLink.setAttribute("type","application/atom+xml");
	headFeedLink.setAttribute("href",feedURL);
	document.getElementsByTagName("head")[0].appendChild(headFeedLink); */
	var pageLink=dojo.html.getElementsByClass("cheap-blog-feed-link",view,"a")[0];
	pageLink.href=feedURL;
//}


	var editTA = edit.getElementsByTagName("textarea")[0];
	editTA.setAttribute("id", "TA_" + instance); 

	var oFCKeditor = new FCKeditor( instance ) ;

	var storedResources = document.createElement("div");
	storedResources.setAttribute("id", "richTextResourceFrames");
	storedResources.setAttribute("display", "none");
	document.body.appendChild(storedResources);

	oFCKeditor.Config.CustomConfigurationsPath = "/.module/richtext/RTE_fck_conf.js";
	oFCKeditor.ToolbarSet = "Custom1";
	oFCKeditor.Height="300";
	//richTextMods[instance].origText = richTextMods[instance].origText.replace(/&#160;/g, ' ');
	//document.getElementById('rtModName').value = richTextMods[instance].origText;
	//editTA.value = currElm.viewRefBody.innerHTML;
	oFCKeditor.ReplaceTextarea();

	cheapblog.fck=oFCKeditor;

}

cheapblog.deleteEntry=function(entryId) {
	var entry=dojo.byId(entryId);
	if (entry) {
		entry.parentNode.removeChild(entry);
		cheapblog.clearFields();
		alert("Entry has been deleted.");
	}
}

cheapblog.clearFields=function() {
	var form=dojo.byId("cheap-blog-entries"), idField, titleField, contentField, tagField, deleteLI=dojo.byId("cheap-blog-delete"), editor;
	deleteLI.innerHTML="<!-- -->";
	
	var editor=FCKeditorAPI.GetInstance(dojo.byId("editModal").parentNode.id);
	editor.SetHTML("");
	
	idField=dojo.html.getElementsByClass("cheap-blog-entry-id",form,"input")[0];
	idField.value="";
	titleField=dojo.html.getElementsByClass("cheap-blog-entry-title",form,"input")[0];
	titleField.value=""
	contentField=dojo.html.getElementsByClass("cheap-blog-entry-body",form,"textarea")[0];
	contentField.value=""
	tagField=dojo.html.getElementsByClass("cheap-blog-entry-tags",form,"input")[0];
	tagField.value="";
}

cheapblog.loadEntry=function(entryId) {
	var form=dojo.byId("cheap-blog-entries");
	var entry=dojo.byId(entryId);
	
	if (!entry) {
		cheapblog.dbg("entry node doesn't exist");
	}
	
	var title,body,tagLinks,nTags,tags="",form=dojo.byId("cheap-blog-entries"),idField,titleField,contentField,tagField, deleteLI=dojo.byId("cheap-blog-delete");
	
	deleteLI.innerHTML="<a href='javascript:cheapblog.deleteEntry(\""+entryId+"\")'>delete this entry</a>";
	
	idField=dojo.html.getElementsByClass("cheap-blog-entry-id",form,"input")[0];
	idField.value="";
	titleField=dojo.html.getElementsByClass("cheap-blog-entry-title",form,"input")[0];
	contentField=dojo.html.getElementsByClass("cheap-blog-entry-body",form,"textarea")[0];
	tagField=dojo.html.getElementsByClass("cheap-blog-entry-tags",form,"input")[0];
	
	title=dojo.dom.textContent(dojo.html.getElementsByClass("entry-title",entry,"h4")[0]);
	body=dojo.html.getElementsByClass("entry-content",entry,"div")[0].innerHTML;
	tagLinks=dojo.html.getElementsByClass("cheap-blog-tag",entry,"a");
	nTags=tagLinks.length;
	
	var editor=FCKeditorAPI.GetInstance(dojo.byId("editModal").parentNode.id);
	editor.SetHTML(body);
	
	idField.value=entryId;
	titleField.value=title;
	contentField.value=body;
	
	for (i=0;i<nTags;i++) {
		var t=tagLinks[i];
		if (i>0) {
			tags+=", ";
		}
		tags+=dojo.dom.textContent(t);
	}
	
	cheapblog.dbg("nTags:"+nTags+", tags:"+tags);
	
	tagField.value=tags;

	cheapblog.dbg("entry totally exists!");
	
}

cheapblog.saveSettings=function(form) {
	var module, view, p=new lop.Page(), title=dojo.html.getElementsByClass("cheap-blog-title",form,"input")[0].value, author=dojo.html.getElementsByClass("cheap-blog-author",form,"input")[0].value, perPageSelect=dojo.html.getElementsByClass("cheap-blog-nentries",form,"select")[0], nentries, head;
	
	nentries=perPageSelect[perPageSelect.selectedIndex].value;
	
	/* The next line only work if the form is inside <div class="body"> inside <div class="edit">.  You may need to change it. */
	
	module=form.parentNode.parentNode.parentNode;
	view=dojo.html.getElementsByClass("view",module,"div")[0];
	head=view.getElementsByTagName("h3")[0];

	/*
		Continuing the charade that we have a form, and that it has an input with the class of "name" in it, 
		we'll use setModuleData this time to set 
	*/
		
	p.setModuleData(module,"author",author);
	p.setModuleData(module,"perPage",nentries);
	dojo.dom.textContent(head,title);
	
	
	/*
		Now, we should be done, but we may want to initialize the view again since we changed the data.
		So, we'll want to run its init function again.
	*/
	
	cheapblog.view(module,view);
	
	/*
		This tells the tool to close the edit window because now we're done with it.
		This doesn't work in standalone mode.
	*/

	if ( !dojo.lang.isUndefined(lop_mod_closeModEdit) ) {
		lop_mod_closeModEdit()
	}
}

cheapblog.savePost=function(form) {
	var module, view, out="", p=new lop.Page(), entryId, editingEntry=false, title, body, tags, author, now=new Date(), permaLink, sn=pub.visitor.getNormalizedScreenName(), editor;
	
	module=form.parentNode.parentNode.parentNode;
	view=dojo.html.getElementsByClass("view",module,"div")[0];
	hfeed=view.getElementsByTagName("ul")[0];
	entryId=dojo.html.getElementsByClass("cheap-blog-entry-id",form,"input")[0].value;
	title=dojo.html.getElementsByClass("cheap-blog-entry-title",form,"input")[0].value;
	//body=dojo.html.getElementsByClass("cheap-blog-entry-body",form,"textarea")[0].value;

	editor=FCKeditorAPI.GetInstance(module.id);
	body=editor.GetXHTML(true);
	body=body.replace(/Â/g," ");
	body=body.replace(/&#160;/g," ");

	tags=dojo.html.getElementsByClass("cheap-blog-entry-tags",form,"input")[0].value;

	author=p.getModuleData(module,"author");

	if (body.length<1) {
		alert("You can't post an empty blog entry!");
		return;
	}
	
	if (entryId || entryId.length>0) {
		editingEntry=true;
	} else {
		var nItems=dojo.html.getElementsByClass("hentry",view,"li").length;
		var newInt=nItems;
		while (dojo.byId(module.id+"-entry-"+newInt)) {
			newInt++;
		}
		entryId=module.id+"-entry-"+newInt;
	}
	
	permaLink="http://"+pub.page.viewDomain()+"/"+sn+"/profile.html#"+entryId;
	
	out="<h4 class='entry-title'><a class='bookmark' target='_new' href='"+permaLink+"'>"+title+"</a></h4><div class='entry-content'>"+body+"</div>";
	out+="<div class='cheap-blog-meta'>";
	if (author && author.length > 0) {
		out+="posted by <span class='author vcard fn'>"+author+"</span> | ";
	}
	
	out+=" posted on <abbr class='published' title='"+cheapblog.formatDate(now)+"'>"+now.toLocaleString()+"</abbr>";
	
	if (tags && tags.length>0) {
		var tagArray=tags.split(","), nTags=tagArray.length,i;
		if (nTags>0) {
			out+=" | <span class='cheap-blog-tags'>tags: ";
			for (i=0;i<nTags;i++) {
				if (i>0) {
					out+=", ";
				}
				var t=dojo.string.trim(tagArray[i]);
				if (t.length<1) {
					continue;
				}
				out+="<a href='"+cheapblog.tagbase+escape(t)+"' rel='tag' class='cheap-blog-tag'>"+t+"</a>"
			}
			out+="</span>";
		}
	}
	
	out+="</div>";
	
	if ( editingEntry ) {
		currentEntry=dojo.byId(entryId);
		currentEntry.innerHTML=out;
	} else {
		var li=document.createElement("li");
		li.className="hentry";
		li.id=entryId;
		li.innerHTML=out;
		dojo.dom.insertBefore(li,hfeed.firstChild);
	}

	cheapblog.view(module.id,module,view);

	if ( !dojo.lang.isUndefined(lop_mod_closeModEdit) ) {
		lop_mod_closeModEdit()
	}
}

cheapblog.formatDate=function(date) {
	if (!date) {
		return "";
	}
	
	var year=date.getFullYear(), month=date.getMonth()+1, day=date.getDate(), hour=date.getHours(), minutes=date.getMinutes(), seconds=date.getSeconds();
	
	if (month.toString().length<2) {
		month="0"+month;
	}
	
	if (day.toString().length<2) {
		day="0"+day;
	}
	
	if (hour.toString().length<2) {
		hour="0"+hour;
	}
	
	if (minutes.toString().length<2) {
		minutes="0"+minutes;
	}
	
	if (seconds.toString().length<2) {
		seconds="0"+seconds;
	}
	
	return year+"-"+month+"-"+day+"T"+hour+":"+minutes+":"+seconds;
}

cheapblog.parseDate=function(date) {
	var _one=date.split("T"),hour="",minute="",year="", month="", day="";
	if (_one.length>1) {
		_time=_one[1].split(":");
		hour=_time[0];
		minute=_time[1];
	}
	_date=_one[0].split("-");
	year=_date[0];
	month=_date[1];
	day=_date[2];
	
	return [year,month,day,hour,minute];	
}

cheapblog.changeSelected=function(select,value) {
	var options=select.options, n=options.length, i=0;
	for (i=0;i<n;i++) {
		if (options[i].value==value) {
			options[i].selected=true;
			return;
		}
	}
}
