/*
 * --------------------------------------------------------------------------------------------------------------------
 * Guestbook entries add functions
 * --------------------------------------------------------------------------------------------------------------------
 */
/**
 * Add/Edit guestbookentry field ids array, indicates if the field is an required one or not and if it is deletable
 * array (array1 (fieldID1, isRequired1, isDeletable1), array2 (fieldID2, isRequired2, isDeletable2), ...)
 * @type {Array}
 */
var arrGuestbookentryFields = Array(   Array ('Guestname', 1, 1),
									   Array ('Guestemail', 1, 1), 
									   Array ('Homepage', 0, 1),
									   Array ('Message', 1, 1));	
									   
								  							   
function InitAddScript(pRootUrl){
	sRootUrl = pRootUrl;
};

/**
 * Form fields format functions
 * 
 * @param {String}  pFieldId			: id of the input field
 * @param {Integer} pValidationError	: 1 if the field is requiered, else 0
 * @param {Integer} pDeleteValue		: 1 if the field can be deleted (not deletable for example an select box), else 0
 * @param {Integer} pApplyReadOnly		: 1 if the field is read only, else 0
 */
function FormatFormField (pFieldId, pValidationError, pDeleteValue, pApplyReadOnly) {

	// get field
	var _oField = document.getElementById(pFieldId);

	if(_oField.type != 'hidden'){
		// instead of checking if the styles are set or not to do
		// the appropriate actions we simply remove read only and validation 
		// error styles first
		_oField.className = _oField.className.replace('readOnly', '');
		_oField.className = _oField.className.replace(' readOnly', '');
		_oField.className = _oField.className.replace('validationError', '');
		_oField.className = _oField.className.replace(' validationError', '');
	
		// check if the field has to be displayed with the validation error style
		if(pValidationError == 1){
			// apply validation error style
			_oField.className += " validationError";
		} else {
			// check if the field is readonly and do the appropriate actions
			if(_oField.readOnly == true && pApplyReadOnly){
				// apply read only style
				_oField.className = _oField.className + " readOnly";
			}
		}
		
		// finally remove field value according to the given parameter
		if (_oField.type.search(/select/) != -1 && pDeleteValue){
			EmptyListbox(document.getElementById(pFieldId));
		}
		if (_oField.type.search(/text/) != -1 && pDeleteValue){
			_oField.value = '';
		}
		if (_oField.type.search(/password/) != -1 && pDeleteValue){
			_oField.value = '';
		}
		
	} else {
		if(pDeleteValue){
			var _oEditor = FCKeditorAPI.GetInstance(pFieldId);
			_oEditor.SetHTML('');
		}
	}
};

function DisplayValidationErrors(pArrayXMLError) {
	
	if(pArrayXMLError.length > 0){
		
		var _sMessage = '';			
		for (var i = 0; i < pArrayXMLError.length; i++) {
			
			var _sFieldName = pArrayXMLError[i].getElementsByTagName('property_name').item(0).firstChild.nodeValue;
			try{
				_sMessage += ':: ' + pArrayXMLError[i].getElementsByTagName('message').item(0).firstChild.nodeValue + '<br />';
			}catch(e){}

			// highlight the field where the error occured
			FormatFormField(_sFieldName, 1, 0, 0);
		}
		document.getElementById('errorContent').innerHTML = _sMessage;
		ShowBlockElement('errorBox');
	}
};

function InitFormFields (pDeleteValues) {
	
	for (var i = 0; i < arrGuestbookentryFields.length; i++) {
		if(arrGuestbookentryFields[i][2] == 0){
			FormatFormField (arrGuestbookentryFields[i][0], 0, 0, 1);
		} else {
			FormatFormField (arrGuestbookentryFields[i][0], 0, pDeleteValues, 1);
		}
	}
};

/**
 * Init the request object to make an guestbookentry add request
 * 
 */
function AddGuestbookentry () {
	iGuestbookentryID = 0;
	if(CreateXMLHttpRequest()){
    	RequestSaveGuestbookentry();
    }
};

/**
 * Build the Url and does the http request to do save a guestbookentry (Save new or existent)
 * 
 */
function RequestSaveGuestbookentry() {
	// build Url
	var _sUrl = sRootUrl;
	// build param string to send by Post
	var _sPost = 'module=guestbook&page=ajax&action=add';
	_sPost += '&Guestname=' + escape(document.getElementById('Guestname').value);
	_sPost += '&Guestemail=' + escape(document.getElementById('Guestemail').value);
	_sPost += '&Guesthomepage=' + escape(document.getElementById('Homepage').value);
	_sPost += '&Message=' + escape(document.getElementById('Message').value);
	_sPost += '&SCode=' + escape(document.getElementById('SCode').value);
	//document.getElementById('Test').innerHTML = _sUrl + "?" + _sPost;
	// Execute the request
	oHttpRequest.onreadystatechange = DisplayGuestbookentryValidationErrors;
	oHttpRequest.open('post', _sUrl, true);
	oHttpRequest.setRequestHeader('Content-type', 'application/x-www-form-urlencoded; charset=iso-8859-1');
	oHttpRequest.setRequestHeader('Content-length', _sPost.length);
	oHttpRequest.send(_sPost);	
};

/**
 * Guestbookentry data save http request callback function
 * 
 */
function DisplayGuestbookentryValidationErrors() {
	
	if (oHttpRequest.readyState == 4) {
		if (oHttpRequest.status == 200) {
			
			// put response into xmlobject
			var _xmlDoc = oHttpRequest.responseXML;
			// init variable number of errors
			var _iNbrErrors = 0;
			// get the number of errors from the xml response
			_iNbrErrors = _xmlDoc.documentElement.getElementsByTagName('nbr_errors').item(0).firstChild.nodeValue;
		
			if (_iNbrErrors > 0){
				InitFormFields(0);
				// loop through the returned validation errors and highlight the errors in the template			
				var _arrXmlData = _xmlDoc.documentElement.getElementsByTagName('error');
				DisplayValidationErrors(_arrXmlData);
				
			} else {
				// guestbook entry added go back to listing
				iGuestbookentryID = _xmlDoc.documentElement.getElementsByTagName('guestbook_entry_id').item(0).firstChild.nodeValue;
				window.location = sRootUrl + '?module=guestbook&page=entries';
			}
		} else {
			alert('Bei dem Request ist ein Problem aufgetreten.');
		}
	}
};
