/**
 * @author
 */

var $j = jQuery.noConflict();


function getSessionURL(url) {
	if (typeof sessionURLSuffix == "undefined" || !sessionURLSuffix || sessionURLSuffix == "") {
		return url;
	}
	if (url.indexOf(sessionURLSuffix) >= 0) {
		//already contains session info
		return url;
	}
	var pathEnd = url.indexOf("?");
	if (pathEnd < 0) {
		pathEnd = url.indexOf("#");
		if (pathEnd < 0) {
			pathEnd = url.length;
		}
	}
	var res = url.substring(0, pathEnd) + sessionURLSuffix;
	if (pathEnd < url.length) {
		var urlEnd = url.substring(pathEnd);
		if (urlEnd.charAt(0) == "?") {
			if (sessionURLSuffix.indexOf("?") >= 0) {
				res += "&" + urlEnd.substring(1);
			} else {
				res += urlEnd;
			}
		} else {
			res += urlEnd;
		}
	}
	return res;
}

function getURLWithBasepageParam(url) {
	var pathEnd = url.indexOf("?");
	if (pathEnd < 0) {
		pathEnd = url.indexOf("#");
		if (pathEnd < 0) {
			pathEnd = url.length;
		}
	}
	var basePage = -1;
	if (typeof currentPageId != "undefined") {
		basePage = currentPageId;
	}
	var newUrl = url.substring(0, pathEnd) + "?basePage=" + basePage;
	if (pathEnd < url.length) {
		if (url.charAt(pathEnd) == "?") {
			newUrl += "&" + url.substring(pathEnd + 1);
		} else {
			newUrl += url.substring(pathEnd);
		}
	}
	return newUrl;
}

function quoteString(string) {
	return string.replace("\\", "\\\\").replace("\"", "\\\"").replace("\'", "\\\'");
}

function escapeXML(string) {
	return string.replace("&", "&amp;").replace("<", "&lt;").replace("&gt;");
}

var MySidebar = {

	ToggleSubinfo: function (obj) {
		obj = $j(obj).parent().find('.subinfo');
		if($j(obj).css('display') == 'block') {
			$j(obj).slideUp("middle");
		}
		else {
			$j(obj).slideDown("middle");
		}
		return false;
	}
}


var Pinnboard = {

	SetNewMessageResult: function (selector, html) {
		$j(selector).after(html);
	},

	SetNewMessageFormRequest: function (obj) {
		loading.open();
		return $j(obj).AjaxRequest({
				resultContainer: function(html) { Pinnboard.SetNewMessageResult('#PinnwandListeForm', html); loading.close(); }
		});
	},

	SetNewSubMessageResult: function (selector, html) {
		$j(selector).before(html);
	},

	SetNewSubMessage: function (obj) {
		objItem = $j(obj).parents('.item');
		var objSubItems = $j(objItem).find('.subItems');
		// Formular setzen
		if($j(objSubItems).find('.subItem').length < 1) {
			loading.open();
			return $j(obj).AjaxRequest({
					objResult: objSubItems,
					resultContainer: function(html, objResult) { /*alert($j(objResult).html());*/ $j(objResult).html(html);loading.close(); }
			});
		}
		// Focus auf Formular
		else {
			$j(objSubItems).find('textarea').focus();
		}
		return false;
	},

	SetNewSubMessageFormRequest: function (obj) {
		objItem = $j(obj).parents('.subItems');
		var objResult = $j(objItem).find('.subItemAdd');
		loading.open();
		return $j(obj).AjaxRequest({
				objResult: objResult,
				resultContainer: function(html, objResult) { Pinnboard.SetNewSubMessageResult(objResult, html);loading.close(); }
		});
	}

}

var Messages = {
	init: function (context) {
		_self = this;
		tabels= $j('.nachrichtenListItem');
		$j(tabels).mouseout(function() {
			if(!$j(this).hasClass('active')) {
				$j(this).css('background', '');
			}
		}).mouseover(function() {
			if(!$j(this).hasClass('active')) {
				$j(this).css('background', '#f6f6f6');
			}
		}).click(function() {
			_self.toggleCheckbox($j(this));	
		});
		
		$j(tabels).find('.col6').find('img').mouseout(function() {
			$j(this).attr('src', context + '/v2/images/icon/ico_nachrichten_cross.gif');
		}).mouseover(function() {
			$j(this).attr('src', context + '/v2/images/icon/ico_nachrichten_cross_active.gif');
		});
	},	
	checkedAll: function (obj, checked) {
		_self = this;
		if(checked) {
			$j(obj).each(function(){
				_self.checkedInput(this);			
			});	
		}
		if(!checked) {
			$j(obj).each(function(){
				_self.uncheckedInput(this);	
			});	
		}
	},	
	checkedInput: function(obj) {
		$j(obj).css('background', '').addClass('active');
		if(!$j(obj).find('input').attr('checked')) {
			$j(obj).find('input').trigger('click');
		}			
	},
	uncheckedInput: function(obj) {
		$j(obj).css('background', '').removeClass('active');
		if($j(obj).find('input').attr('checked')) {
			$j(obj).find('input').trigger('click');
		}	
	},	
	toggleCheckbox: function (obj, force) {
		if($j(obj).find('input').attr('checked')) {
			this.checkedInput(obj);	
		}
		else {
			this.uncheckedInput(obj);
		}		
	}	
}

/*
 * Function to Convert the Carraige Returns to <br />
 */
function convertCarriageReturn(text) {
	for(i=0; i<text.length; i++){
         if(text.indexOf('%0D%0A') > -1){
        	text = text.replace('%0D%0A','<br />');
        }
        else if(text.indexOf('%0A') > -1){
        	text = text.replace('%0A','<br />');
        }
        else if(text.indexOf('%0D') > -1){
        	text = text.replace('%0D','<br />');
        }
    }
	return unescape(text);
}

