// Core Javascript document for AJAX Gallery WordPress Plugin
// by: Victorio Duran III - victorio_duran@yahoo.com - iiimedia.net

// AJAX function to get gallery item
function getPLGalleryItem (currentItemID, offset, AJAXAreaID, serverSidePage) {
	// get AJAX Area
	AJAXArea = document.getElementById(AJAXAreaID)

	// set 'wait' message
	msg = 'Loading...';
	
	// build AJAX post variables
	currentItemID = new Array('currentItemID', currentItemID);
	offset = new Array('offset', offset);
	postvar = new Array(currentItemID, offset);		
	
	// submit ajax variables
	submitAJAXVars (AJAXArea, msg, postvar, serverSidePage);
	
	return false;
}

// function to check form data
function checkPLAJAXGalleryForm (infoAreaID) {
	// get info area
	if (infoAreaID) {
		infoArea = document.getElementById(infoAreaID);
	} else {
		infoArea = false;
	}
	
	// hide error message
	infoArea.innerHTML = "";
	
	// check form fields	
	checkField(document.getElementById('txt_pl-ajax-gallery-image'), 'URL for the image', false, infoArea);
		
	if (infoArea.innerHTML == "") return true;
	
	return false;	
}

// function to confirm delete operation
function confirmDelete (itemName) {
	confirmMsg = "Are you sure you want to delete this gallery item";
	if (itemName) confirmMsg += " entitled " + itemName;
	confirmMsg += "?";
	
	return (confirm(confirmMsg));
}

/* misc. functions */

// function to validate form elements - @iii
function checkField (formField, fieldTitle, email, errorArea, customErrMsg) {
	element = formField;
	if (element) {
		// check for empty value
		if (trim(element.value).length <= 0) {			
			errorArea.className = " error";
			
			if (customErrMsg) {
			errorArea.innerHTML = customErrMsg;
			} else {
				errorArea.innerHTML = "Please enter the <strong>" + fieldTitle + "</strong>.";
			}
			return false;
			
		} else {
			// validate email format
			if (email) {
				i = element.value.indexOf("@");
			 	j = element.value.indexOf(".",i);
				k = element.value.indexOf(",");
				kk = element.value.indexOf(" ");
				jj = element.value.lastIndexOf(".")+1;
				len = element.value.length;
			
				if ((i>0) && (j>(1+1)) && (k==-1) && (kk==-1) && (len-jj >=2) && (len-jj<=4)) {
					return true;
				} else {
					errorArea.className = " error";
					
					if (customErrMsg) {
					errorArea.innerHTML = customErrMsg;
					} else {
						errorArea.innerHTML = "Please enter the <strong>" + fieldTitle + "</strong>.";
					}
					return false;
				}
				
			} else {
				return true;
			}
		}
	}

}

// function to imitate PHP's trim function - http://www.webtoolkit.info

function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}
 
function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
 
function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}
