/**   image upload */

var allowedFileTypes = ['gif','jpg','jpeg','png','bmp'];

function uploadImage(obj){
	parent.copyUploadField();
	input = $('imageUploadField');
	v = input.value;
	if(v=='')return;
	p = input.parentNode;
	fileType = v.substr(v.lastIndexOf('.')+1,3);
	if(!in_array(fileType.toLowerCase(),allowedFileTypes)){
		alert('Es sind nur Dateien vom Typ pdf,jpg, gif oder png erlaubt.');
		return;
	}
	fileName = v.substr(v.lastIndexOf('\\')+1,50);
	document.forms['imageUploadform'].submit();
	d = document.createElement('div');
	//htmlString = '<img src="' + v + '" width="40" height="40" />';
	d.innerHTML = '<div id="loadingMessage" > Bild <b>' + fileName + '</b> wird übertragen...</div><img src="typo3conf/ext/gastroportal/res/loading.gif" />';
	$('imageUploadElement').style.display='none';
	$('imageUploadForm').appendChild(d);
	$('imageUploadForm').style.width='350px';
	$('imageUploadForm').style.marginLeft='100px';

}

/**   pdf upload */
var allowedFileTypesPDF = ['pdf'];

function uploadPDF(obj){
	parent.copyUploadField();
	input = $('imageUploadField');
	v = input.value;
	if(v=='')return;
	p = input.parentNode;
	fileType = v.substr(v.lastIndexOf('.')+1,3);
	if(!in_array(fileType.toLowerCase(),allowedFileTypesPDF)){
		alert('Es sind nur Dateien vom Typ PDF erlaubt.');
		return;
	}
	fileName = v.substr(v.lastIndexOf('\\')+1,50);
	document.forms['imageUploadform'].submit();
	d = document.createElement('div');
	//htmlString = '<img src="' + v + '" width="40" height="40" />';
	d.innerHTML = '<div id="loadingMessage" > Die Datei <b>' + fileName + '</b> wird übertragen...</div><img src="typo3conf/ext/gastroportal/res/loading.gif" />';
	$('imageUploadElement').style.display='none';
	$('imageUploadForm').appendChild(d);
	$('imageUploadForm').style.width='350px';
	$('imageUploadForm').style.marginLeft='100px';

}

function resizeIframe(i,size){
	if(size == 'big')$('imageUploadFormWrapper_' + i).style.height = '120px';
	else $('imageUploadFormWrapper_' + i).style.height = '70px';
}

function resizeIframe2(i,size){
	if(size == 'big')$('imageUploadFormWrapper_' + i).style.height = '150px';
	else $('imageUploadFormWrapper_' + i).style.height = '70px';
}

function copyUploadField(){
		if(imageNumber >= maxImages)return;
		/*
		tmp = $$('.imageUploadFormWrapper');
		clone = tmp[0].cloneNode(true);
		tmp[0].parentNode.appendChild(clone);
		*/
		d = document.createElement('div');
		d.innerHTML = '<div class="imageUploadFormWrapper" id="imageUploadFormWrapper_' + imageNumber + '"><iframe style="border:1px solid #FFF;" frameborder="0" class="imageUploadIframe"  name="uploadIframe' + imageNumber + '" src="'+ iframeSrc + '?' + prefixId + '[iframe]=1&' + prefixId + '[n]=' + imageNumber + '" ></iframe></div>';
		$$('.tx-gastroportal-pi1')[0].appendChild(d);
		imageNumber ++;
}
/*    arrangement selector     */