/*
 * Callback Functions for Popup Layer - are called when Popuplayer is opened
 */

//Funktion die aufgerufen wird um eine Suchanzeige aufzugeben
var suchanzeigeAuslesen = function() {
	sache = $j('#addThing').attr('value');
	ort = $j('#addThingCity').attr('value');

	textarea = escape($j('#DetailedDescription').find('textarea').attr('value'));

	if($j('#DetailedDescription').find('textarea').attr('value') != 'Detaillierte Beschreibung hinzufügen ...') {
		//alert($j('#DetailedDescription').find('textarea').attr('value'));
		textarea = convertCarriageReturn(textarea);
		$j('#popupLayer').find('p.beschreibungsText').find('span').html(textarea);
	}
	else
		$j('#popupLayer').find('p.beschreibungsText').remove();

	$j('#popupLayer').find('span.sache').html(sache);
	$j('#popupLayer').find('span.ort').html(ort);
};


/*	Popup Layer Handling
 *
 *
 */

// Fix second ajax request not working in ie8
// http://stackoverflow.com/questions/4557532
jQuery.ajaxSetup({
	xhr: function() {
		try {
			if (window.ActiveXObject) {
				return new window.ActiveXObject("Microsoft.XMLHTTP");
			}
		} catch (e) {
			// ignore: use modern style XMLHttpRequest()
		}
		return new window.XMLHttpRequest();
	}
});

var loading = {
	img: '<div id="ajaxLoderAnimation" style="position:absolute;width:220px;height:31px;visibility:hidden;z-index:20000;"><img src="'
		+ (typeof contextPath != "undefined"? contextPath + '/v2/' : '') + 'images/icon/ajax-loader.gif" /></div>',

	open: function() {
		loading.close(); // für alle Fälle
		$j('body').append(this.img);
		y = $j(document).scrollTop() - $j('div#ajaxLoderAnimation').height()/2 + $j(window).height()/2;
		x = $j(document).width()/2 - $j('div#ajaxLoderAnimation').width()/2;
		$j('div#ajaxLoderAnimation').css({top: y + 'px',left: x +'px', visibility:'visible'});
	},

	close: function() {
		$j('div#ajaxLoderAnimation').remove();
	}
}


var popupLayer = {

	callbackFunc: false,

	create: function(title, urlString, text, width, height) {
		if (!width) {
			width = 580;
		}
		
		var content = '';
		content += '<div id="popupLayer" class="layer" style="z-index:1500;width:' + width + 'px;display:none;">';
		content += '	<div class="" style="width:' + width + 'px;height:5px; background-color: #999" />';
		content += '	<div class="layerContent " style="width:' + width + 'px;">';
		content += '		<div class="inner ">';
		content += ' 			<div id="popupLayerContent" style="background-color:#ffffff;height:100%;">';
		content += '			</div>';
		content += '		</div>';
		content += '	</div>';
		content += '	<div class="" style="width:' + width + 'px;height:5px; background-color: #999;"/>';
		content += '</div>';
		$j('body').append(content);
	},

	open:function(config) {



		title = 		config.title || false;
		url =			config.url || false;
		width = 		config.width || false;
		height = 		config.height || false;
		setEvent = 		config.setEvent || false;
		text = 			config.text || false;
		htmlContainer = config.htmlContainer || false;//jQuery object containing popup contents
		var callbackFunctionOpen = 	config.callbackFunctionOpen || false;

		popupLayer.remove(); // für alle fälle
		loading.open();

		popupLayer.create(title, url, text, width, height);

		//wenn keine URL mit übergeben sollte ein Text dabei sein
		if (!url && text) {
			popupLayer.createTextPopup(config.title, config.text);
			popupLayer.showPopup();
		} else if (!url && htmlContainer) {
			popupLayer.createPopupFromHtmlContainer(config.title, config.htmlContainer);
			popupLayer.showPopup();
		} else {
			$j.ajax({
				url: getSessionURL(getURLWithBasepageParam(url)),
				cache: false,
				success: function(html){
					var docContents = extractUniqueTagContents(html, "html");
					// in case of multiple requests due to double click, show only the result of the last one:
					popupLayer.remove();
					popupLayer.create(title, url, text, width, height);
					if (docContents.length > 0) {
						var headContents = extractUniqueTagContents(docContents, "head");
						var headElements = $j(headContents).filter("script,link");
						html = removeUniqueTag(docContents, "head");
						$j('#popupLayerContent').append(headElements);
					}
					$j('#popupLayerContent').append(html).each(function(i){
						if (callbackFunctionOpen) {
							callbackFunctionOpen();
						}
					});
					popupLayer.showPopup();
					if (setEvent) {
						$j("#popupLayer").find('form').submit(function(){
							SendForm.post('#ajaxForm', '#popupLayerContent');
							return false;
						});
					}

					//Um die Checkboxen zu ersetzen
					//Custom.initLayer('popupLayer');
					//crir.init();
					if (typeof ajaxInit == 'function') {
						ajaxInit();
					}

				},
				error: function (request, textStatus, exceptionThrown) {
					// just ignore for now
				}
			});
		}
	},

	showPopup: function() {
		loading.close();
		y = ($j(document).scrollTop() - Math.ceil($j('div#popupLayer').height() / 2) + ($j(window).height() / 2));
		x = ($j(document).width() / 2) - Math.ceil($j('div#popupLayer').width() / 2);
		if (y < 0) {
			y = 0;
		}
		$j('div#popupLayer').css({
			top: y + 'px',
			left: x + 'px'
		});
		$j('div#popupLayer').fadeIn(200);
	},

	//Text wird mit beim Aufruf übergeben
	createTextPopup: function(title, text) {
		var temp = '';
		temp +=  '<div id="FreundBestaetigenLayer" class="popup">';
		temp +=	 '<div class="content">';
		temp +=  '<div class="leftContent">';
		temp +=  '<h2>' + title + '</h2>';
		temp +=  '<h3>' + text + '</h3>';
		temp +=  '</div>';
		temp +=  '</div>';
		temp +=  '<div id="Buttons">';
		temp +=  '<img id="Send" onclick="popupLayer.close();return false;" style="float:right;" class="button" src="images/button/ok.gif" alt="Ok" />';
		temp +=  '</div>';
		temp +=  '<br class="clear" />';
		temp +=  '</div>';

		$j('#popupLayerContent').append(temp);
	},

	createPopupFromHtmlContainer: function(title, htmlContainer) {
		var htmlContents = htmlContainer.html();
		htmlContainer.empty();
		$j('#popupLayerContent').html(htmlContents);
	},

	close:function(callbackFunc) {
		callbackFunc = callbackFunc || false;

		//Layer ausblenden
		$j('div#popupLayer').fadeOut(200, function(){$j('div#popupLayer').remove();} );

		if(callbackFunc) {
			callbackFunc();
		}
		return false;
	},

	remove:function() {
		$j('div#popupLayer').remove();
	},

	showContainer: function(id) {
		this.id = id;
		$j("#" + this.id).toggle(200);
		return false;
	},

	showContainerHideLink: function(obj,id) {
		this.id = id;
		$j(obj).parent().hide();
		$j("#" + this.id).toggle(200);
		return false;
	}

}

