
/**
 * Opodien functions - main resource of opodien JavaScript functions
 * @author	opodo
 * @package	Opodien
 */


/**
 * debug helper function - adds a message to #log
 * @return void
 * @param string title
 * @param string val
 */
function log (title, val) {
	if (DEBUG) $('#log').prepend('<table cellspacing="0" cellpadding="0"><tr><td class="head">' + title + '</td><td>' + val + '</td</tr</table>');
	//console.log(title + ": " + val);
}

/**
 * checks if a DOM item exists
 * @return bool
 * @param string id
 */
function itemExists(id) {
	var len = $(id).length;
	if (len > 0) {
		return true;
	} else {
		return false;
	}
}

/**
 * truncates a string and attaches '...' if necessary
 * @param string subject
 * @param string limit
 */
function limitChars(subject, limit) {
	if (subject && limit > 0) {
		if (subject.length > limit) subject = subject.substr(0,limit) + '...';
	}
	return subject;
}


/**
 * hides opo_main_googlemaps extension when an error pod exists on the page
 * @return void
 */
function checkErrorPods() {
	var errorpod = $(".mainguide_error").html();
	if (errorpod) {
		$('.tx-opomaingooglemaps-pi1').hide();
	} else {
		$('.tx-opomaingooglemaps-pi1').show();
	}
}


/**
 * puts a tag in all available tag fields of each user item
 * @return void
 * @param string tag
 * @todo dupe check
 */
function assignTags(tag) {
	if (tag.length > 0) {
		$('.gallery_image .tags input').each( function() {
			var oldvalue = this.value;
			if (oldvalue.length > 0) {
				this.value = this.value + ' ' + tag;
			} else {
				this.value = tag;
			}
		});
	}
}

/**
 * replaces all tags in all available tag fields of each user item
 * @return void
 * @param string tag
 */
function replaceTags(tag) {
	$('.gallery_image .tags input').each( function() {
		this.value = tag;
	});
}


/**
 * gets the number from a string like "useritem-123"
 * @return string field number
 * @param string field_id
 */
function getFieldNumber(field_id) {
	var pos_slice = '';
	var field_number = '';
	if (field_id) {
		pos_slice = field_id.indexOf('-');
		if (pos_slice > 1) {
			field_number = field_id.substring(pos_slice + 1, field_id.length);
		}
	}
	return field_number;		
}



/**
 * invokes an ajax request and puts the json response to the select inputs via deserialize plugin
 * this is used on manual geo search and on clicking the geo drill selectboxes
 * 
 * @return void
 * @param string id id of the object that was clicked
 * @param string entity usually "geo_continent|geo_country|geo_region|geo_city" - may contain "_item-123" suffix
 * @param bool submit if true, form is submitted after dispatching ajax request
 * @param string formname name of the form that should be submitted (only if "submit" is true), defaults to "myopodien_form"
 * @see updateGeobox()
 * @see setModRewriteFoundation()
 * @see updateAllFields()
 * @see dehighlightError()
 */
