window.onload = init;
var emailResult="";

function init() {
	
	setFocus('inpUsername');
	enableMailBlockHandling();
	enableThesaurusBlockHandling('listChars');

} // function init


function enableThesaurusBlockHandling(theId) {

	if(document.getElementById(theId)) {
		var thesBlock = document.getElementById(theId);
		var trArray = thesBlock.getElementsByTagName('TR');
		for(var i = 0; i < trArray.length; i++) {
			if(!(trArray[i].className.indexOf('disabled') > -1)) {
				//trArray[i].className = '';
				trArray[i].className = trArray[i].className.replace(/open/gi, '');
				var linkArray = trArray[i].getElementsByTagName('A');
				var theLinkObj = linkArray[0];
				theLinkObj.onclick = handleThesaurusBlock;
				theLinkObj.style.cursor = 'pointer';
			}
		}
	}
	
} // function enableThesaurusBlockHandling


function handleThesaurusBlock() {
	
	var trNode = this.parentNode.parentNode.parentNode;
	if (trNode.className.indexOf('open') > -1) trNode.className = trNode.className.replace(/open/gi, '');
	else trNode.className = trNode.className + ' open';
	
} // function handleThesaurusBlock


function setFocus(theId) {
	
	if(document.getElementById(theId)) {
		focusedElement = document.getElementById(theId);
		focusedElement.focus();
	}
	
} // function setFocus()


function submitParentForm(formElement) {
    
  if (document.getElementById) {
    formElement.form.submit();
  }
  
} // function submitParentForm


function enableMailBlockHandling (theType, theMode) {
	
	if (document.getElementById('pdfBlock')) {
		var inputArray = document.getElementsByTagName('INPUT');
		for(var i = 0; i < inputArray.length; i++) {
			if(inputArray[i].type == 'radio') {
				inputArray[i].onclick = handleMailBlock;
			}
		}
	}
	
} // function enableMailBlockHandling


function handleMailBlock () {

	var theMode = this.id.substring(this.id.indexOf('_') + 1, this.id.lastIndexOf('_'));
	var theType = this.id.substring(this.id.lastIndexOf('_') + 1, this.id.length);
	var requestetId = 'mailBlock_' + theType;
	var requestetDiv = document.getElementById(requestetId);
	var pseudoId = theType + '_subject';
	var pseudoObject = document.getElementById(pseudoId);
	var inputArray = requestetDiv.getElementsByTagName('INPUT');
	var textareaArray = requestetDiv.getElementsByTagName('TEXTAREA');
	var formObject = document.getElementById('forPDFGenerator_' + theType);

	for(var i = 0; i < inputArray.length; i++) {
		if(inputArray[i].type = 'text') {
			if(theMode == 'download') {
				inputArray[i].disabled = 'disabled';
			} else if(theMode == 'email') {
				inputArray[i].disabled = null;
			}
		}
	}
	for(var j = 0; j < textareaArray.length; j++) {
		if(theMode == 'download') {
			textareaArray[j].disabled = 'disabled';
		} else if(theMode == 'email') {
			textareaArray[j].disabled = null;
		}
	}
	
	if(theMode == 'download') {

		// Email-Block ausblenden
		if(requestetDiv.className.indexOf('hidden') < 0) requestetDiv.className = requestetDiv.className + ' hidden';
		// Hidden-Parameter emailSubject setzen
		pseudoObject.name = 'pseudo';
		pseudoObject.value = '';
		// form target setzen
		formObject.target = '_self';
		// form action setzen
		formObject.action = pdfGeneratorURL_generate;
	} else if(theMode == 'email') {
		// Email-Block einblenden
		if(requestetDiv.className.indexOf('hidden') > -1) requestetDiv.className = requestetDiv.className.replace(/hidden/gi, '');
		// Hidden-Parameter emailSubject setzen
		pseudoObject.name = 'eMailSubject';
		if(theType == 'booklet') {
			pseudoObject.value = eMailSubject_booklet;
		} else if (theType == 'dina4') {
			pseudoObject.value = eMailSubject_dina4;
		}
		// form target setzen
		//formObject.target = 'target_' + theType;
		// form action setzen
		formObject.action = pdfGeneratorURL_email;
	}

	if(document.getElementById('scrollPos')) window.setTimeout ('document.getElementById (\'scrollPos\').focus()', 10);
  if(document.getElementById('scrollPos')) window.setTimeout ('document.getElementById (\'scrollPos\').blur()', 20);

} // function handleMailBlock