function extractUniqueTagContents(s, tag) {
	var tagPos = s.indexOf("<" + tag);
	if (tagPos >= 0) {
		var fromIndex = s.indexOf(">", tagPos + tag.length) + 1;
		var toIndex = s.lastIndexOf("</"  + tag + ">")
		if (toIndex < 0) {
			toIndex = s.length;
		}
		return s.substring(fromIndex, toIndex);
	}
	return "";
}

function removeUniqueTag(s, tag) {
	var tagPos = s.indexOf("<" + tag);
	if (tagPos >= 0) {
		var fromIndex = tagPos;
		var toIndex = s.lastIndexOf("</"  + tag + ">")
		if (toIndex < 0) {
			toIndex = s.length;
		} else {
			toIndex += 3 + tag.length;
		}
		return s.substring(0, fromIndex) + s.substring(toIndex);
	}
	return "";
}

/* Ergebnislisten Handling
 * Highlighten der aktuellen Seite +
 * Verschieben der Seitenzahlen
 */

var resultlist = {

	showPage: function(obj) {
		//active setzen und bei allen anderen removen
		$j(obj).parent().parent().find('li').removeClass('active');
		$j(obj).parent().addClass('active');

		//wenn First oder Last angeklickt - Liste verschieben
		/*
		if($j(obj).parent().attr('class') == 'First') {

			$j(obj).parent().parent().find('li a').each( function(){ var newPage = parseInt( $j(this).text()); newPage--; $j(this).text(newPage); } );
		}
		else if ($j(obj).parent().attr('class') == 'Last') {
			$j(obj).parent().parent().find('li a').each( function(){ var newPage = parseInt( $j(this).text()); newPage++; $j(this).text(newPage); } );
		}
		*/


	}
}

/* Handling für die Kurzlisten */
var shortList = {

	highlight: function(obj) {
		$j(obj).css('background-color', '#f6f6f6');

		if ($j(obj).find('.addFriend').length > 0) {
			$j(obj).find('.addFriend>p').show();
			var src = $j(obj).find(".addFriend>a img").attr('src');
			if (src) {
				src = src.replace(/pas.gif/, "act.gif");
				$j(obj).find(".addFriend>a img").attr('src', src);
			}
		}
	},

	unhighlight: function(obj) {
		$j(obj).css('background-color', '#ffffff');

		if ($j(obj).find('.addFriend').length > 0) {
			$j(obj).find('.addFriend>p').hide();
			var src = $j(obj).find('.addFriend>a img').attr('src');
			if (src) {
				src = src.replace(/act.gif/, "pas.gif");
				$j(obj).find('.addFriend>a img').attr('src', src);
			}
		}
	}

}