var selectedItems = [];
var map;
var errorLabels = {
		'required' : 'Dieses Feld muss ausgefüllt werden!',
		'num' : 'Es können nur Zahlen eintragen werden!',
		'alphanum_x' : 'Der Eintrag enthält ungültige Zeichen!',
		'email' : 'Ungültige Mailadresse!',
		'phone' : 'Ungültige Telefon-Nummer (Bitte nur Zahlen sowie + oder - oder / eingeben)!',
		'zip' : 'Ungültige Postleitzahl!',
		'twice' : 'Die Passwörter stimmen nicht überein!',
		'nothingSelected' : 'Es muss eine Auswahl getroffen werden',
		'agb' : 'Sie müssen die Geschäftsbedingungen akzeptieren'
};

/*
var W3CDOM = (document.createElement && document.getElementsByTagName);

function initFileUploads() {
	if (!W3CDOM) return;
	var fakeFileUpload = document.createElement('div');
	fakeFileUpload.className = 'fakefile';
	fakeFileUpload.appendChild(document.createElement('input'));
	var image = document.createElement('img');
	image.src='typo3conf/ext/gastroportal/res/button_select.gif';
	fakeFileUpload.appendChild(image);
	var x = document.getElementsByTagName('input');
	for (var i=0;i<x.length;i++) {
		if (x[i].type != 'file') continue;
		if (x[i].parentNode.className != 'fileinputs') continue;
		x[i].className = 'file hidden';
		var clone = fakeFileUpload.cloneNode(true);
		x[i].parentNode.appendChild(clone);
		x[i].relatedElement = clone.getElementsByTagName('input')[0];
		x[i].onchange = x[i].onmouseout = function () {
			this.relatedElement.value = this.value;
		}
	}
}
*/


function processDeselectedValue(id,v,l,index){
	s = $('rightSelectorA' + id);
	leftSel = $('leftSelectorA' + id);
 	s.options[s.length] = new Option(l,v,false,false);
	leftSel.options[index] = null;
	$('A' + id + '_counter').innerHTML = leftSel.length;
	removeHiddenFormElem('selected' + id + v);
	
	
}


function processSelectedValue(id,v,l,index){
	s = $('leftSelectorA' + id);
 	s.options[s.length] = new Option(l,v,false,false);
	$('rightSelectorA' + id).options[index] = null;
	$('A' + id + '_counter').innerHTML = s.length;
	addHiddenFormElem('selected' + id + v, 'tx_gastroportal_pi1[selectedVantages][' + id + '][vantages][]',v);
 	
}

function processBonusValue(s){
	var f = $$('.tx_formslib_neu-field ');
	
	f[f.length-1].value = s;
}

function addBonusRow(){
		var tableElement = $('bonusTable');
		newRow = tableElement.insertRow(-1)
		newCell1 =newRow.insertCell(-1);
		newCell2 = newRow.insertCell(-1);
		newCell1.innerHTML = '<input type="text" name="tx_gastroportal_pi1[tx_gastroportal_bonus][score][]" value=""  class="tx_formslib_neu-field tx_formslib_neu-field-normal"  size="3" onfocus="checkError(this)" onblur="checkField(this,\'num\')"/>';
		newCell2.innerHTML = '<input type="text" name="tx_gastroportal_pi1[tx_gastroportal_bonus][name][]" value=""  class="tx_formslib_neu-field tx_formslib_neu-field-normal"  size="50"  onfocus="checkError(this)"/>';	
		return false;
}

function showPanel(id,obj){
	if($(id).style.display == ''){
			if(id.indexOf('A') > -1){
				if(!checkArrangementItem(id.substr(1,1)))return false;
			}
			$(id).style.display = 'none';
			obj.id = '';
	}
	else {
			$(id).style.display = '';
			//obj.id = 'url(typo1/typo3conf/ext/res/res/minus.gif)';
			obj.id = 'activeLink';
	}
	return false;
}

function checkArrangementForm(){
	errormessage = '';
	for(var i=1;i<6;i++){
		if(!checkArrangementItem(i)){
			$('A' + i).style.display = '';
			$('arrangementItem_' + i).style.border = '2px solid red';
			return false;
		}
	}
	return true;
}