function handleSubmit(formName) {

	var theType = formName.substring(formName.indexOf('_') + 1, formName.length);
	var requestedId = 'mailBlock_' + theType;
	var requestedObject = document.getElementById(requestedId);

	if(requestedObject.className.indexOf('hidden') < 0 && theType != "gallery") {
		var isFormOK = checkMandatoryFields(formName);;
		
		if (!isFormOK) alert(mandatoryMessage.unescapeHTML());
		else {
			sendPDF( theType );
		}
	} 
	else {
		document.forms[formName].submit();
	}
	
} // function handleSubmit


function isValidMailAddress(theString) {
	
	var result = true;
	var atPos = theString.indexOf('@');
	var atLastPos = theString.lastIndexOf('@');
	var stringAfterAt = theString.substring(atPos + 1, theString.length);
	var dotLastPos = stringAfterAt.lastIndexOf('.');

	if(atPos < 1) result=false; // enthält kein @ mit mindestens einem Zeichen davor
	if(atPos != atLastPos) result=false; // enthält mehr als ein @
	if(stringAfterAt.indexOf('.') < 1) result=false; // // enthält kein . mit mindestens einem Zeichen davor (hinter dem @)
	if(dotLastPos == stringAfterAt.length - 1) result=false; // enthält kein Zeichen mehr hinter dem letzten Punkt
	
	if (result) return true;
	else return false;
	
} // function isValidMailAddress


function handleEnabling(parDeliveryType) {

	if (document.getElementById('addressForm')) {
		
		var basketForm, isdninput, emailinput, pseudo1, delivery_type;

		if ((parDeliveryType != null) && (parDeliveryType.length > 0)) delivery_type = parDeliveryType;
		else {
			if(document.location.href.indexOf('delivery_type=') > -1) {
				var startPos = document.location.href.indexOf('delivery_type=') + 14;
				var restString = document.location.href.substring(startPos, document.location.href.length);
				if (restString.length > 0) {
					if(restString.indexOf('&') > -1) {
						delivery_type = restString.substring(0, restString.indexOf('&'));
					} else delivery_type = restString;
				}
				else delivery_type = defaultDeliveryType;
			}
			else delivery_type = defaultDeliveryType;
		}

		basketForm = document.getElementById ('forOrderBasket');
		if(document.getElementById('isdninput')) isdninput = document.getElementById ('isdninput');
		if(document.getElementById('emailinput')) emailinput = document.getElementById ('emailinput');
		if(document.getElementById('zipinput')) zipinput = document.getElementById ('zipinput');		

		if(delivery_type == 'cd') {
			$('forOrderBasket').getInputs('text').invoke('enable');
			if(document.getElementById('isdninput')) isdninput.disabled = 'disabled';
			if(document.getElementById('emailinput')) emailinput.disabled = 'disabled';
			if(document.getElementById('zipinput')) zipinput.disabled = 'disabled';
			if(document.getElementById('isdninput')) isdninput.value = '';
			if(document.getElementById('emailinput')) emailinput.value = '';
			if(document.getElementById('zipinput')) zipinput.value = '';
			if(document.getElementById('isdninput') && isdninput.className.indexOf('disabled') < 0) isdninput.className = isdninput.className + ' disabled';
			if(document.getElementById('emailinput') && emailinput.className.indexOf('disabled') < 0) emailinput.className = emailinput.className + ' disabled';
			if(document.getElementById('zipinput') && zipinput.className.indexOf('disabled') < 0) zipinput.className = zipinput.className + ' disabled';
			if ( !$('addressForm').visible()) $('addressForm').show();
		}
		if(delivery_type == 'zip') {
			if ($('addressForm').visible()) $('addressForm').hide();
			if(document.getElementById('isdninput')) isdninput.disabled = 'disabled';
			if(document.getElementById('emailinput')) emailinput.disabled = 'disabled';
			if(document.getElementById('isdninput')) isdninput.value = '';
			if(document.getElementById('emailinput')) emailinput.value = '';
			if(document.getElementById('isdninput') && isdninput.className.indexOf('disabled') < 0) isdninput.className = isdninput.className + ' disabled';
			if(document.getElementById('emailinput') && emailinput.className.indexOf('disabled') < 0) emailinput.className = emailinput.className + ' disabled';
			if(document.getElementById('zipinput')) {
				if ( zipinput.className.indexOf('disabled') > - 1) 
					zipinput.removeClassName('disabled');
			}
			pseudo1 = basketForm.pseudo1;
			pseudo1.value = 'zip';
			pseudo1.name = 'basket_user_deliverytype';
			
			$('forOrderBasket').getInputs('text').invoke('disable');
			$('zipinput').enable().activate();
		}
		if(delivery_type == 'isdn') {
			$('forOrderBasket').getInputs('text').invoke('enable');
			if(document.getElementById('isdninput')) isdninput.disabled = null;
			if(document.getElementById('emailinput')) emailinput.disabled = 'disabled';
			if(document.getElementById('zipinput')) zipinput.disabled = 'disabled';
			if(document.getElementById('emailinput')) emailinput.value = '';
			if(document.getElementById('zipinput')) zipinput.value = '';
			if(document.getElementById('emailinput') && emailinput.className.indexOf('disabled') < 0) emailinput.className = emailinput.className + ' disabled';
			if(document.getElementById('zipinput') && zipinput.className.indexOf('disabled') < 0) zipinput.className = zipinput.className + ' disabled';
			if(document.getElementById('isdninput')) {
				var lastpos = isdninput.className.indexOf('disabled') - 1;
				isdninput.className = isdninput.className.substring(0, lastpos);
			}
			if ( !$('addressForm').visible()) $('addressForm').show();
		}
		if(delivery_type == 'email') {
			$('forOrderBasket').getInputs('text').invoke('enable');
			if(document.getElementById('isdninput')) isdninput.disabled = 'disabled';
			if(document.getElementById('emailinput')) emailinput.disabled = null;
			if(document.getElementById('zipinput')) zipinput.disabled = 'disabled';
			if(document.getElementById('isdninput')) isdninput.value = '';
			if(document.getElementById('zipinput')) zipinput.value = '';
			if(document.getElementById('isdninput') && isdninput.className.indexOf('disabled') < 0) isdninput.className = isdninput.className + ' disabled';
			if(document.getElementById('zipinput') && zipinput.className.indexOf('disabled') < 0) zipinput.className = zipinput.className + ' disabled';
			if(document.getElementById('emailinput')) {
				var lastpos = emailinput.className.indexOf('disabled') - 1;
				emailinput.className = emailinput.className.substring(0, lastpos);
			}
			if ( !$('addressForm').visible()) $('addressForm').show();
		}
		
	}	

} // function handleEnabling