/* Seitenhandling für Actionbilder */
var actionImages = {

        /**
     * Function to scroll a list with pagination
     * @param id is the name of the List to Scroll
     * @param page is the pagenumber to scroll to
     * @param count is the number of elements to show
     */
	init: function(id){
		this.id = id;

		//Anzahl der Listenelemente rausfinden
		this.count = $j("#" + this.id).find(".inner:ul li").length;
		//Größe eines Listenelementes
		this.length = $j("#" + this.id).find(".inner:ul li").outerWidth(true);
		//Größe des gesamten UL ändern
		this.completeWidth = this.count * this.length + "px";
		$j("#" + this.id).find(".inner:ul").children().css("width",this.completeWidth);
	},

	hover: function (obj) {
		$j(obj).parent().addClass('active');
	},

	unhover: function (obj) {
		$j(obj).parent().removeClass('active');
	},

	/**
     * Function to scroll a list with pagination
     * @param id is the name of the List to Scroll
     * @param page is the pagenumber to scroll to
     * @param count is the number of elements to show
     */
	scrollToPage: function(obj,id,page, count){
		this.id = id;
		this.page = page;

		//active setzen und bei allen anderen removen
		$j(obj).parent().parent().find('li').removeClass('active');
		$j(obj).parent().addClass('active');

		//Breite eines Elementes holen
		this.itemWidth = $j("#" + this.id).find('li').outerWidth(true);

		//Gesamtbreite der zu scrollenden Elemente ermitteln
		this.scrollAreaWidth = this.itemWidth * count;

		//Wert für left ermitteln - neue Position
		if (page == 1)
			this.newPosition = 0;
		else {
			this.newPosition = (page - 1) * this.scrollAreaWidth;
			this.newPosition = "-" + this.newPosition + "px";
		}

		//animieren
		$j("#" + this.id).animate({
			left: this.newPosition
      		}, 1100, "easeInOutQuart");
	},

    /**
     * Function to scroll between image 1 and 2
     * @param obj is the clicked image
     * @param number is the number of the image to scroll to
     */
	showImage: function(obj, number) {
		//Breite des Image holen
		this.width = $j(obj).parent().width();

		if(number == 1)
			this.width = 0;

		//animieren
		$j(obj).parent().parent().animate({
			left: '-' + this.width
      		}, 500, "easeInOutQuart");
	},

 	/**
     * Function to show plus and zoom on Amazon Images
     * @param obj is the clicked image
     */
	showIcons: function(obj) {
		if($j(obj).parent().find('.iconZoom'))
			$j(obj).parent().find('.iconZoom').show();
		$j(obj).parent().find('.iconPlus').show();
		if($j(obj).parent().find('.iconRating'))
			$j(obj).parent().find('.iconRating').show();
	},

 	/**
     * Function to hide plus and zoom on Amazon Images
     * @param obj is the clicked image
     */
	hideIcons: function(obj) {
		if($j(obj).parent().find('.iconZoom'))
			$j(obj).parent().find('.iconZoom').hide();
		$j(obj).parent().find('.iconPlus').hide();
		if($j(obj).parent().find('.iconRating'))
			$j(obj).parent().find('.iconRating').hide();
	},

	 /**
     * Function to show text on Amazon Images
     * @param obj is the clicked image
     */
	showText: function(obj) {
		$j(obj).parent().find('a').css('visibility','visible');
	},

	 /**
     * Function to hide text on Amazon Images
     * @param obj is the clicked image
     */
	hideText: function(obj) {
		$j(obj).parent().find('a').css('visibility','hidden');
	}

}

//Zeigt das Fake-Inputfeld mit dem Hilfetext, wenn kein Text gesetzt ist, sonst das echte Inputfeld
function inputShowHelpIfEmpty(input, helpDummy) {
	if ($j(input).attr('value') == '') {
		$j(input).hide().addClass('hiddenInput');
		$j(helpDummy).show().removeClass('hiddenInput');
	} else {
		$j(input).show().removeClass('hiddenInput');
		$j(helpDummy).hide().addClass('hiddenInput');
	}
}

//Zeigt das echte Inputfeld und versteckt das Fake-Inputfeld mit dem Hilfetext
function inputShowRealInput(input, helpDummy) {
	$j(helpDummy).hide().addClass('hiddenInput');
	$j(input).show().removeClass('hiddenInput');
	$j(input).focus();
}

function inputShowHelp(input, helpDummy){
	$j(input).hide().addClass('hiddenInput');
	$j(helpDummy).show().removeClass('hiddenInput');
}

//Verstecken des Dummy Passwort Feldes - und anzeigen des wirklichen Passwort Feld mit ****
function changePasswortType(obj) {
	$j('#DummyPasswort').hide();
	$j('#Passwort').show();
	$j('#Passwort').focus();

	$j('#Passwort').blur(function () {
		if ($j('#Passwort').attr('value') === '') {
			$j('#Passwort').hide();
			$j('#DummyPasswort').show();
		}
	})
}

//Überprüfung ob Checkbox nach reload angecheckt sein soll
function checkCheckbox(obj) {
	var src;
	src = $j(obj).attr('src');
	if ($j(obj).parent().find('input').attr('checked') == true) {
		src = src.replace(/_pas/, '_act');
	}
	else {
		src = src.replace(/_act/, '_pas');
	}
	src = $j(obj).attr('src',src);
}

//Austauschen des Checkbox Bildes und setzen des hidden Checkbox Feldes
function switchCheckbox(obj) {
	var src;
	src = $j(obj).attr('src');
	if ($j(obj).parent().find('input').attr('checked') == true) {
		$j(obj).parent().find('input').removeAttr('checked');
		src = src.replace(/_act/, '_pas');
	}
	else {
		$j(obj).parent().find('input').attr('checked','checked');
		src = src.replace(/_pas/, '_act');
	}
	src = $j(obj).attr('src',src);
}

//Input bei focus leeren wenn standard text drin
function resetInput(obj, text) {
	if( $j(obj).attr('value') === text ) {
		$j(obj).attr('value','');
		$j(obj).css('color','#999999');
	}
	$j(obj).blur(function () {
        if ($j(obj).attr('value') === '') {
          $j(obj).attr('value',text);
		  $j(obj).css('color','#c6c6c6');
        }
      })
}


//Input bei focus leeren wenn standard text drin
function resetInputAutosuggest(obj) {
	$j(obj).css('color','#444444');
}

//Input bei focus leeren wenn standard text drin
function resetInputDark(obj, text) {
	if( $j(obj).attr('value') === text ) {
		$j(obj).attr('value','');
		$j(obj).css('color','#444444');
	}
	$j(obj).blur(function () {
        if ($j(obj).attr('value') === '') {
          $j(obj).attr('value',text);
		  $j(obj).css('color','#c6c6c6');
        }
      })
}