function updateGeoboxSelection(id, entity, submit, formname) {
	if (!formname && $('#' + entity)[0]) {
		formname = $('#' + entity)[0].form.id;
	}
	if (!formname) formname = 'myopodien_form'; //default form
	var formnametemp = formname;
	
 	//alert('formname initial: ' + formname);
	
	log('updateGeoboxSelection', id + ':' + entity);
	var suffix = '';
	var geoall = '';
	var query = '';
	//var entity = 'geo_city';

	//if the user has clicked a "per item" geo assign selectbox...
	//alert('entity: ' + entity);
	var field_number = getFieldNumber(entity);
	var field_number_suffix = '';
	if (field_number) {
		field_number_suffix = '-' + field_number;
		suffix = '_item' + field_number_suffix;
	}

	//remove highlighting
	geoall = getGeoAllStatus();
	dehighlightError('geobox_edit' + suffix, '.geo_search_edit_item');
	dehighlightError('geobox_edit' + suffix, '.geo_country_item');

	var query = "&id=" + id + "&entity=" + entity + "&suffix=" + suffix;
	log("query: ", query);

	$.ajax({
		type: "POST",
		url: BASEDIR + "/ajax_geosearch.php",
		data: "mode=geobox" + query,
		success: function(msg){
			log("ajax response", msg);

			//alert("update");

			var result = eval("data=" + msg);

			//alert('deserializing form: ' + formnametemp);
			$('#' + formnametemp).deserialize(result);

			$('#response_indicator_image' + field_number_suffix).hide();

			var geo_continent = result['items']['geo_continent'];
			var geo_country = result['items']['geo_country'];
			var geo_region = result['items']['geo_region'];
			var geo_city = result['items']['geo_city'];
			
			//input was found (by text or by selectbox)
			if ((geo_country > 0) || (geo_region > 0) || (geo_city > 0) || (geo_continent > 0 && $('#geo_search_edit' + field_number_suffix).is('.geo_search_edit_item_countryonly') )) {
				if ((getItemStatus(field_number_suffix) == '') || (getItemStatus(field_number_suffix) == 'reset')) {
					//OK - no selection present -> go to country, region or city selection
					log('showing', '#geo_response_ok' + field_number_suffix);
					setGeoStatus('ok', field_number_suffix);
					//apply this to all other items (user backend)
					if (geoall == 1) updateAllFields(geo_continent, geo_country, geo_region, geo_city, 'ok');
				}
				if (getItemStatus(field_number_suffix) == 'error') {
					//SUGGEST OK - there was an error before, but a country was selected now:
					setGeoStatus('suggest_ok', field_number_suffix)
					
					//append the selected country string to the search string
					var labelstr = '';
					
					if ($('#geo_search_edit' + field_number_suffix).is('.geo_search_edit_item_countryonly')) {
						var continent_name = $('#geo_continent' + suffix + ' option:selected').text();
						labelstr = ', ' + continent_name;
					} else {
						var country_name = $('#geo_country' + suffix + ' option:selected').text();
						labelstr = ', ' + country_name;
					}
					appendGeoboxLabel('#geobox_edit' + suffix, labelstr);
					
					if (geoall == 1) updateAllFields(geo_continent, geo_country, geo_region, geo_city, 'suggest_ok');
				}
			} else {
				/*
					// suggestion for country only geoboxes
				if (geo_continent > 0
					&& getItemStatus(field_number_suffix) == 'error'
					&& $('#geo_search_edit' + field_number_suffix).is('.geo_search_edit_item_countryonly')) {
						//SUGGEST OK - there was an error before, but a continent was selected now:
						//this is a "country only" geobox field
						setGeoStatus('suggest_ok', field_number_suffix)
						
						//append the selected country string to the search string
						var continent_name = $('#geo_continent' + suffix + ' option:selected').text();
						var labelstr = ', ' + continent_name;
						appendGeoboxLabel('#geobox_edit' + suffix, labelstr);
				} else {
				*/
				if (geo_continent <= 0) {
					//ERROR - text input was not found (show an error message) or "reset" the box
					if ($('#geo_search_edit' + field_number_suffix).is('.geo_search_edit_item_countryonly')) {
						setGeoStatus('reset', field_number_suffix);
					} else {
						setGeoStatus('error', field_number_suffix);
					}
					if (geoall == 1) updateAllFields(geo_continent, geo_country, geo_region, geo_city, 'error');
				}
			}
			if (submit == true) {
				var formname = formnametemp;

				//reiseziele_form is not submitted, instead the values written into opodien_form are submitted
				if (formname == 'reiseziele_form') {
					formname = 'opodien_form';
				}
				
				//alert("submitting form " + formname)
				setModRewriteFoundation();
				$('#' + formname).submit();
			}
		}
	});
}

/**
 * sets the selected geostructure direcly - this function acts as a callback for the
 * autocompleter "on_result_select" for the geo search field
 * 
 * @return void
 * @param {Object} event
 * @param {Object} data
 * @param {Object} formatted
 * @param {Object} field_id
 * @param {Object} submit
 * @param {Object} formname
 */
function updateModrewriteForm(event, data, formatted, field_id, submit, formname) {
	
	var name= data[0];
	var id = data[1];
	var entity = data[2];

	$('#geo_button_search').hide(); //hide search button
	$('#geo_button_select').hide(); //hide select button, because the page is going to be refreshed
	$('#geoboxsearch #response_indicator_image').show(); //show indicator
	var query = "&id=" + id + "&entity=" + entity;

	$.ajax({
		type: "POST",
		url: BASEDIR + "/ajax_geosearch.php",
		data: "mode=geobox" + query,
		success: function(msg){
			log("ajax response", msg);

			var result = eval("data=" + msg);

			var geo_continent_namesimple = result['items']['geo_continent_namesimple'];
			var geo_country_namesimple = result['items']['geo_country_namesimple'];
			var geo_region_namesimple = result['items']['geo_region_namesimple'];
			var geo_city_namesimple = result['items']['geo_city_namesimple'];

			var geostructure = '';
			if (geo_continent_namesimple) geostructure = geostructure + geo_continent_namesimple + '/';
			if (geo_country_namesimple) geostructure = geostructure + geo_country_namesimple + '/';
			if (geo_region_namesimple) geostructure = geostructure + geo_region_namesimple + '/';
			if (geo_city_namesimple) geostructure = geostructure + geo_city_namesimple + '/';
	
			var pagekey = $('input[@name=pagekey]').fieldValue();
			 
			$('#opodien_form').attr('action', pagekey + '/' + geostructure);
			$('#opodien_form').submit();

		}
	});	
}


/**
 * gets the selected geostructure of the navi_geo fe-plugin and constructs the action parameter
 * of the form to match mod_rewrite conditions
 * 
 * @return void
 * @see geoNameSimplify()
 */