function checkArrangementItem(i){
	errormessage = '';
	s = $('leftSelectorA' + i);
	if(s.options.length > 0){
		if(s.options.length <1){
			errormessage += 'Ein Arrangement muss mindestens 3 Vorteile beinhalten.';
		}
		inputs = $$('.inputA' + i);
		firstemptyField = true;
		for (var p = 0;p < inputs.length;p++){
			if(isNaN(inputs[p].value) || inputs[p].value<1){
				inputs[p].style.border = '2px solid red';
				if(firstemptyField){
					errormessage += "\nEs müssen alle Zimmerpreise für ein Arrangement ausgefüllt werden";
					firstemptyField = false;
				}
			}
		}
		if(errormessage!=''){
			alert(errormessage);
			return false;
		}
	}
	return true;
}



/*      company code       */

function sendVars(vars){
		//var _this = this; // don't overload the meaning of 'this'
		var url = window.location.href;
		varstring = '';
		//if(url.indexOf('?')>-1)varstring = '';
		//else varstring = '?';
		vars['ajaxRequest'] = 1;
		for (var key in vars){
			if(typeof vars[key] !='function'){
				varstring += 'tx_gastroportal_pi1[' + key + ']=' + escape(vars[key]) + '&';
			}
		}
		myAjax = new Ajax.Request( url, { method: 'post', parameters: varstring, onComplete:eval('display' + vars['action'])});
}

function getCompanyCode(){
	vars = [];
	vars['companyCode'] = $F('companyCodeField').toUpperCase();
	vars['action'] = 'CompanyInfo';
	if(vars['companyCode'].length < 3 || vars['companyCode'].length > 3){
		alert('Ein Firmencode besteht aus genau 3 Buchstaben');
		return false;
	}
	else if($(vars['companyCode'])){
		alert('Dieser Firmencode ist bereits in der Liste');
		return false;
	}
	else sendVars(vars);
	return false;
}

function displayCompanyInfo(request){
		$('companyInfoContainer').innerHTML = request.responseText;
}

function checkCompanyRatesForm(){
	inputs = $$('.tx_formslib_neu-field ');
	firstErrorInput = null;
	for(var i = 0;i<inputs.length;i++){
		if(inputs[i].type == 'text'){
			var v = inputs[i].value;
			if(isNaN(v) || v < 1){
				if(!defaultBorder){
					defaultBorder = inputs[i].style.border;
				}
				inputs[i].style.border = '2px solid red';
				if(!firstErrorInput)firstErrorInput = inputs[i];
			}
		}
	}
	if(firstErrorInput){
		alert('Es müssen alle Zimmerpreise korrekt ausgefüllt werden!');
		firstErrorInput.focus();
		return false;
	}
	return true;
}



function deleteCompanyRate(c,s,code,codeId, obj){
	//deleteRow(obj.parentNode.parentNode.rowIndex);
	x = confirm(s);
	if(x){
		vars = [];
		$('companyRateListTable').deleteRow(obj.parentNode.parentNode.rowIndex + 1);
		$('companyRateListTable').deleteRow(obj.parentNode.parentNode.rowIndex);
		removeHiddenFormElem('hiddenField' + c);
		removeHiddenFormElem(code);
		vars['companyCode'] = codeId;
		vars['action'] = 'deleteCompanyRate';
		sendVars(vars);
		return false;
	}
	return false;
}

// dummy function, no output needed
function displaydeleteCompanyRate(){
}
	
	

/*
* Helper function for adding hidden form elements
*
*
*/

function addHiddenFormElem(id,name,value){
		form = document.getElementById('arrForm')
		el = document.createElement('input');
		typeAttr = document.createAttribute('type');
		typeAttr.nodeValue = "hidden";
		nameAttr = document.createAttribute('name');
		nameAttr.nodeValue = name;
		valueAttr = document.createAttribute('value');
		valueAttr.nodeValue = value;
		idAttr = document.createAttribute('id');
		idAttr.nodeValue = id;
		
		el.setAttributeNode(typeAttr);
		el.setAttributeNode(nameAttr);
		el.setAttributeNode(valueAttr);
		el.setAttributeNode(idAttr);
		form.appendChild(el);
}
		