//Textarea bei focus leeren wenn standard text drin
function resetTextarea(obj, text) {
	if( $j(obj).attr('value') === text ) {
		$j(obj).attr('value','');
		$j(obj).css('color','#999999');
	}
	$j(obj).blur(function () {
        if ($j(obj).attr('value') === '') {
          $j(obj).attr('value',text);
		  $j(obj).css('color','#c6c6c6');
        }
      })
}

//Textarea einblenden
function showTextarea(obj,id){
	this.id = id;
	$j(obj).parent().hide();
	$j("#" + this.id).show();
	//animieren

	$j("#" + this.id).find('textarea:not(.hiddenInput)').css("height", "0").animate({height: '57' }, 500, "swing", function() {});

}


/* Handling fuer GoogleMaps Scroller */
function mapcarousel_itemLoadCallback(carousel, state) {
    // Check if the requested items already exist
    if (carousel.has(carousel.first, carousel.last)) {
        return;
    }
    jQuery.get(
        getSessionURL(contextPath + '/mapdata/carousel.xml'),
		//'javascript/ajax/mapCarousel.php', //for local testing
        {
            first: carousel.first,
            last: carousel.last
        },
        function(xml) {
            mapcarousel_itemAddCallback(carousel, carousel.first, carousel.last, xml);
        },
        'xml'
    );
};

function mapcarousel_itemAddCallback(carousel, first, last, xml) {
    // Set the size of the carousel
	var size = parseInt(jQuery('total', xml).text());
    carousel.size(size);		
    $j('item', xml).each(function(i) {
        carousel.add(first + i, mapcarousel_getItemHTML(i,$j(this).find('image').text(), $j(this).find('link').text(), $j(this).find('title').text(), $j(this).find('type').text() ));
    });
    for (var i = size; i < last; i++) {
    	carousel.add(first + i, "");
    }
};

function mapcarousel_getItemHTML(index,imageURL, linkURL, title, type) {
	return '<a index="'+index+'" class="' + type + '" href="' + linkURL + '"><img onmouseover="mapScroller.showOverlay(this,\'' + quoteString(title) + '\');"  src="' + imageURL + '" width="48" height="48" alt="' + title + '" /></a>';
};