function submitShowSelection(formName) {
	
	var formElement = $( formName );
	var ccatIsSet = false;
	var hiddenFields = formElement.getInputs('hidden','ccat_id');
	var checkboxFields = formElement.getInputs('checkbox','ccat_id');
	// check, if any ccat_ids are selected
	checkboxFields.each(function(cb) {
		if ( cb.checked ) {
			ccatIsSet = true;
		}
	})
	ccatIsSet = ( hiddenFields.length > 0 || ccatIsSet );
		
	var selectedCcat = $('selectedCcatId');
	
	if(!ccatIsSet) {
		// if no ccat_ids are selected - take the currently selected ccat_id
		selectedCcat.name = 'ccat_id';
	} 
	else {
		if ( selectedCcat != null ) {
			$('parent_ccat_id').value = selectedCcat.value;
			selectedCcat.remove();
		}
		
	}
	
	// submit the form
	formElement.submit();
	
} // function submitShowSelection

// checks, whether all mandatory fields (element's class contains 'mandatory') are filled
// if not, we return a message box and mark all missing fields (currently only text-inputs !!!)
function checkMandatoryFields ( formID ) {
	var mandatoryFields = document.getElementsByClassName('mandatory', $(formID));
	var formIsComplete = true;
	var focusSet = false;
	mandatoryFields.each(function check( element ){
		if ( element.type == "text" && !element.present() ) {
			element.addClassName('error');
			formIsComplete = false;
			element.onblur = function (){ if(this.present()) this.removeClassName('error');}
			if ( !focusSet ){
			 element.activate();
			 focusSet = true;
			}
		}
	
	})
	if ( !formIsComplete && formID == "forDownloadGallery_gallery") {
		return confirm(mandatoryMessage.unescapeHTML());
	}
	return formIsComplete;
} // function checkMandatoryFields

function sendPDF( type ) {
	emailResult = 'result_' + type;
	$(emailResult).show();
 	$(emailResult).update(EmailSendStart);
	new Ajax.Request($('forPDFGenerator_' + type).action,
						{method: 'post',
						parameters:  $('forPDFGenerator_' + type).serialize().toQueryParams(),
	         	onSuccess: function(transport) {
	    				var result = $(emailResult);
					    if (transport.responseText.match(/^ok/))
					      result.update(eMailSendSuccess).addClassName('success');
					    else
					      result.update(eMailSendError).addClassName('error');
					    setTimeout("Effect.Fade(emailResult)",10000);
					  },
					  onFailure: function(transport) {
	    				var result = $('result_' + type);
					    if (500 == transport.status)
					      result.update(eMailSendError).addClassName('error');
					  }
					  });
}