function removeHiddenFormElem(id){	
	hiddenField = document.getElementById(id);
	if(!hiddenField)alert("hiddenField not found:id - " + id ); 
	hiddenField.parentNode.removeChild(hiddenField);
}


function addHonorField(){
		var tableElement = $('honorsTable');
		newRow = tableElement.insertRow(-1)
		newCell1 =newRow.insertCell(-1);
		newCell2 = newRow.insertCell(-1);
		newCell1.innerHTML = '<input type="text" name="tx_gastroportal_pi1[data][tx_gastroportal_honors][honor][]" value=""  class="tx_formslib_neu-field tx_formslib_neu-field-normal"  size="30" />';
		newCell2.innerHTML = '<input type="text" name="tx_gastroportal_pi1[data][tx_gastroportal_honors][publisher][]" value=""  class="tx_formslib_neu-field tx_formslib_neu-field-normal"  size="30" />';

		
}


/*   wizard function   */

var f; // wizard window
var m; // map marker

function googleWizard(flexmap_path,params){
	params += '&lon=' + $F('tx_gastroportal_pi1_tx_gastroportal_restaurant_lon') + '&lat=' + $F('tx_gastroportal_pi1_tx_gastroportal_restaurant_lat');
	if(!f || f.closed){
		//relExtPath=' + encodeURI(flexmap_path) + '&
		f = window.open('http://' + window.location.host + '/' + flexmap_path + 'res/class.tx_googlemap_wizard.php?' + params,'wizard',"width=500,height=490,left=150,top=150,resizable=yes,scrollbars=yes");
	}
	f.focus();
}


function getEl(el){
	return document.getElementById(el);
}



function loadMap(){
	

	map = new GMap2(getEl('mapcontainer'));
	
	getEl('final_address').value = getValue('address') + ', ' + getValue('zipcode') + ' ' + getValue('city');
	
	hasCoordinates = false;
	latitude = getEl('lat').value;
	longitude = getEl('lon').value;
	
	if(latitude != '' && longitude != ''){
		 zoomlevel = 16;
		 hasCoordinates = true;
	}
	else {

		latitude = 51;
		longitude = 9;
		zoomlevel = 6;
	}
		
	showMarker = false;
	
	p = new GLatLng(latitude,longitude);
	map.setCenter(p, zoomlevel);
	map.addControl(new GLargeMapControl());	
	m = new GMarker(p,{draggable: true});
	map.addOverlay(m);

	GEvent.addListener( m, 'dragend', function(){
		updateCoordinates(this.getPoint());
	});

	if(getEl('final_address').value != '' && !hasCoordinates)getAddress();

}


function getAddress() {
	address = getEl('final_address').value;
	geocoder.getLatLng(address,function(point) {
     		 		if (!point) {
        				alert(address +  ' not found');
      	 		} 
			 		else {
							getEl('lat').value = point.y;
							getEl('lon').value = point.x;
							if(m){
								map.setCenter(point, 16);
								m.setPoint(point);
							}
							else addMarker(point);
					}
     		}
	);
}


function updateCoordinates(point){
		getEl('lat').value = point.y;
		getEl('lon').value = point.x;
}



function performUpdate(){

	opener.focus();
	opener.$('tx_gastroportal_pi1_tx_gastroportal_restaurant_lat').value = getEl('lat').value;
	opener.document.getElementById('tx_gastroportal_pi1_tx_gastroportal_restaurant_lon').value = getEl('lon').value;
	window.close();
}

function getValue(key){
	return opener.document.getElementById('tx_gastroportal_pi1_tx_gastroportal_restaurant_' + key).value;
}