/* Handling für den Map Scroller */
var mapScroller = {

	/**
	 * Function to show the overlay with subtitle
	 * @param obj is the image
	 * @param title is the text to display under the image
	 */
	showOverlay: function(obj, title){
		//falls noch ein Overlay oder ein Subtitle visible ist wird es removed
		$j('.mapOverlay').remove();
		$j('#MapCarousel').find('h3').remove();
		//leute oder sache ?
		var type = $j(obj).parent().attr('class');
		// Link, damit ich den für IE7 nochmal an das Sushi-Dingens schreiben kann
		var href = $j(obj).parent().attr('href');
//		//den title fuer den Subtitle holen
//		var title = $j(obj).parent().attr('title');
		// wenn people gruener Overlay - wenn things blauer Overlay
		var image;
		if(type == 'things') {
			if (typeof contextPath != "undefined") {
				image = contextPath + '/v2/images/icon/sushibar_overlay_blue.gif';
			} else {
				image = '../images/icon/sushibar_overlay_blue.gif';
			}
		} else if(type="people") {
			if (typeof contextPath != "undefined") {
				image = contextPath + '/v2/images/icon/sushibar_overlay_green.gif';
			} else {
				image = '../images/icon/sushibar_overlay_green.gif';
			}
		}

		//div mit Overlay generieren und hidden ins DOM einfügen
		var overlay = '<div class="mapOverlay">' + '<a href="' + href + '">'
			+ '<img onmouseout="mapScroller.hideOverlay(this);" src="' + image + '" alt="" />'
			+ '</a></div>';
		$j(obj).parent().append(overlay);

		//Subtitle generieren und hidden ins DOM einfügen
		var headline = '<h3 class="' + type + '">' + escapeXML(title) + '</h3>';
		$j('#MapCarousel').append(headline);

		//Position des aktuellen li's holen
		var pos = $j(obj).parent().parent().position();
		//der Subtitle an die position des li anpassen
		$j('#MapCarousel').find('h3').css('left',pos.left + $j(obj).width());

		//zentrierung der Subtitle unter dem li
		var laenge = $j('#MapCarousel').find('h3').outerWidth();

		if (laenge < 48) {
			$j('#MapCarousel').find('h3').css('margin-left', ($j(obj).width() - laenge) + 'px');
		}
		else
			$j('#MapCarousel').find('h3').css('margin-left', (($j(obj).width() - laenge)/2) + 'px');

		//wenn erstes oder letztes Bild und Text größer als 20 Zeichen - aligne left or right
		//wenn zweites oder zweitletztes Bild und Text größer 40 - align left or right

		//welches li?
		var index = $j(obj).parent().attr('index');

		//alert(laenge);
		//erstes Bild
		if (index == 0) {
			if (laenge >= 98) {
				$j('#MapCarousel').find('h3').css('margin-left', '0');
			}
		}
		//zweites Bild
		if (index == 1) {
			if (laenge >= 152) {
				$j('#MapCarousel').find('h3').css('margin-left', '0');
			}
		}
		//vorletzes Bild
		if(index == 10) {
			if (laenge >= 152) {
				$j('#MapCarousel').find('h3').css('margin-left', ($j(obj).width() - laenge) + 'px');
			}
		}
		//letzes Bild
		if(index == 11) {
			if (laenge >= 98) {
				$j('#MapCarousel').find('h3').css('margin-left', ($j(obj).width() - laenge) + 'px');
			}
		}

		//Overlay und Subtitle anzeigen
		$j('#MapCarousel').find('h3').css('visibility','visible');
		$j('.mapOverlay').show();
	},

	/**
	 * Function to remove the overlay with subtitle
	 * @param obj is the image
	 */
	hideOverlay: function(obj){
		//Overlay und Subtitle removen
		$j(obj).parent().remove();
		$j('#MapCarousel').find('h3').remove();
	}
}

	//Funktion um die Unterkategorien anzuzeigen
	var subcategories = new Array();

	//Hier muss ein Javascript Array mit den Unterkategorien aufgebaut werden
	subcategories[0] = new Array();
	subcategories[0][0] = "";

	subcategories[1] = new Array();
	subcategories[1][0] = "1 Unterkategorie Eins";
	subcategories[1][1] = "1 Unterkategorie Zwei";
	subcategories[1][2] = "1 Unterkategorie Drei";

	subcategories[2] = new Array();
	subcategories[2][0] = "2 Unterkategorie Eins";
	subcategories[2][1] = "2 Unterkategorie Zwei";
	subcategories[2][2] = "2 Unterkategorie Drei";
	subcategories[2][3] = "2 Unterkategorie Vier";

	subcategories[3] = new Array();
	subcategories[3][0] = "3 Unterkategorie Eins";
	subcategories[3][1] = "3 Unterkategorie Zwei";
	subcategories[3][2] = "3 Unterkategorie Drei";

	subcategories[4] = new Array();
	subcategories[4][0] = "4 Unterkategorie Eins";
	subcategories[4][1] = "4 Unterkategorie Zwei";
	subcategories[4][2] = "4 Unterkategorie Drei";

	subcategories[5] = new Array();
	subcategories[5][0] = "5 Unterkategorie Eins";
	subcategories[5][1] = "5 Unterkategorie Zwei";
	subcategories[5][2] = "5 Unterkategorie Drei";

	subcategories[6] = new Array();
	subcategories[6][0] = "6 Unterkategorie Eins";
	subcategories[6][1] = "6 Unterkategorie Zwei";
	subcategories[6][2] = "6 Unterkategorie Drei";

	subcategories[7] = new Array();
	subcategories[7][0] = "7 Unterkategorie Eins";
	subcategories[7][1] = "7 Unterkategorie Zwei";
	subcategories[7][2] = "7 Unterkategorie Drei";

	subcategories[8] = new Array();
	subcategories[8][0] = "8 Unterkategorie Eins";
	subcategories[8][1] = "8 Unterkategorie Zwei";
	subcategories[8][2] = "8 Unterkategorie Drei";

	subcategories[9] = new Array();
	subcategories[9][0] = "9 Unterkategorie Eins";
	subcategories[9][1] = "9 Unterkategorie Zwei";
	subcategories[9][2] = "9 Unterkategorie Drei";

	subcategories[10] = new Array();
	subcategories[10][0] = "10 Unterkategorie Eins";
	subcategories[10][1] = "10 Unterkategorie Zwei";
	subcategories[10][2] = "10 Unterkategorie Drei";

	function initCategories(){
		$j("#category").change(function(){
			wert = $j(this).val();
			//options zusammenbauen
			if (wert != 0)
				var output = '<option value="0">W&auml;hle hier bitte eine Unterkategorie aus:</option>';
			else
				var output = '';
			for (i = 0; i < subcategories[wert].length; i++) {
				output += '<option value="' + subcategories[wert][i] + '">' + subcategories[wert][i] + '</option>';
			}
			$j("#subcategory").html(output);
		});
	}

	function showLocationForm() {
		//alert("ds");
		$j('div.address label').css('color','#444444');
		$j('div.address input').removeAttr('readonly');
	}

	function hideLocationForm() {
		//alert("ds");
		$j('div.address label').css('color','#A5A5A5');
		$j('div.address input').attr('readonly','readonly');
	}


	function resetMainImage(obj) {
		$j('ul#files li').each(function(){ $j(this).find('.mainImage').show() });
		$j(obj).hide();
		$j('ul#files li').each(function(){ $j(this).find('input').attr('main','0') });
	}

	function initfotoUpload(){
		var btnUpload=$j('#upload');
		var status=$j('#status');
		new AjaxUpload(btnUpload, {
			action: 'javascript/ajax/upload.php',
			name: 'uploadfile',
			onSubmit: function(file, ext){
				 if (! (ext && /^(jpg|png|jpeg|gif)$/.test(ext))){
                    // extension is not allowed
					status.text('Nur JPG, PNG oder GIF Dateien sind erlaubt');
					return false;
				}
				//status.text('Lade Bild hoch ...');
			},
			onComplete: function(file, response){
				//On completion clear the status
				status.text('');
				//Add uploaded file to list
				//Im response bekommen wir den unique Dateinamen
				response = response.split('-----------');
				if(response[0]==="success"){
					if( $j('ul#files').children().length > 1) {
						var wert = $j('li.empty').prev().find('input').attr('name');
						var first = false;
						wert = wert.replace(/Bild/ig, "");
					}
					else {
						var wert = $j('input#Last').val();
					}

					if (first != false) {
						$j('.empty').before('<li><img src="./uploads/' + response[1] + '" alt="Bild" style="" />' +
						'<input type="hidden" value="./uploads/' + response[1] + '" name="Bild' + (parseInt(wert) + 1) + '" />' +
						'<br /><a href="javascript:void(null);" onclick="$j(this).parent().remove();" title="Dieses Bild l&ouml;schen">Dieses Bild l&ouml;schen</a>' +
						'<br /><a href="javascript:void(null);" style="display:none;" class="mainImage" onclick="resetMainImage(this);$j(this).parent().find(\'input\').attr(\'main\',\'1\');" title="Als Hauptbild verwenden">Als Hauptbild verwenden</a></li>');
					}
					else {
						$j('.empty').before('<li><img src="./uploads/' + response[1] + '" alt="Bild" style="" />' +
						'<input type="hidden" value="./uploads/' + response[1] + '" name="Bild' + (parseInt(wert) + 1) + '" />' +
						'<br /><a href="javascript:void(null);" onclick="$j(this).parent().remove();" title="Dieses Bild l&ouml;schen">Dieses Bild l&ouml;schen</a>' +
						'<br /><a href="javascript:void(null);" class="mainImage" onclick="resetMainImage(this);$j(this).parent().find(\'input\').attr(\'main\',\'1\');" title="Als Hauptbild verwenden">Als Hauptbild verwenden</a></li>');
					}

				} else{
					$j('<li></li>').prependTo('#files').text(file).addClass('error');
				}
			}
		});
	}

	function initProfilfotoUpload(){
		var btnUpload=$j('#upload');
		var status=$j('#status');
		new AjaxUpload(btnUpload, {
			action: 'javascript/ajax/upload.php',
			name: 'uploadfile',
			onSubmit: function(file, ext){
				 if (! (ext && /^(jpg|png|jpeg|gif)$/.test(ext))){
                    // extension is not allowed
					status.text('Nur JPG, PNG oder GIF Dateien sind erlaubt');
					return false;
				}
				//status.text('Lade Bild hoch ...');
			},
			onComplete: function(file, response){
				//On completion clear the status
				status.text('');
				//Add uploaded file to list
				//Im response bekommen wir den unique Dateinamen
				response = response.split('-----------');
				if(response[0]==="success"){
					$j('#ProfilImage').find('img').attr('src','./uploads/' + response[1]);
					popupLayer.close();return false;
				} else{
					status.text('Es ist ein Fehler aufgetreten. Bitte versuche es erneut.');
				}
			}
		});
	}



	/**
	 * Funktion um das grosse Bild des Vertikalen Scrollers zu tauschen
	 * @param obj is the link of the image
	 */
	function changeVerticalImage(obj) {
		var tempName = $j(obj).find('img').attr('src');
		var newName = tempName.replace( /\.jpg$/, '_big.jpg' )
		//alert(newName);
		$j('.imageBig').fadeOut(150, function() {
			$j(this).attr('src',newName).load(function() {
		    	$j(this).fadeIn(150);
			});
		});
		return false;
	}

	/**
	 * Funktion um das grosse Bild des Vertikalen Scrollers zu tauschen
	 * @param url is the url for the big version of the image
	 */
	function changeVerticalImage2(url) {
		$j('.imageBig').fadeOut(150, function() {
			$j(this).attr('src',url).load(function() {
		    	$j(this).fadeIn(150);
			});
		});
		return false;
	}

	/**
	 * Funktion um das grosse Bild des Vertikalen Scrollers zu tauschen
	 * @param obj is the link of the image
	 */
	function showContainer(obj,id) {

		//Bewertungsbox hoehe setzen - die gleiche hoehe wie Detailinformationen box
		if(id == 'ReiterBewertung') {
			$j('#ReiterBewertung').css('min-height',$j('#ReiterDetailinformationen').height());
		}

		$j(obj).parent().parent().find('li').removeClass('active');
		$j(obj).parent().addClass('active');

		$j(obj).parent().parent().parent().parent().find('div.container').hide();
		$j("#" + id).show();

	}

	function resetPriceField(obj){
		$j('input.friendsprice').val('0');
		if ($j(obj).parent().find('.checkbox_checked').length > 0) {
			$j('input.sachpreis').attr('readonly', 'readonly');
			$j('input.friendsprice').removeAttr('readonly');
		}
		else {
			$j('input.sachpreis').removeAttr('readonly');
			$j('input.friendsprice').attr('readonly', 'readonly');
		}
	}

	function hidePart(id) {
		$j("#" + id).fadeOut(500);
		return false;
	}

	function showPart(id) {
		$j("#" + id).fadeIn(500);
		return false;
	}

	/* Function to escape special characters in element IDs which are passed to a jQuery selector. */
	function escapeJQueryId(id) { 
		return id.replace(/(:|\.)/g,'\\$1');
	}
	
	function removeSpecialChars(char) { 
		return char.replace(/(:|\.)/g,'');
	}
	

	/* Funktion um auf der Detailseite die Kommentare komplett einzublenden */
	function expandCommentary(id) {
		$j('#' + id).find('li.hidden').each(function(){
			$j(this).show(300);
		});
		$j('#ReiterBewertung').find('h3').html('Die aktuellen Bewertungen - <a class="things link" onclick="closeCommentary(\'Commentary\');return false;" href="javascript:void(null);" title="weniger anzeigen">weniger anzeigen</a>');
	}
	/*
	 	function expandCommentary(id) {
		$j('#' + id).find('li').each(function(){
			var hoehe = $j(this).find('span.bewertung').height();
			$j(this).find('div').animate({height:hoehe},500);
			if ($j.browser.msie && $j.browser.version.substr(0,1)<7)
				$j(this).animate({height:hoehe},500);

		});
		$j('#ReiterBewertung').find('h3').html('Die aktuellen Bewertungen - <a class="things link" onclick="closeCommentary(\'Commentary\');return false;" href="javascript:void(null);" title="weniger anzeigen">weniger anzeigen</a>');
	}
	 */

	function closeCommentary(id) {
		$j('#' + id).find('li.hidden').each(function(){
			 $j(this).hide(300);
		});
		$j('#ReiterBewertung').find('h3').html('Die aktuellen Bewertungen - <a class="things link" onclick="expandCommentary(\'Commentary\');return false;" href="javascript:void(null);" title="alle anzeigen">alle anzeigen</a>');
	}

	/*
		function closeCommentary(id) {
		$j('#' + id).find('li').each(function(){
			var hoehe = $j(this).find('span.bewertung').css('height')
			 $j(this).find('div').animate({height:'14px'},500);
			 if ($j.browser.msie && $j.browser.version.substr(0,1)<7)
			 	$j(this).animate({height:'14px'},500);
		});
		$j('#ReiterBewertung').find('h3').html('Die aktuellen Bewertungen - <a class="things link" onclick="expandCommentary(\'Commentary\');return false;" href="javascript:void(null);" title="alle anzeigen">alle anzeigen</a>');
	}
	 */
	/*
	function getContacts (id) {
		 $j.ajax({
		   type: "GET",
		   url: "javascript/ajax/kontakte.php",
		   data: ({seite : id}),
		   success: function(data){
		 		//$j('#ModuleLeftYourContacts').html('');
				$j('#ModuleLeftYourContacts .inner').animate({ marginLeft: "500px" },function() {
					$j('#ModuleLeftYourContacts .number').html(id + ' von 15')
					$j('#ModuleLeftYourContacts .prev').attr('href','javascript:getContacts('+(id-1)+')');
					$j('#ModuleLeftYourContacts .next').attr('href','javascript:getContacts('+(id+1)+')');
					$j('#ModuleLeftYourContacts .inner').html('');
					$j('#ModuleLeftYourContacts .inner').append(data);
					$j('#ModuleLeftYourContacts .inner').animate({ marginLeft: "0"
				});
			});
		   }
		 });
	}*/


