/*********************************
ActiveBoard File Attachment Script
Copyright ©2005 Sparklit Networks
**********************************/

var atcIdField;
var atcNameField;
var atcDisplay;
var removeLater;
var atcFileNames;
var atcFileIDs;
var insertedIDs = [];

function atcInit(idField, nameField, display) {
	atcIdField = idField;
	atcNameField = nameField;
	atcDisplay = display;
	insertedIDs = new Array();
	atcFileNames = new Array();
	atcFileIDs = new Array();
}

function atcAddFile(id, name) {
	atcFileNames[atcFileNames.length] = name;
	atcFileIDs[atcFileIDs.length] = id;
	
	atcUpdateIDs();
	atcUpdateDisplay();
}

function addSlashes(str) {
	return (str+'').replace(/([\\"'])/g, "\\$1").replace(/\u0000/g, "\\0");
}

function atcRemoveLink(id, name) {
	return name+" <a href=\"javascript: if(confirm('Remove file "+addSlashes(name)+"?')) { atcRemoveFile("+id+"); }\">["+removeLinkText+"]</a>";
}

function atcInsertLink(id, name) {
	return " <a href=\"javascript: if(confirm('Insert "+addSlashes(name)+" into the text area? It will be removed from the attachments section once you submit your post.')) { insertedIDs.push("+id+"); insertImageIntoTextArea(document.getElementById(\'textEditor\'),\'"+addSlashes(name)+"\', \'/download.spark?ID="+id+"&aBID="+aBID+"\'); }\">["+insertLinkText+"]</a>";
}

function atcRemoveInsertedFiles(){
	var i;
	for(i in insertedIDs){
		atcRemoveFile(insertedIDs[i]);
	}
}

function atcRemoveFile(id) {
	newFiles = new Array();
	newFileIDs = new Array();
	
	j = 0;
	for(i = 0; i < atcFileIDs.length; i++) {
		if(atcFileIDs[i] == id)
			continue;
		
		newFiles[j] = atcFileNames[i];
		newFileIDs[j] = atcFileIDs[i];
		j++;
	}
	
	atcFileNames = newFiles;
	atcFileIDs = newFileIDs;
	atcUpdateIDs();
	atcUpdateDisplay();
}

function atcUpdateIDs() {

	str = '';
	for(i = 0; i < atcFileIDs.length; i++) {
		if(i > 0)
			str += ',';
		str += atcFileIDs[i];
	}
	atcIdField.value = str;
	
	str = '';
	for(i = 0; i < atcFileNames.length; i++) {
		if(i > 0)
			str += ',';
		str += atcFileNames[i];
	}
	atcNameField.value = str;
}

function atcUpdateDisplay() {
	str = '';
	for(i = 0; i < atcFileIDs.length; i++) {
		if(i > 0)
			str += ', ';
		else
			str += attachedText+': ';
		str += atcRemoveLink(atcFileIDs[i], atcFileNames[i]);

		var regex=/.*\.(jpe?g|png|gif)$/i;
		 
		if (regex.test(atcFileNames[i]))
			str += atcInsertLink(atcFileIDs[i], atcFileNames[i]);			
	}
	atcDisplay.innerHTML = str;
}