function setModRewriteFoundation() {
		var continent_name = '';
		var country_name = '';
		var region_name = '';
		var city_name = '';
		
		var continent_id = $('#geo_continent').fieldValue();
		var country_id = $('#geo_country').fieldValue();
		var region_id = $('#geo_region').fieldValue();
		var city_id = $('#geo_city').fieldValue();

		var geostructure = '';
		
		if (continent_id > 0) {
			continent_name = geoNameSimplify($('#geo_continent option:selected').text());
			geostructure = geostructure + continent_name + '/';
		}
		if (country_id > 0) {
			country_name = geoNameSimplify($('#geo_country option:selected').text());
			geostructure = geostructure + country_name + '/';
		}
		if (region_id > 0) {
			region_name = geoNameSimplify($('#geo_region option:selected').text());
			geostructure = geostructure + region_name + '/';
		}
		if (city_id > 0) {
			city_name = geoNameSimplify($('#geo_city option:selected').text());
			geostructure = geostructure + city_name + '/';
		}			

		var pagekey = $('input[@name=pagekey]').fieldValue();
		$('#opodien_form').attr('action', pagekey + '/' + geostructure);
}

/**
 * simplifies a geo location name for usage in an URL (must be the same as corresponding backend function!)
 * 
 * @return string
 * @param string str
 * @see replace_accents()
 */