/* Checks/unchecks chechboxes in a target container */
function checkAll(targetContainer){
	$j(targetContainer + ' input').attr('checked', true);
	return false;
}

function uncheckAll(targetContainer){
	$j(targetContainer + ' input').attr('checked', false);
	return false;
}

function checkboxToggle(event, id){
		if($j(event).is(':checked')){
				$j('#' + id).fadeIn(500)
		}else{
				$j('#' + id).fadeOut(500)
		}
}

var searchBox = {
	init: function() {
		var box = $j('#ModuleMyProfile .lookingFor ul.things');
		var listElement = $j('#ModuleMyProfile .lookingFor ul.things li')

		for(i = 0; i<=listElement.length; i++){
			if(i > 2)
				$j(listElement[i]).css('display','none')
		}

		this.bindClicks(box, listElement);
		this.triggers();
	},
	bindClicks: function(box, listElement){
		$j('#ModuleMyProfile .lookingFor a.things').live('click', function(){
			$j(this).toggle(
				function(){
					for(i = 0; i<=listElement.length; i++){
						if(i > 2)
							$j(listElement[i]).css('display','none')
					}
					$j(this).text('alle anzeigen (' + listElement.length + ')');
				},
				function(){
					box.find('li').css('display','block');
						$j(this).text('weniger anzeigen (' + listElement.length + ')');
				}
			)
		})

		$j('#ModuleMyProfile .lookingFor ul.things li').live('click', function(){
			$j(this).toggle(
				function(){
					$j(this).find('.short').css('display', 'none');
					$j(this).find('.full').css('display', 'block');
				},
				function(){
					$j(this).find('.short').css('display', 'block');
					$j(this).find('.full').css('display', 'none');
				}
			)
		})
	},
	triggers: function(){
		$j('#ModuleMyProfile .lookingFor a.things').trigger('click');
		$j('#ModuleMyProfile .lookingFor ul.things li').trigger('click');
	}
}

/* Funktion um unter Mein frents Profil die Textfelder zu speichern und in Inputfelder umzuwandeln*/
/*
function enableEditMode(obj) {
	//suche alle input felder nimm den value und speicher ihn in das hidden input
	$j(obj).parent().parent().find('input[type="text"]').each(function(i) {
		//alert($j(this).val());
		var id = $j(this).attr('id');
		var value = $j('#' + id +'Hidden').val();
		$j(this).val(value)
		$j(this).parent().find('p').hide();
		$j(this).show();
	});
	$j(obj).parent().html('<a href="javascript:void(null);" onclick="cancelEditMode(this);" title="abbrechen"><img src="images/button/btn_abbrechen_profil.gif" alt="abbrechen" /></a><a href="javascript:void(null);" onclick="disableEditMode(this);" title="Speichern"><img src="images/button/btn_speichern_profil.gif" alt="Speichern" /></a>');
}
*/
/* Funktion um unter Mein frents Profil die Formularfelder zu speichern und in Textfelder umzuwandeln*/
/*
function disableEditMode(obj) {
	//suche alle input felder nimm den value und speicher ihn in das hidden input
	$j(obj).parent().parent().find('input[type="text"]').each(function(i) {
		var value = $j(this).val();
		var id = $j(this).attr('id');
		$j('#' + id +'Hidden').val(value);
		$j(this).parent().find('p').html(value);
		$j(this).hide();
		$j(this).parent().find('p').show();
	});
	$j(obj).parent().html('<a href="javascript:void(null);" onclick="enableEditMode(this)" title="&auml;ndern"><img src="images/button/btn_aendern.gif" alt="&auml;ndern" /></a>');
}
*/
/*
function cancelEditMode(obj){
	$j(obj).parent().parent().find('input[type="text"]').each(function(i) {
		var id = $j(this).attr('id');
		var value = $j('#' + id +'Hidden').val();
		$j(this).parent().find('p').html(value);
		$j(this).hide();
		$j(this).parent().find('p').show();

	});
	$j(obj).parent().html('<a href="javascript:void(null);" onclick="enableEditMode(this)" title="&auml;ndern"><img src="images/button/btn_aendern.gif" alt="&auml;ndern" /></a>');
}
*/