function geoNameSimplify(str) {
	var newstr = str;
	newstr = newstr.replace(/ /g, '-');
	newstr = newstr.replace(/&/g, '+');
	newstr = newstr.replace(/ß/g, 'ss');
	newstr = newstr.replace(/ä/g, 'ae');
	newstr = newstr.replace(/ü/g, 'ue');
	newstr = newstr.replace(/ö/g, 'oe');
	newstr = newstr.replace(/Ä/g, 'Ae');
	newstr = newstr.replace(/Ö/g, 'Oe');
	newstr = newstr.replace(/Ü/g, 'Ue');
	newstr = newstr.replace(/\//g, '-');
	newstr = newstr.replace(/,/g, '-');
	newstr = newstr.replace(/[(]/g, '');
	newstr = newstr.replace(/[)]/g, '');
	newstr = newstr.replace(/[.]/g, '');
	newstr = newstr.replace(/'/g, '');
	newstr = replace_accents(newstr);
	newstr = newstr.toLowerCase();
	return newstr
}

/**
 * replaces all accents in the given string (must be the same as corresponding backend function!)
 * (C)Stephen Chalmers - Strips grave, acute & circumflex accents from vowels
 * @return string
 * @param string str
 */
function replace_accents(str) {
	var s=str;
	// http://www.asciizeichen.de/tabelle.html
	var rExps=[ 
	/[\xC0-\xC6]/g, /[\xE0-\xE6]/g,  // A a
	/[\xC7]/g, /[\xE7]/g,  // C c
	/[\xC8-\xCB]/g, /[\xE8-\xEB]/g,  // E e
	/[\xCC-\xCF]/g, /[\xEC-\xEF]/g,  // I i
	/[\xD0]/g, /[\xE0]/g,  // D d
	/[\xD2-\xD8]/g, /[\xF2-\xF8]/g,  // O o
	/[\xD9-\xDC]/g, /[\xF9-\xFC]/g,   // U u
	/[\xDD]/g, /[\xFD]/g,  // Y y
	/[\xDE]/g, /[\xFE]/g,  // T t
	/[\xDF]/g, /[\xFF]/g   // ss 
	]; 
	var repChar=['A','a','C','C','E','e','I','i','D','d','O','o','U','u','Y','y','T','t','ss','ss'];
	for(var i=0; i<rExps.length; i++)
	  s=s.replace(rExps[i],repChar[i]);
	return s;
}


/**
 * checks if the DOM flag is set whether geo matching made on the first item should be applied on all other items
 * @return bool
 * @see setGeoAllStatus()
 */
function getGeoAllStatus() {
	var geoall = $('input[@name=geoall]').fieldValue();
	return geoall;
}

/**
 * sets the DOM flag to apply the geo matching made on the first item to all other items
 * @return void
 * @param string status
 * @see getGeoAllStatus()
 */
function setGeoAllStatus(status) {
	log('setting geoall status', status);
	if (status == 0) {
		$('#geoall_applyall').hide();
	} else {
		$('#geoall_applyall').show();
	}
	$('input[@name=geoall]').setValue(status);
}

/**
 * sets the input forms to starting values
 * @return void
 */
function resetOnLoad() {
/*
	$('.geo_status').setValue('');
	$('input[@name=geoall]').setValue(0);
	$('.tx-myopodien-pi1 .geo_country_item').setValue('0');
	//$('.tx-myopodien-pi1-userreports .geo_country_item').setValue('0');
	//$('.tx-myopodien-pi1-usertips .geo_country_item').setValue('0');
	$('textarea.geo_edit_name').setValue('');
	replaceTags('');
*/
}

/**
 * show/hides input elements based on response status of the geo matching request
 * @return void
 * @param string status "ok|error|suggest_ok|reset"
 * @param string field_number_suffix identifies the current item by "-123"
 * @see setItemStatus()
 */
function setGeoStatus(status, field_number_suffix) {
	$('.geo_editall_message').hide();

	setItemStatus(field_number_suffix, status);
	
	if (status == 'ok') {
		log('state ok suffix:',  field_number_suffix);
		setGeoAllStatus(0);
		var geoall = getGeoAllStatus();
		$('#geo_response_danke' + field_number_suffix).hide();
		$('#geo_response_error' + field_number_suffix).hide();
		$('#geo_response_listselection' + field_number_suffix).hide();
		$('#geo_search_edit' + field_number_suffix).hide(); //search field
		$('#geo_button_apply' + field_number_suffix).hide(); //apply button
		$('#geo_sample_text' + field_number_suffix).hide(); //sample code
		$('#geobox_edit_item' + field_number_suffix).show();
		$('#geo_response_ok' + field_number_suffix).show();
	}
	
	if (status == 'error') {
		var geoall = getGeoAllStatus();
		log('status error for', field_number_suffix);
		$('#geo_response_ok' + field_number_suffix).hide(); 
		$('#geo_response_danke' + field_number_suffix).hide(); 
		$('#geo_response_error' + field_number_suffix).show();
		if ((geoall == '') || ((geoall=='1') && (field_number_suffix == ''))) $('#geo_response_listselection' + field_number_suffix).show(); //show listselection at master image only
		$('#geoall_applyall').hide();
		$('#geo_search_edit' + field_number_suffix).hide(); //search field
		$('#geo_button_apply' + field_number_suffix).hide(); //apply button
		$('#geo_sample_text' + field_number_suffix).hide(); //sample code
		if ((geoall == '1') && (field_number_suffix != '')) $('#geo_change3' + field_number_suffix).hide(); //no "change" linnk for non-master images
		if ((geoall == '1') && (field_number_suffix != '')) $('#error_hint' + field_number_suffix).hide();
	}
	
	if (status == 'suggest_ok') {
		var geoall = getGeoAllStatus();
		log('status suggest ok for', field_number_suffix);
		$('#geo_response_ok' + field_number_suffix).hide();
		$('#geo_response_danke' + field_number_suffix).show();
		$('#geo_response_error' + field_number_suffix).hide();
		$('#geo_response_listselection' + field_number_suffix).hide();
	}
	
	if (status == 'reset') {
		$('#geo_response_danke' + field_number_suffix).hide();
		$('#geo_response_error' + field_number_suffix).hide();
		$('#geo_response_listselection' + field_number_suffix).hide();
		$('#geo_search_edit' + field_number_suffix).show(); //search field
		$('#geo_button_apply' + field_number_suffix).show(); //apply button
		$('#geo_sample_text' + field_number_suffix).show(); //sample code
		$('#geobox_edit_item' + field_number_suffix).show(); //main edit wrapper
		$('#geo_response_ok' + field_number_suffix).hide(); 
		resetItem(field_number_suffix);		
	}
}

/**
 * reset values of an item
 * @param string field_number_suffix identifies the current item by "-123"
 */
function resetItem(field_number_suffix) {
	var suffix = '';
	if (field_number_suffix != '') suffix = '_item' + field_number_suffix;
	$('#geo_continent' + suffix).setValue('0');
	$('#geo_continent_hidden' + suffix).setValue('0');
	$('#geo_country' + suffix).setValue('0');
	$('#geo_country_hidden' + suffix).setValue('0');
	$('#geo_region' + suffix).setValue('0');
	$('#geo_city' + suffix).setValue('0');
}


/**
 * picture handling: update all pictures with the geo matching set for the first picture
 * @return void
 * @param int geo_continent id of the continent
 * @param int geo_country id of the country
 * @param int geo_region id of the region
 * @param int geo_city id of the city
 * @param string status "ok|error|suggest_ok|reset"
 * @see updateGeoboxLabel()
 * @see setGeoStatus()
 * @see setGeoAllStatus()
 */
function updateAllFields(geo_continent, geo_country, geo_region, geo_city, status) {
	//loop all items and update their hidden values
	$(".geobox_edit_item").each(
		function(index){
			var field_id = this.id;
			var field_number = getFieldNumber(field_id);
			if (field_number) {
				var field_number_suffix = '-' + field_number
				var suffix = '_item' + field_number_suffix;

				//update current item with master data
				log ('updating field#', field_number);
				$('#myopodien_form').deserialize(eval("data={'geo_continent" + suffix + "': '" + geo_continent + "', 'geo_country" + suffix + "': '" + geo_country + "', 'geo_region" + suffix + "': '" + geo_region + "', 'geo_city" + suffix + "': '" + geo_city + "'}"));
				
				var labelstr = $('#geobox_edit .geo_auswahl').html(); //get master label
				updateGeoboxLabel('#geobox_edit' + suffix, labelstr); //update label for current item
				
				setGeoStatus(status, field_number_suffix);
			}
		}
	);
	
	//if no error, switch from master selection only to per item selection
	if (status != 'error') setGeoAllStatus(0);
}



/**
 * updates select fields with (manually searched) data (this is triggered on text search / autocompleter)
 * example: user types "Hamburg" in the search field, which simulates a click on "Hamburg" in the select fields
 * @param {Object} event
 * @param {Object} data
 * @param {Object} formatted
 * @param {Object} field_id
 * @param {Object} submit
 * @param {Object} formname
 * @see updateGeoboxSelection()
 */
function updateGeobox(event, data, formatted, field_id, submit, formname) {
	var name= data[0];
	var id = data[1];
	var entity = data[2];
	var country_name = data[3];

	if (!formname) {
		formname = $('#' + field_id)[0].form.id;
	}

	var field_number = getFieldNumber(field_id);
	if (field_number) setGeoAllStatus(0); //switch to "per item" selection upon first interaction with a single image

	var field_number_suffix = '';
	if (field_number) field_number_suffix = '-' + field_number;
	
	if (!field_number) {
		field_id = '#geobox_edit'; //fï¿½r alle
	} else {
		field_id = '#geobox_edit_item' + field_number_suffix; //einzeln
	}
	
	labelstr = '';
	if (country_name) {
		labelstr = name + ', ' + country_name;
	} else {
		labelstr = name;
	}
	updateGeoboxLabel(field_id, labelstr);

	var suffix = '';
	var pos_slice = field_id.indexOf('-');
	
	//per image or master selection?
	
	if (pos_slice > 0) {
		//per image
		var suffix = '_item' + field_id.substring(pos_slice, field_id.length);
		log('suffix', suffix);
		//log('blah', '.geobox_edit_item #' + entity + suffix);
		$('.geobox_edit_item #' + entity + suffix).selectOptions(id, true);
	} else {
		//normal geobox
		$('#geobox_edit #' + entity + ', #geobox #' + entity).selectOptions(id, true);
	}

	//initiate ajax request to update the selectboxes (same effect as a click on the select boxes)
	updateGeoboxSelection(id, entity + suffix, submit, formname);
}


function updateGeoboxAutocompleter(event, data, formatted, field) {
	var name= data[0];
	var id = data[1];
	var entity = data[2];
	var country_name = data[3];

	$('#' + field.id + '_entity').val(entity);
	$('#' + field.id + '_id').val(id);
}

/**
 * gets the status of a certain input item
 * @return string status "ok|error|suggest_ok|reset"
 * @param string field_number_suffix identifies the item by "-123"
 */
function getItemStatus(field_number_suffix) {
	return $('#geo_status' + field_number_suffix).getValue();
}

/**
 * sets the status of a certain input item
 * @return void
 * @param string field_number_suffix identifies the item by "-123"
 * @param string value status "ok|error|suggest_ok|reset"
 */
function setItemStatus(field_number_suffix, value) {
	$('#geo_status' + field_number_suffix).setValue(value);
}

/**
 * updates the geo location label of a certain input item
 * @return void
 * @param string field_id full DOM id of the item to update
 * @param string label
 */
function updateGeoboxLabel(field_id, label) {
	$(field_id).show();
	var label_id = field_id + ' .geo_auswahl';
	field_number = getFieldNumber(field_id);

	if (!label) label = 'keine Auswahl';
	var label = jQuery.trim(label);
	
	log('updating ' + label_id, label);
	$(label_id).html(label);
}

/**
 * appends to the geo location label of a certain input item
 * @return void
 * @param string field_id full DOM id of the item to update
 * @param string label
 */
function appendGeoboxLabel(field_id, label) {
	$(field_id).show();
	var label_id = field_id + ' .geo_auswahl';
	field_number = getFieldNumber(field_id);

	if (!label) label = 'keine Auswahl';
	var label = jQuery.trim(label);
	
	log('updating ' + label_id, label);
	$(label_id).append(label);
}

/**
 * form validation: checks if all pictures were geo matched and have a name entered
 * @param string form name of the form
 * @return bool error
 * @see highlightError()
 * @see dehighlightError()
 */
function checkFormImages(form) {
	var geoall = getGeoAllStatus(); 

	//master image or per item selection?
	var error = false;
	if (geoall == 1) {
		highlightError('geobox_edit');
		log('missing values in first field');
		error = true;
	} else {
		$("li.gallery_image").each(
			function(index){
				var field_number_suffix = '';
				var suffix = '';
				var field_id = this.id;
				var field_number = getFieldNumber(field_id);
				if (field_number) field_number_suffix = '-' + field_number;
				if (field_number_suffix) suffix = '_item' + field_number_suffix;
				
				//country is mandatory
				if (index == 0) {
					var country_id = 'geo_country_hidden';
					var country_select_id = '#' + country_id;
					var country = $(country_select_id).fieldValue();
				} else {	
					var country_id = 'geo_country_hidden' + suffix;
					var country_select_id = '#' + country_id;
					var country = $(country_select_id).fieldValue();
				}
				
				if (country == '0') {
					log('missing values in', country_select_id);
					//$('#geobox_edit .choicebox_inner').Shake(2);
					highlightError(field_id, '.geo_search_edit_item', 'border');
					highlightError(field_id, '.geo_search_edit_item_head', 'color');
					highlightError(field_id, '.geo_country_item', 'border');
					//alert('highlight: ' + field_id +  '.geo_search_edit_item_head color');
					
					error = true;
				} else {
					log('found values in', country_select_id);
					dehighlightError(field_id, '.geo_search_edit_item', 'border');
					dehighlightError(field_id, '.geo_search_edit_item_head', 'color');
					//alert('dehighlight: ' + field_id +  ' .geo_search_edit_item_head color');


					dehighlightError(field_id, '.geo_country_item', 'border');

					//$('#gallery_image-187 .geo_search_edit_item_head').css('color', '#000000');
				}
				
				//text field is mandatory
				if (field_number_suffix) {
					var name_id = 'image_name' + field_number_suffix;
					var name_textarea_id = 'textarea[@name=\'' + name_id + '\']';
					var name = $(name_textarea_id).fieldValue();  
				}
				if (name[0] == '') {
					log('missing values in', name_textarea_id);
					//$('#geobox_edit .choicebox_inner').Shake(2);
					highlightError(field_id, name_textarea_id, 'border');
					highlightError(field_id, '.image_name_head', 'color');
					error = true;
				} else {
					log('found values in', name_textarea_id);
					dehighlightError(field_id, name_textarea_id, 'border');
					dehighlightError(field_id, '.image_name_head', 'color');
				}
			}
		);
	}
	return error;		
}

/**
 * tooltips for images
 */
function bindTooltips(additionalselector){
	var selector = 'span.tooltip, img.tooltip';
	if (additionalselector) selector = additionalselector + ' ' + selector;
	$(selector).Tooltip({
		delay: 0,
		showURL: false,
		track: true,
		extraClass: "tooltip_width"
	});
}



/**
 * form validation: checks a general form - wraps detailed validation methods
 * @return bool error
 * @param string form name of the form
 * @see checkFormImages()
 * @see hideGeneralError()
 * @see showGeneralError()
 */
function checkForm(form,nosubmit) {
	var error = true;
	error = checkFormImages(form);
	
	if (error == false) {
		hideGeneralError();
		if (!nosubmit) $('#' + form).submit();
	} else {
		showGeneralError();
		return false;
	}
	return true;
}


function checkFormReportsUploadRedirect(form) {
	$('input[@name=upload_redirect]').setValue(1);
	var check = checkFormReports(form);
	if (check == false) {
		$('input[@name=upload_redirect]').setValue(0);
		$.scrollTo('#general_error_message', 800);
	}
	return false;
}

/**
 * form validation: checks userreports if they have a geo location matched and a text
 * @return bool error
 * @param string form name of the form
 * @see highlightError()
 * @see dehighlightError()
 * @see hideGeneralError()
 * @see showGeneralError()
 */
function checkFormReports(form, nosubmit) {
	var error = false;

	var country_id = 'geo_country_item';
	var field_id = 'myopodien_form';
	var name_id = 'name';
	
	var country_select_id = 'input[@name*=\'' + country_id + '\']';
	var country = $(country_select_id).fieldValue();
	if ((country == '0') || (country == '')) {
		log('missing values in', country_select_id);
		highlightError(field_id, '.geo_search_edit_item', 'border');
		highlightError(field_id, '.geo_search_edit_item_head', 'color');
		highlightError(field_id, '.geo_country_item', 'border');
		error = true;
	} else {
		log('found values in', country_select_id);
		dehighlightError(field_id, '.geo_search_edit_item', 'border');
		dehighlightError(field_id, '.geo_search_edit_item_head', 'color');
		dehighlightError(field_id, '.geo_country_item', 'border');
	}

	var text_id = 'text';
	
	var text_textarea_id = 'textarea[@name=\'' + text_id + '\']';
	
	
	//var text = $(text_textarea_id).fieldValue(); 
	var text = $("iframe.mceEditorIframe").contents().find("body").html();

	if (text[0] == '') {
		log('missing values in', text_textarea_id);
		//$('#geobox_edit .choicebox_inner').Shake(2);
		highlightError(field_id, text_textarea_id, 'border');
		highlightError(field_id, '.item_text_head', 'color');
		error = true;
	} else {
		log('found values in', text_textarea_id);
		dehighlightError(field_id, text_textarea_id, 'border');
		dehighlightError(field_id, '.item_text_head', 'color');
	}

	var name_select_id = 'input[@name*=\'' + name_id + '\']';
	var name = $(name_select_id).fieldValue();
	if ( $(name_select_id) && (name == '')) {
		highlightError(field_id, '[name=name]', 'border');
		error = true;
	} else {
		dehighlightError(field_id, '[name=name]', 'border');
	}


	if (error == false) {
		hideGeneralError();
		
		//put list of assigned pictures into input field
		var selected_items = getAssignedPicturesString();
		$('input[@name=selected_pictures]').setValue(selected_items);
		
		if (!nosubmit) $('#' + form).submit();
	} else {
		showGeneralError();
		return false;
	}
	return true;
}


/**
 * form validation: checks userreports if they have a geo location matched and a text
 * @return bool error
 * @param string form name of the form
 * @see highlightError()
 * @see dehighlightError()
 * @see hideGeneralError()
 * @see showGeneralError()
 */
function checkFormTargets(form, nosubmit) {
	var error = false;

	if (error == false) {
		hideGeneralError();
				
		//put list of assigned pictures into input field
		if (!nosubmit) $('#' + form).submit();
	} else {
		showGeneralError();
		return false;
	}
	return true;
}


function loadUserreportPictures(offset) {
	
	var query = '';
	if (offset < 0) offset = 0;
	if (offset > 0) query = query + '&offset=' + offset;

	$('.embeddedpics_loading_indicator').show();

	$('.picturesembedded').each( function() { //should only be one occurence
		
		var report_id = getFieldNumber(this.id);
		
		if (report_id > 0) {
			query = query + '&report_id=' + report_id;
		
			$.ajax({
				type: "POST",
				url: BASEDIR_ROOT + "/index.php",
				data: "id=" + AJAX_HANDLER_PID + "&mode=frontend_load_assigned_pictures" + query,
				success: function(msg){
					var result = eval("data=" + msg);
		
					//prepend loaded pictures
					$('#picturesembedded-' + report_id).html(result['result_html']);
					$('.embeddedpics_loading_indicator').hide();
					postbindThickbox('.picturesembedded a.thickbox');
					bindTooltips('.picturesembedded');
											
					//result['offset']
					//result['overall_count']
					//result['results_at_a_time']
					//result['picleft_prev']
					
					//binding the prev link
					if (result['picleft_prev'] > 0) {
						//show next button, bind links
						$('.embeddedpics_icon_prev').show();
						$('.embeddedpics_text').show();
						$('.embeddedpics_icon_prev').unbind();
						$('.embeddedpics_icon_prev').bind(
							'click',
							function() {
								$(this).unbind();
								var offset_new;
								if (!isNaN(parseInt(result['offset']))) var offset_new = parseInt(result['offset']);
								offset_new = offset_new - parseInt(result['results_at_a_time']);
								loadUserreportPictures(offset_new);	
							}
						);
					} else {
						$('.embeddedpics_icon_prev').hide();
					}
					
					
					//binding the next link
					if (result['picleft_next'] > 0) {
						//show next button, bind links
						$('.embeddedpics_icon_next').show();
						$('.embeddedpics_text').show();
						$('.embeddedpics_icon_next').unbind();
						$('.embeddedpics_icon_next').bind(
							'click',
							function() {
								$(this).unbind();
								var offset_new = parseInt(result['results_at_a_time']);
								if (!isNaN(parseInt(result['offset']))) offset_new = offset_new + parseInt(result['offset']);
								loadUserreportPictures(offset_new);	
							}
						);
					} else {
						$('.embeddedpics_icon_next').hide();
					}
				}
			});
		}			
		
	});

}


function postbindThickbox(selector){
	tb_init(selector);
	imgLoader = new Image();// preload image
	imgLoader.src = tb_pathToImage;
}

//add thickbox to href & area elements that have a class of .thickbox
function tb_init(domChunk){
	$(domChunk).unbind();
	$(domChunk).click(function(){
	var t = this.title || this.name || null;
	var a = this.href || this.alt;
	var g = this.rel || false;
	tb_show(t,a,g);
	this.blur();
	return false;
	});
}



/**
 * highlights an error in the form	
 * @return void
 * @param string item_id full DOM id of the parent of the item to highlight
 * @param string field_class class of the item to highlight
 * @param string attribute "border|color"
 * @see highlightErrorDirect()
 */
function highlightError(item_id, field_class, attribute) {
	var selector = "#" + item_id + " " + field_class;
	highlightErrorDirect(selector, attribute);
}

/**
 * actually highlights an item
 * @return void
 * @param string selector full DOM selector
 * @param string attribute "border|color"
 */
function highlightErrorDirect(selector, attribute) {
	if (attribute == 'border') $(selector).css('border', $.i18n._('highlight_error_border'));
	if (attribute == 'color') $(selector).css('color', $.i18n._('highlight_error_color'));
}


/**
 * de-highlights an error in the form	
 * @return void
 * @param string item_id full DOM id of the parent of the item to de-highlight
 * @param string field_class class of the item to de-highlight
 * @param string attribute "border|color"
 * @see dehighlightErrorDirect()
 */
function dehighlightError(item_id, field_class, attribute) {
	var selector = "#" + item_id + " " + field_class;
	dehighlightErrorDirect(selector, attribute);
}

/**
 * actually dehighlights an item
 * @return void
 * @param string selector full DOM selector
 * @param string attribute "border|color"
 */
function dehighlightErrorDirect(selector, attribute) {
	if (attribute == 'border') $(selector).css('border', $.i18n._('dehighlight_error_border'));
	if (attribute == 'color') $(selector).css('color', $.i18n._('dehighlight_error_color'));
}

/**
 * shows the general error message
 * @return void
 */
function showGeneralError() {
	$('#general_error_message').show();
}

/**
 * hides the general error message
 * @return void
 */
function hideGeneralError() {
	$('#general_error_message').hide();
}


/**
 * Usertargets: Show remaining targets and hide the "show all" link
 */
function toggleUsertargets(targetid, actionlink) {
	$('#' + targetid + '_remain').show();
	$(actionlink).parent().hide();
}


/**
 * builds a promotion pod based on the json data delivered by the hotel review interface
 * @param {Object} obj
 */
function populateXSellImagepod(obj) {
	if (obj.ResultSet.offers.length >= 2) {
		var skeleton_container = $('#xsell_hotel_promotion_skeleton').html();
		$('#xsell_hotel_promotion_skeleton').remove();
		var skeleton_item = $('#xsell_hotel_promotion_skeleton_item').html();
		$('#xsell_hotel_promotion_skeleton_item').remove();
		
		$('.tx-opomainxsell-pi1 .textlink_tt').hide();
		$('.tx-opomainxsell-pi1 .textlink_hotel').hide();
		$('.tx-opomainxsell-pi1').append(skeleton_container);
	
		$.each(obj.ResultSet.offers, function(index, offer) {
			//console.log(offer);
			$('.xsell_hotelpromotion .mainpod_inner').prepend(skeleton_item);
		});
	
		$('.xsell_hotelpromotion:visible .xsell_hotel_item').each(function(index) {
			var offer = obj.ResultSet.offers[index];
			var stars = '';
			for (var i=0; i<offer.sterne; i++) {stars = stars + '*';}
			$(this).children('p.maintext').html(limitChars(offer.name, 16) + ' '  + stars);
			$(this).children('a.xsell').children('img.thumbimage').attr("src", offer.imgthumbnail);
			$(this).children('h3.subheadline').html(limitChars(offer.ort, 35));
			$(this).children('span.offertext').html($.i18n._('xsell_subheadline'));
			$(this).children('a.price').children('.xsell_price_value').html(offer.offerprice);
			$(this).children('a.xsell').attr("href", offer.offerdeeplink);
		});
		
		$('.tx-opomainxsell-pi1 .xsell_hotel_item:eq(1)').css('float', 'right');
		
	} else {
		$('.tx-opomainxsell-pi1 .textlink_tt').show();
		$('.tx-opomainxsell-pi1 .textlink_hotel').show();
	}
}


function showMoreText(id) {
	$('#toggletext-start-' + id).css('position', 'relative');
	$('#toggletext-start-' + id).fadeOut();
	$('#toggletext-full-' + id).css('position', 'relative');
	$('#toggletext-full-' + id).slideDown();
}

function thickboxSlideNext(url, title) {
	$("#TB_window").remove();
	$("body").append("<div id='TB_window'></div>");
	tb_show(title, url, false);				
	return false;	
}


function setFocusOnGuestbook() {
		if ($("#comment_form textarea") && document.location.hash == "#gaestebuch") {
			$("#comment_form textarea:first").focus();
		}
}
function checkAndSetContext() {
		if (document.location.hash == '#browse-continent') {
			$('.context-continent').show();
			$('.gallery_image a.thickbox:first').attr('href', $('.gallery_image a.thickbox:first').attr('href').replace('getItemForThickbox', 'getItemForThickbox&context=continent'));
		} else
		if (document.location.hash == '#browse-country') {
			$('.context-country').show();
			$('.gallery_image a.thickbox:first').attr('href', $('.gallery_image a.thickbox:first').attr('href').replace('getItemForThickbox', 'getItemForThickbox&context=country'));
		} else
		if (document.location.hash == '#browse-region') {
			$('.context-region').show();
			$('.gallery_image a.thickbox:first').attr('href', $('.gallery_image a.thickbox:first').attr('href').replace('getItemForThickbox', 'getItemForThickbox&context=region'));
		} else
		if (document.location.hash == '#browse-city') {
			$('.context-city').show();
			$('.gallery_image a.thickbox:first').attr('href', $('.gallery_image a.thickbox:first').attr('href').replace('getItemForThickbox', 'getItemForThickbox&context=city'));
		} else {
			$('.context-' + geo_entity).show();
		}
}

if (!jQuery.dequeue) {
	jQuery.dequeue = function() {
	}
}
