// Entry detail class
var tgmEntryDetailClass = Class.create({
	className:'tgmEntryDetailClass',
	menuEl:null,
	detailEl:null,
	topnavEl:null,
	bodyEl:null,
	entryId:null,
	currentPage:null,
	ivWPixel:null,
	baseUrl: null,
	path: "/cgi-bin/ivw/CP/",
	context: "MEDIA+Eintrag",
	ratingsCharCounter:null,
	ratingsCharCountMax:4000,
	ratingDefaultText: '',
	currentRatingValue: 0,
	
	initialize:function(utilsObject)
	{
		utilsObject.log('tgmEntryDetail initialized');
		
		if ($('detailentry') == null) return;

		this.detailEl = $('detailentry');

		var entryId = this.detailEl.down('div.detail').id;

		// Add menu events
		var menu = $$('div.menu');
		if (menu.length > 0) {
			menu        = menu[0];
			this.menuEl = menu;

			// Attach events to each menu link
			var links = menu.select('li a.menulink');
			if (links.length > 0) {
				links.each(function(link) {
					link.observe('click', this.handleMenuClick.bindAsEventListener(this));
				}.bind(this));
			}
		}

		// Add top nav events
		var topnav = $$('div.topnavdetail');
		if (topnav.length > 0) {
			topnav        = topnav[0];
			this.topnavEl = topnav;

			// Dropmenu
			var selectors = this.detailEl.select('span.menu');
			/*if (this.getPageType() == 'myPage') {
				console.log('myPage');
			} else {
				console.log('irgendwas anderes');
			}*/
			selectors.each(function(topnavSelector) {
				if (topnavSelector != null) {
					//var currentClass = utilsObject.getClassesWithout(topnavSelector, 'menu');
					//var selector = eval('(selector' + counter + ')');//currentClass[0];
					var selector = new tgmDropmenuClass(topnav, utilsObject, topnavSelector);
				}
			}.bind(this));
		}
		
		// Like-Button tracking is documented in Wiki at http://wiki.telegate-media.de/wikka.php?wakka=slotLikeButton#paragraph2
		utilsObject.observeEvent('facebookLikeView', this.facebookLikeView.bindAsEventListener(this));
		utilsObject.observeEvent('facebookLikeClick', this.facebookLikeClick.bindAsEventListener(this));
        
		
		// Detailview
		var divEl =  this.detailEl.down('div.detail');
		if (divEl != null) {
			var entryId = divEl.id.replace(/^entry_/, '');
		}
		this.entryId = entryId;

		this.updateContactLinks();
		this.updatePhoneLinks();
		this.updateFaxLinks();
		this.updateVcfLinks();
		this.updateSmsLinks();
		this.updateEmailLinks();
		this.updatePrintLinks();
		this.updatePdfLinks();
		this.updateBackLink();
		this.updateMapImageLink();
		this.updateVideoPreviewImageLink();
		this.updateRatingStars();
		this.updateReportLinks();
		
		// Ratings box - 4000 chars limit
		this.updateTextCounterElement();
		
		// Slidebox for images
		this.updateSlidebox();

		// Get the body element
		this.bodyEl = $('detailcontainer');

		this.updateSubsidiaryForm(utilsObject);
		
	// Sprint 10 Story 4 - Enable the following line to activate Story 4
	// Like-Button tracking is documented in Wiki at http://wiki.telegate-media.de/wikka.php?wakka=slotLikeButton#paragraph2
		utilsObject.observeEvent('facebookLikeClick', this.handleFacebookLikeClick.bindAsEventListener(this));
		
	},
	
	isPremiumEntry:function()
	{
		return $('detailentry').hasClassName('premium');
	},
	
	isBaseEntry:function()
	{
		return $('detailentry').hasClassName('standard');
	},
	
	handleFacebookLikeClick:function(e)
	{
		new Ajax.Request('/ajax/facebookRating/', {
			parameters:{
				id:this.entryId
			},
			
			onSuccess:function(req)
			{
				// Nada
			}
		});
	},
	
	checkRatingButton:function()
	{
		var setSpan          = $$('div.rating form span.set')[0];
		var setFieldset      = $$('div.rating form fieldset')[0];
		var ratingStars      = setFieldset.select('span.stars');
		var commentField     = setFieldset.select('#ratingText');
		var submitRatingForm = setFieldset.select('#ratingSubmit');
		console.log("check: "+this.ratingDefaultText);
		if (ratingStars.length > 0 && commentField.length > 0) {
			if (ratingStars[0].hasClassName('selected') && (commentField[0].getValue() != '' && commentField[0].getValue() != this.ratingDefaultText)) {
				submitRatingForm[0].disabled = false;
				submitRatingForm[0].removeClassName('disabled');
			} else {
				submitRatingForm[0].disabled = true;
				submitRatingForm[0].addClassName('disabled');
			}
		}
	},
	
	updateVideoPreviewImageLink:function()
	{
		//Add Imagemap Event
		var videopreviewlinks = $$('div#detailentry div#detailcontainer div.subcolumns div.cl div#horizontal_carousel div.container ul li img.videopreview');
		if (videopreviewlinks.length > 0) {
			videopreviewlinks.each(function(videopreviewlink) {
				videopreviewlink.observe('click', this.handleVideoPreviewClick.bindAsEventListener(this));
			}.bind(this));
		}
	},
	
	updateMapImageLink:function()
	{
		//Add Imagemap Event
		var imagemaplinks = $$('div#detailentry div#detailcontainer div.subcolumns div.cr p.location map area.arealink');
		if (imagemaplinks.length > 0) {
			imagemaplinks.each(function(imagemaplink) {
				imagemaplink.observe('click', this.handleLocationImagemapClick.bindAsEventListener(this));
			}.bind(this));
		}
	},

	updateSlidebox:function()
	{
		var slidebox = $('horizontal_carousel');
		if (slidebox != null) {
			var mediaSlidebox = this.detailEl.down('div.slidebox');
			var singleSlidebox = slidebox.down('div.singlepicture');
			if (singleSlidebox == null) {
				var slidebox = new tgmSlideboxClass(slidebox, mediaSlidebox);
			}
		}
	},

	updateContactLinks:function()
	{
		var emailLinks = this.detailEl.select('img.contact, a.contact');
		if (emailLinks.length > 0) {
			emailLinks.each(function(emailLink) {
				if (typeof emailLink.observed == 'undefined' || emailLink.observed == 0) {
					emailLink.observe('click', this.handleContactEmailClick.bindAsEventListener(this));
					emailLink.observed = 1;
				}
			}.bind(this));
		}
	},

	updatePhoneLinks:function()
	{
		var phoneLinks = this.detailEl.select('a.phone');
		if (phoneLinks.length > 0) {
			phoneLinks.each(function(phoneLink) {
				if (typeof phoneLink.observed == 'undefined' || phoneLink.observed == 0) {
					phoneLink.observe('click', this.handleFreecallClick.bindAsEventListener(this));
					phoneLink.observed = 1;
				}
			}.bind(this));
		}
	},

	updateFaxLinks:function()
	{
		var faxLinks = this.detailEl.select('a.fax');
		if (faxLinks.length > 0) {
			faxLinks.each(function(faxLink) {
				if (typeof faxLink.observed == 'undefined' || faxLink.observed == 0) {
					faxLink.observe('click', this.handleFaxClick.bindAsEventListener(this));
					faxLink.observed = 1;
				}
			}.bind(this));
		}
	},

	updateVcfLinks:function()
	{
		var vcfLinks = this.detailEl.select('a.vcf');
		if (vcfLinks.length > 0) {
			vcfLinks.each(function(vcfLink) {
				if (!vcfLink.hasClassName('disabled') && (typeof vcfLink.observed == 'undefined' || vcfLink.observed == 0)) {
					vcfLink.observe('click', this.handleVcfClick.bindAsEventListener(this));
					vcfLink.observed = 1;
				}
			}.bind(this));
		}
	},

	updateSmsLinks:function()
	{
		var smsLinks = this.detailEl.select('a.sms');
		if (smsLinks.length > 0) {
			smsLinks.each(function(smsLink) {
				if (!smsLink.hasClassName('disabled') && (typeof smsLink.observed == 'undefined' || smsLink.observed == 0)) {
					smsLink.observe('click', this.handleSmsClick.bindAsEventListener(this));
					smsLink.observed = 1;
				}
			}.bind(this));
		}
	},

	updateEmailLinks:function()
	{
		var emailLinks = this.detailEl.select('a.email');
		if (emailLinks.length > 0) {
			emailLinks.each(function(emailLink) {
				if (!emailLink.hasClassName('disabled') && (typeof emailLink.observed == 'undefined' || emailLink.observed == 0)) {
					emailLink.observe('click', this.handleEmailClick.bindAsEventListener(this));
					emailLink.observed = 1;
				}
			}.bind(this));
		}
	},

	updatePrintLinks:function()
	{
		var printLinks = this.detailEl.select('a.printview');
		if (printLinks.length > 0) {
			printLinks.each(function(printLink) {
				if (!printLink.hasClassName('disabled') && (typeof printLink.observed == 'undefined' || printLink.observed == 0)) {
					printLink.observe('click', this.handlePrintClick.bindAsEventListener(this));
					printLink.observed = 1;
				}
			}.bind(this));
		}
	},

	updatePdfLinks:function()
	{
		var pdfLinks = this.detailEl.select('a.pdfcurrent');
		if (pdfLinks.length > 0) {
			pdfLinks.each(function(pdfLink) {
				if (!pdfLink.hasClassName('disabled') && (typeof pdfLink.observed == 'undefined' || pdfLink.observed == 0)) {
					pdfLink.observe('click', this.handlePdfClick.bindAsEventListener(this));
					pdfLink.observed = 1;
				}
			}.bind(this));
		}
	},

	updateSubsidiaryForm:function(tgmMain)
	{
		var detailForm = this.bodyEl.down('form');
		if (detailForm != null) {
			tgmMain.fireEvent('onNewForm');

			// Selectbox
			var selectbox = detailForm.down('span.selectbox');
			if (selectbox != null) {
				var sort_selectbox = new tgmSelectboxClass(tgmMain, selectbox);
				var foldoutEl = selectbox.down('span.selectbox_options');
				if (foldoutEl != null) {
					var links = foldoutEl.select('li a, li a img');
					if (links.length > 0) {
						links.each(function(link) {
							link.observe('click', this.getSubsidiaries.bindAsEventListener(this));
						}.bind(this));
					}
				}
			}

			// Subsidiary search form
			var allSubsidiaries = detailForm.down('a.allSubsidiaries');
			if (allSubsidiaries != null) {
				allSubsidiaries.observe('click', this.getSubsidiaries.bindAsEventListener(this));
			}
			var mapView = detailForm.down('a.mapView');
			if (mapView != null) {
				mapView.observe('click', this.displayMap.bindAsEventListener(this));
			}
			var searchSubsidiaries = detailForm.down('button.searchSubsidiaries');
			if (searchSubsidiaries != null) {
				searchSubsidiaries.observe('click', this.getSubsidiaries.bindAsEventListener(this));
			}

			var dropdowns = $$('div.dropdown');
			if (dropdowns.length > 0) {
				dropdowns.each(function (dropdown) {
					if (typeof dropdown.dropdown == 'undefined') {
						var singleDropdown = new tgmUiDropdownClass(tgmMain, dropdown);
						tgmMain.objectPool.push(singleDropdown);
					}
				}.bind(this));
			}

		}

	},
	
	updateBackLink:function()
	{		
		var linkies = $$('div.backtolist');
		if (linkies.length > 0) {
			var backlink  = linkies[0];
			if (history.length == 1 || history.length == 0) {
				backlink.hide();
			} else {
				backlink.show();
			}
		}
	},
	
	updateRatingStars:function()
	{		
		var stars = $$('div.rating form span.set span.stars img');
		var wrapper_stars = $$('div.rating form span.set span.stars');
		
		var frm = $$('div.rating form');
		
		if (frm.length > 0) {
			frm.each(function(frmelement) {
				frmelement.observe('submit', this.submitRatingform.bindAsEventListener(this));
			}.bind(this));
		}
		
		if (stars.length > 0) {
				stars.each(function(star) {
				star.observe('mouseover', this.displayStars.bindAsEventListener(this));
				star.observe('click', this.submitStars.bindAsEventListener(this));
			}.bind(this));
		}
		if (wrapper_stars.length > 0) {
			wrapper_stars.each(function(wrapper_star) {
				wrapper_star.observe('mouseout', this.resetStars.bindAsEventListener(this));
			}.bind(this));
		}
	},
	
	updateReportLinks:function()
	{	
		// Add report rating event
		var ratingList = $('ratingList');
		if (ratingList != null) {
			reportElements = ratingList.select('a.report');
			if (reportElements.size() > 0) {
				reportElements.each(function(reportEl) {
					if (reportEl != null) {
						reportEl.observe('click', this.handleReportClick.bindAsEventListener(this));
					}
				}.bind(this));
			}
		}
	},
	
	updateTextCounterElement:function()
	{	
 	    if ($('ratingText') != null) {
 	    	
 	    	this.ratingDefaultText = $F('ratingTextDefault');
			
			if (typeof(_tag) != "undefined") {
				_tag.DCSext = {};
			}
			
			if(document.referrer){
				var ref = document.referrer.match(new RegExp("(.*)(11880)(.*)/$", "i"));
				if(ref){
					dcsMultiTrack("DCSext.ratingText", '1');
				}
			}

 	    	if ($('starNumberChar') != null) {
				$('starNumberChar').update(this.ratingsCharCountMax);
				this.ratingsCharCounter = this.ratingsCharCountMax;
	        }
			$('ratingText').observe('keyup', this.updateTextCount.bindAsEventListener(this));
		    $('ratingText').observe('click', this.switchRatingText.bindAsEventListener(this));
		    $('ratingText').observe('blur', this.switchRatingText.bindAsEventListener(this));
		}
	},
	
	handleLocationImagemapClick:function(e)
	{
		if (!pandoraData.premiumDomain) {
		
			tgmMain.fireEvent('onLocationImagemapClick', e);
			var el = Event.element(e);
			
			if (el.tagName.toLowerCase() != 'area') {
				el = el.up('area');
			}
			if (el != null) {
				Event.stop(e);
				var url = el.href + '?ajax=1';
			}
			
			var menuElements = $$('div#detailentry div.tabs ul li');
			
			//Select map tab
			var newCurrentTab = $$('div#detailentry div.tabs ul li a.map');
			//if subsidiaries tab exist, take second list element
			if (newCurrentTab.length > 1) {
				newCurrentTab = $$('div#detailentry div.tabs ul li a.map')[1];
			}
			else {
				newCurrentTab = $$('div#detailentry div.tabs ul li a.map')[0];
			}
			newCurrentTab = newCurrentTab.up('li');
			
			if (menuElements.length > 0) {
				menuElements.each(function(menuElement){
					menuElement.removeClassName('current');
					if (menuElement === newCurrentTab) {
						menuElement.addClassName('current');
					}
				});
			}
			this.updateDetailContent(url, 'map');
		}
	},

	handleContactEmailClick:function(e)
	{
		tgmMain.fireEvent('onClickDialogContactEmail', { entryId:this.entryId });
		Event.stop(e);
	},

	handleFreecallClick:function(e)
	{
		var el = Event.element(e);
		if (el.rel != null && el.rel != "") {
			//Entry id is attached to link, for example in subsidiary list
			tgmMain.fireEvent('onClickDialogFreecall', { entryId:el.rel });
		} else {
			tgmMain.fireEvent('onClickDialogFreecall', { entryId:this.entryId });
		}
		Event.stop(e);
	},

	handleFaxClick:function(e)
	{
		var el = Event.element(e);
	
		tgmMain.fireEvent('onClickDialogFax', { entryId:this.entryId });
			
		Event.stop(e);
	},

	handleVcfClick:function(e)
	{
		tgmMain.fireEvent('onClickVcfDownload', { entryId:this.entryId });
		// Nothing to do as real file download only via PHP!
		//Event.stop(e);
	},

	handleSmsClick:function(e)
	{
		tgmMain.fireEvent('onClickDialogSms', { entryId:this.entryId });
		Event.stop(e);
	},

	handleEmailClick:function(e)
	{
		tgmMain.fireEvent('onClickDialogEmail', { entryId:this.entryId });
		Event.stop(e);
	},

	handlePrintClick:function(e)
	{
		//tgmMain.fireEvent('onClickDialogPrint', { entryId:this.entryId });
		tgRoa.sendToServer(this.entryId, 'print');
		window.print();
		Event.stop(e);
	},

	handlePdfClick:function(e)
	{
		var newUrl = Event.element(e).href; //+'&pagetype='+this.getPageType();
		Event.stop(e);
		tgmMain.fireEvent('onClickCreatePdf', { entryId:this.entryId });
		top.location.href = newUrl;
	},
	
	handleVideoClick:function(e)
	{
		if (typeof(e) != "undefined") {
			if (typeof(_tag) != "undefined") {
				_tag.DCSext = {};
			}
			dcsMultiTrack("DCSext.mediaEntryVideo", 'video', "DCSext.mediaEntryVideoReferrer", document.location.href);		

			return "";
		}
	},
	
	handleVideoPreviewClick:function(e)
	{
		
		if (typeof(_tag) != "undefined") {
		    _tag.DCSext = {};
		}
		dcsMultiTrack("DCSext.mediaEntryVideo", 'detail', "DCSext.mediaEntryVideoReferrer", document.location.href);		
		 
		tgmMain.fireEvent('onVideoPreviewClick', e);
		var el = Event.element(e);
		
		if (el.tagName.toLowerCase() != 'img') {
			el = el.up('img');
		}
		if (el != null) {
			Event.stop(e);
		}
		
		var menuElements = $$('div#detailentry div.tabs ul li');
		
		//Select multimedia tab
		var newCurrentTab = $$('div#detailentry div.tabs ul li a.media');
		//if subsidiaries tab exist, take third list element
		if (newCurrentTab.length > 0){
			newCurrentTab = $$('div#detailentry div.tabs ul li a.media')[0];
			var url = newCurrentTab.href + '?ajax=1';
		}
		
		newCurrentTab = newCurrentTab.up('li');

		if (menuElements.length > 0) {
			menuElements.each(function(menuElement) {
				menuElement.removeClassName('current');
				if (menuElement === newCurrentTab) {
					menuElement.addClassName('current');
				}
			});
		}
		
		this.updateDetailContent(url, 'media');

	},

	handleMenuClick:function(e)
	{
		tgmMain.fireEvent('onDetailMenuClick', e);
		var el = Event.element(e);

	
		if (el.tagName.toLowerCase() != 'a') {
			el = el.up('a');
		}
 
		var currentClass = tgmMain.getClassesWithout(el, 'menulink');
		var newLi = el.up('li');

		var listElements = el.up('ul').select('li');
		if (listElements.length > 0) {
			listElements.each(function(listElement) {
				listElement.removeClassName('current');
				if (listElement === newLi) {
					listElement.addClassName('current');
				}
			});
		}
		if (el != null) {
			Event.stop(e);
			var url = el.href+'?ajax=1';
			
			
				
			
			
			if (el.hasClassName("subsidiaries") && el.hasClassName ("menulink")) {
				if (typeof(_tag)!="undefined"){
					_tag.DCSext={};	
				}
				if (!pandoraData.premiumDomain) {
					dcsMultiTrack("DCSext.tabClick", 'subsidiaries');
				}
			}
			
			if (el.hasClassName("detail") && el.hasClassName ("menulink")) {
				if (typeof(_tag)!="undefined"){
					_tag.DCSext={};	
				}
				if (!pandoraData.premiumDomain) {
					dcsMultiTrack("DCSext.tabClick", 'detail');
				}
			}
			
			if (el.hasClassName("map") && el.hasClassName ("menulink") && !el.hasClassName("subsidiaries")) {
				if (typeof(_tag)!="undefined"){
					_tag.DCSext={};	
				}
				if (!pandoraData.premiumDomain) {
					dcsMultiTrack("DCSext.tabClick", 'map');
				}
			}
			
			if (el.hasClassName("media") && el.hasClassName ("menulink")) {
				if (typeof(_tag)!="undefined"){
					_tag.DCSext={};	
				}
				
				if (!pandoraData.premiumDomain) {
					dcsMultiTrack("DCSext.tabClick", 'media');
				}
			}
			
			
			if (el.hasClassName("subsidiaries") && el.hasClassName ("menulink")) {
				this.displayMap(e);
				return;
			}
						
			var rating = el.href.match(/\,(rating)\.html$/);
			
			if(rating){
				if (typeof(_tag)!="undefined"){
					_tag.DCSext={};	
				}
				
				if (!pandoraData.premiumDomain) {
					dcsMultiTrack("DCSext.ratingClick", '1');
					dcsMultiTrack("DCSext.tabClick", 'rating');
				}
			}
			//var matches = el.href.match(/\/([^\/]+)\.html$/);
			var matches = el.href.match(/\/(filialen|karte|multimedia|mypage-1|bewertungen)\.html$/);
			if (matches || el.href.match(/\/$/)) {
				// Premium domain call, must be rewritten
				if (el.href.match(/\/$/)) {
					var urlName = 'detail';
				} else {
					var urlName = matches[1];
				}
				var pageType = 'detail';

				switch(urlName)
				{
					case 'filialen':
						pageType = 'subsidiaries';
					break;
					case 'karte':
						pageType = 'map';
					break;
					case 'multimedia':
						pageType = 'media';
					break;
					case 'mypage-1':
						pageType = 'mypage-1';
					break;
					case 'bewertungen':
						pageType='rating';
					break;
				}
			
				url = '/ajax/premiumDomain?id='+this.entryId+'&pagetype='+pageType;
				
				//top.location.href='#'+''+pageType;
			}
			
			
			if (pandoraData.premiumDomain != 1) {
				
				if(pageType != 'map'){
					
					this.ivWPixel = document.createElement("img");
					this.ivWPixel.style.width = "1px";
					this.ivWPixel.style.height = "1px";
					this.ivWPixel.style.visibility = "hidden";
					
					if ($("klicktel")){
						$("klicktel").appendChild (this.ivWPixel);
					} else if ($("telegate")){
						$("telegate").appendChild (this.ivWPixel);						
					}
					this.baseUrl = "http://klicktel.ivwbox.de";
					
					if (($("klicktel") != null && typeof($("klicktel")) != "undefined") ||
					($("telegate") != null && typeof($("telegate")) != "undefined")) {
						this.ivWPixel.src = this.baseUrl + this.path + this.context + ";/?r=" + document.referrer + "&d=" + (Math.random() * 100000);
					}
					
					if (typeof(_tag)!="undefined"){
						_tag.DCSext={};
					}
					_tag.dcsCollect();
				}
			}
			this.updateDetailContent(url, currentClass);

		}
	},

	updateDetailContent:function(url, page)
	{
		/*var currentHeight = $(this.bodyEl).getHeight();
		this.bodyEl.setStyle({
			height:currentHeight+'px'
		});

		new Effect.BlindUp($(this.bodyEl), { duration:0.3, afterFinish:function() {*/
			this.bodyEl.setStyle({
				height:'auto'
			});
			var indicatorHTML = '<div class="ajaxloader"><img src="/global/img/ajaxloader.gif" alt=""></div>';
			this.bodyEl.update(indicatorHTML);
			this.bodyEl.show();
			new Ajax.Request(url, {
				method: 'get',
				evalScripts:true,
					onComplete: function(transport) {
						if (page == 'mypage') {
							$$('a.pdfcurrent')[0].hide();
						} else {
							$$('a.pdfcurrent')[0].show();
						}
						$('detailcontainer').update(transport.responseText);
						this.currentPage = page;
						this.updateEmailLinks();
						this.updateSlidebox();
						this.updateSubsidiaryForm(tgmMain);
						this.updateMapImageLink();
						this.updateVideoPreviewImageLink();
						this.updateRatingStars();
						this.updateReportLinks();
						this.updateTextCounterElement();
						//top.location.href='#'+page;

						tgmMain.fireEvent('updateDetailContent');
						
						tgmMain.handleFacebookButton();
						
						var currentPdfEl = this.topnavEl.down('a.pdfcurrent');
						currentHref = currentPdfEl.href;
						var matches = currentHref.match(/pdf\/([0-9A-Z]+)-([a-z]+)-(.*)$/);
						var newHref = '/pdf/'+matches[1]+'-'+page+'-'+matches[3];
						currentPdfEl.href = newHref;

						// Display page content
						//if (page == 'map') {
							$(this.bodyEl).show();
						/*} else {
							Effect.SlideDown($(this.bodyEl), { duration:0.7 });
						}*/
						this.updatePhoneLinks();
						this.updateFaxLinks();
					}.bind(this)
			});
		//}.bind(this)});
	},

	getSubsidiaries:function(e)
	{
		var el = Event.element(e);
		if (el.hasClassName('searchSubsidiaries')) { //
			var searchterm 			= $F('searchterm');
			var street 				= $F('street');
			var zipcity 			= $F('zipcity');
			url = '/ajax/premiumDomain/getSubsidiaries?id='+this.entryId+'&searchterm='+searchterm+'&street='+street+'&zipcity='+zipcity;
		} else if (el.hasClassName('selectbox_option')) { // Selectbox option links
			var searchterm 			= $('searchterm').value;
			var street 				= $('street').value;
			var zipcity 			= $('zipcity').value;
			var sort				= el.id;
			url = '/ajax/premiumDomain/getSubsidiaries?id='+this.entryId+'&searchterm='+searchterm+'&street='+street+'&zipcity='+zipcity+'&sort='+sort;
		} else {
			$('searchterm').value 	= $('searchterm').getAttribute('alt');
			$('street').value		= $('street').getAttribute('alt');
			$('zipcity').value		= $('zipcity').getAttribute('alt');
			url = '/ajax/premiumDomain/getSubsidiaries?id='+this.entryId+'&returnAll=1';
		}

		this.updateSubsidiaryList(url);
		Event.stop(e);
	},

	displayMap:function(e)
	{
		url = '/ajax/premiumDomain/displayMap?id='+this.entryId+'&pagetype=subsidiaries';
		//this.updateSubsidiaryList(url);
		/*
		new Ajax.Updater ($$("div .subsidiaries_box")[0], url, {
			method: 'get',
			evalScripts:true,
				onSuccess: function(transport) {
					this.updateSlidebox();
				}.bind(this)
		});
		*/
		this.updateDetailContent(url, "subsidiaries");
		Event.stop(e);
	},
	
	displayStars:function(e)
	{
		
		var el = Event.element(e);
		if (typeof(_tag)!="undefined"){
			_tag.DCSext={};
		}
		
		
		
		//console.log (el.up('span').hasClassName('selected'));
		if (el != null) {
			for (var i = 1; i <= 5; i++) {
				$('star' + i).src = "/global/img/ratings/star_blank.gif";
			}
			
			var elSrc = el.src;
			var elId = el.id.replace(/star/, '', el.id);
			
			//tgmMain.fireEvent(elSrc.match(/_blank/));
			if (elSrc.match(/_blank/) != null) {
				for (var i = 1; i <= elId; i++) {
					$('star' + i).src = "/global/img/ratings/star_full.gif";
				}
			}
			else {
				for (var i = 1; i <= elId; i++) {
					$('star' + i).src = "/global/img/ratings/star_blank.gif";
				}
			}
		}
		return;
	},
	
	submitStars:function(e)
	{
		var el = Event.element(e);
		
		if (el != null){
			if (el.tagName.toLowerCase() == 'img' ) {
				var imgId = el.id.replace(/^star/, '');
				this.currentRatingValue = imgId;
			}
			el = el.up('span');
			el.addClassName('selected');
		}
		this.checkRatingButton();
		return;
	},
	
	submitRatingform: function(e)
	{		
		if (this.currentRatingValue && $F('ratingText').length <= 4000) {	//&& $F('ratingText').length >= 4
			var frm = Event.element(e);
			if (frm.tagName.toLowerCase() != 'form') {
				frm = frm.up('form');
			}
			
			var divEl   = "";
			var entryId = "";
			
			if (frm != null) {
				var divEl   = frm.up('div#detailentry').down('div.detail');
				var entryId = divEl.id.replace(/^entry_/, '');
			}
			
			var bt = frm.down('.ratingbutton');
			bt.addClassName('disabled');
			Form.disable(bt);
			
			var paddingVal = 2;
			if ($('ratings_ajax_loader') == null) {
				var ajaxLoaderEl = new Element('div', { id: 'ratings_ajax_loader' });
				$(document.body).appendChild(ajaxLoaderEl);
				ajaxLoaderEl.setStyle({
					backgroundColor: '#63879c',
					color:'white',
					border:'1px solid white',
					position:'absolute',
					padding: '12px 0px 2px 13px'
				});
				ajaxLoaderEl.update('<img src="/global/img/ajaxloader_notification.gif" style="vertical-align:text-top;margin-right:8px" alt="" /> Bitte warten...');
			} else {
				var ajaxLoaderEl = $('ratings_ajax_loader');
			}
			
			ajaxLoaderEl.show();
						
			ajaxLoaderEl.setStyle({
				left:(parseInt(bt.cumulativeOffset()[0])-paddingVal*2) + 'px',
				top:(parseInt(bt.cumulativeOffset()[1])-paddingVal*2) + 'px',
				width: '170px',
				height: '20px'
			});

			new Ajax.Request('/ajax/ratings/saveRating', {
				method: 'POST',
				evalScripts: true,
				parameters: {
					id: entryId,
					rating: this.currentRatingValue,
					comment: $F('ratingText'),
					userid: tgmMain.userId,
					userh: tgmMain.userH
				},
				onComplete: function(req){
					
					bt.removeClassName('disabled');
					Form.enable(bt);
					ajaxLoaderEl.hide();
					var result = req.responseText;
					var msg = '';			
					if (req.status != 200) {
						msg = 'Es ist leider ein Fehler beim Speichern aufgetreten, bitte versuchen Sie es später erneut.';
					} else {
						if (result == 'SUSPICIOUS') {
							
							//msg = 'Ihre döselige Bewertung wurde nicht veröffentlicht, da sie pöse pöse Worte enthält! Sie böser Mensch, Sie!';
							
							var dlf = new tgmRatingBadwordsDialogClass();
							dlf.show();
							
							
						} else if (result == 'ERROR') {
							msg = 'Es ist leider ein Fehler beim Speichern aufgetreten, bitte versuchen Sie es später erneut.';
						} else if (result == 'NOT_LOGGED_IN') {
							// Show Login
							
							tgmMain.log("here u are");
							tgmMain.ratingInProgress = true;
							tgmLoginDialog.comeFrom='saveRating';
							tgmLoginDialog.show();
							
							//msg = 'Ihre Session ist leider abgelaufen. Bitte laden Sie die Seite neu und loggen sich oben rechts über "Anmelden" neu ein.';
							msg = 'need2Login';
						} else if (result == 'MISSING_DATA') {
							msg = 'Sie haben nicht alle nötigen Daten angegeben.';
						} else if (result == 'INVALID_DATA') {
							msg = 'Sie haben einen ungültigen Stern-Wert angegeben.';
						} else if (result == 'COMMENT_TOO_LONG') {
							msg = 'Der Kommentar ist zu lang. Bitte kürzen Sie den Text und senden Sie das Formular erneut ab.';
						} else if (result == 'ALREADY_RATED') {
							msg = 'Sie haben den Eintrag bereits bewertet.';
						} else if (result == 'INVALID_ENTRY') {
							msg = 'Der angegebene Eintrag ist nicht mehr aktiv und kann nicht mehr bewertet werden.';
						} else if (result == 'NO USERNAME') {
							if (typeof tgmUserNameDialog == 'undefined') {
								var tgmUserNameDialog = new tgmUserNameDialogClass();
							}
							tgmUserNameDialog.show();
						} else if (result == 'SUCCESS') {
							
							
							msg = '';
						} else {
							msg = 'Es ist ein unbekannter Fehler aufgetreten, bitte versuchen Sie es erneut.';
						}
						if (result == 'NO USERNAME') {
							
						} else if (msg == '') {
							// AJAX and MEDIA entry
							if (typeof(_tag)!="undefined"){
								_tag.DCSext={};	
							}
							dcsMultiTrack("DCSext.ratingSaved", '1',"DCSext.entryId",entryId,"DCSext.userid", tgmMain.userId,"DCSext.ratingValue", this.currentRatingValue );
							
							if (entryId.substr(0, 1) == 'Z') {
								// OPO url?
								var newUrl = top.location.href;
								if (newUrl.substr(-12, 12) == ',rating.html') {
									
									top.location.reload();
								}
								else 
									if (newUrl.substr(-5, 5) == '.html') {
										var urlLen = newUrl.length;
										if (newUrl.substr(-1, 1) == '#') {
											newUrl = newUrl.substr(0, urlLen - 1);
										}
										top.location.href = newUrl.substr(0, urlLen - 5) + ',rating.html';
									}
									else 
										if (newUrl.substr(-16, 16) == '&pagetype=rating') {
											top.location.reload();
										}
										else {
											var urlLen = newUrl.length;
											if (newUrl.substr(-1, 1) == '#') {
												newUrl = newUrl.substr(0, urlLen - 1);
											}
											top.location.href = newUrl + '&pagetype=rating';
										}
							//tgmMain.warn('href: '+top.location.href);
							} else {
								if (result != 'SUSPICIOUS') {
									top.location.reload();
								}
							}
							//top.location.reload();							
						} else {
							if (msg != 'need2Login') {
								alert(msg);
							}
						}
					}
					Event.stop(e);
				}.bind(this)
			});
		} else {
			/*if ($F('ratingText').length <= 3) {
				alert('Bitte geben Sie mindestens 4 Zeichen ein.');
			}*/
		}
		Event.stop(e);
			
		return false;
	},

	handleReportClick:function(e)
	{
		var el  = Event.element(e);
		el.blur();
		var msg = '';
		
		var elementDisabled = (el.hasClassName('disabled')) ? true : false;
		var listElementId   = el.up('li.listentry').id;
		if (!elementDisabled && listElementId != null && listElementId.startsWith('rating_')) {
			var encodedRatingId = el.up('li.listentry').id.split('_')[1];
			
			var paddingVal = 2;
			if ($('ratings_ajax_loader') == null) {
				var ajaxLoaderEl = new Element('div', { id: 'ratings_ajax_loader' });
				$(document.body).appendChild(ajaxLoaderEl);
				ajaxLoaderEl.setStyle({
					backgroundColor: '#FFFFFF',
					color:'#63879C',
					position:'absolute',
					padding: '5px 0px 0px 6px'
				});
				ajaxLoaderEl.update('Bitte warten...');
				// <img src="/global/img/ajaxloader_notification.gif" style="vertical-align:text-top;margin-right:8px" alt="" />
			} else {
				var ajaxLoaderEl = $('ratings_ajax_loader');
			}
			
			ajaxLoaderEl.show();
			ajaxLoaderEl.setStyle({
				left:(parseInt(el.cumulativeOffset()[0])-paddingVal*2) + 'px',
				top:(parseInt(el.cumulativeOffset()[1])-paddingVal*2) + 'px',
				width: '115px',
				height: '20px'
			});
						
			new Ajax.Request('/ajax/ratings/addReport', {
				method: 'POST',
				evalScripts: true,
				parameters: {
					ratingId: encodedRatingId
				},
				onComplete: function(req){
					
					var result = req.responseText;
					if (req.status != 200) {
						msg = 'Es ist leider ein Fehler beim Speichern aufgetreten, bitte versuchen Sie es später erneut.';
					} else {
						if (result == 'ERROR') {
							msg = 'Es ist leider ein Fehler beim Speichern aufgetreten, bitte versuchen Sie es später erneut.';
						} else if (result == 'ALREADY_REPORTED') {
							msg = 'Sie haben den Eintrag bereits bewertet.';
						} else if (result == 'SUCCESS_NOT_LOGGED_IN') {
							msg = '';
						} else if (result == 'SUCCESS_LOGGED_IN') {
							msg = '';
							el.removeClassName('javascript');
							el.addClassName('remove disabled');
							if ($("klicktel")) {
								el.update('Eintrag gemeldet');
							}
						} else {
							msg = 'Es ist ein unbekannter Fehler aufgetreten, bitte versuchen Sie es erneut.';
						}
					}
					ajaxLoaderEl.hide();
					if (msg == '') {
						var reportLayer = new Element('div', { id: 'reportNotificationLayer' });
						$(document.body).appendChild(reportLayer);
						reportLayer.setStyle({
							'display':'none',
							'position':'absolute',
							'width':'80px',
							/*'height':'10px', */
							'border':'1px solid #eee',
							'backgroundColor':'#63879C',
							'padding':'6px 1px',
							'zIndex':999999,
							'color':'white',
							'textAlign':'center'
						});
						reportLayer.update('<strong>Bewertung als anstößig gemeldet</strong>');
						var pos     = el.cumulativeOffset();
						var widthD  = 250;
						var leftPos = (pos[0]-70)+'px';
						var topPos  = (pos[1]-30)+'px';
						reportLayer.setStyle({
							'left':leftPos,
							'top':topPos,
							'width':widthD+'px'
						});
						new Effect.Appear(reportLayer);
						window.setTimeout(function() {
							new Effect.Fade(reportLayer);
						}.bind(this), 3000);
						//top.location.reload();			
					} else {
						alert(msg);
					}
				}.bind(this)
			});
		} else if (elementDisabled) {
			//msg = 'Sie haben den Eintrag bereits bewertet.';
			//alert(msg);
		} else {
			msg = 'Error: Rating list element id is not correct! Has to begin with \'rating_\', but is currently '+listElementId;
			alert(msg);
		}
		Event.stop(e);
	},
	
	resetStars:function(e)
	{
		var el = Event.element(e);
		if (el.tagName.toLowerCase() != 'span') {
			el = el.up('span');
		}
		if (el != null && !el.hasClassName('selected')){
			for(var i=1; i<=5; i++) {
				$('star'+i).src = "/global/img/ratings/star_blank.gif";
			}
		} else if (el.hasClassName('selected')) {
			for(var i=1; i<=5; i++) {
				$('star'+i).src = "/global/img/ratings/star_blank.gif";
			}
			for (var i = 1; i <= parseInt(this.currentRatingValue); i++) {
				$('star' + i).src = "/global/img/ratings/star_full.gif";
			}
	}
		return;
	},
	
	updateTextCount:function(e)
	{
		//var currentValue = this.ratingsCharCounter;
		var textValue = Event.element(e).getValue();
		var currentLength = textValue.length;
		this.checkRatingButton();
		if (currentLength == this.ratingsCharCountMax) {
			if (e.keyCode != Event.KEY_BACKSPACE && e.keyCode != Event.KEY_DELETE && e.keyCode != Event.KEY_RETURN && e.keyCode != Event.KEY_ESC && e.keyCode != Event.KEY_LEFT && e.keyCode != Event.KEY_UP && e.keyCode != Event.KEY_RIGHT && e.keyCode != Event.KEY_DOWN && e.keyCode != Event.KEY_HOME && e.keyCode != Event.KEY_END && e.keyCode != Event.KEY_PAGEUP && e.keyCode != Event.KEY_PAGEDOWN) {
				Event.stop(e);
			} else if (e.keyCode == Event.KEY_BACKSPACE || e.keyCode == Event.KEY_DELETE) {
				currentLength = textValue.length;
			}
		} else if (currentLength > this.ratingsCharCountMax) {
			textValue = textValue.substring(0, this.ratingsCharCountMax);
			Event.element(e).setValue(textValue);
			currentLength = textValue.length;
		}
		if ($('starNumberChar') != null) {
			$('starNumberChar').update(this.ratingsCharCountMax - currentLength);
		}
	},
	
	switchRatingText: function(e){
		var el = Event.element(e);
		this.ratingDefaultText = $F('ratingTextDefault');
		console.log(this.ratingDefaultText);
		var elText = this.ratingDefaultText;
		if (el.innerHTML == "") {
			el.innerHTML = elText;
		}
		else if (el.innerHTML == elText) {
			el.innerHTML = "";
		}
	},
	
	displayList: function() {
		//var currentClass = tgmMain.getClassesWithout(el, 'menulink');
		//url = '/ajax/premiumDomain?id='+this.entryId+'&pagetype=subsidiaries';
		url = '/homepage/detail?id='+this.entryId+'&pagetype=subsidiaries&ajax=1';
		this.updateDetailContent(url, "subsidiaries");
		this.ivWPixel = document.createElement("img");
		this.ivWPixel.style.width = "1px";
		this.ivWPixel.style.height = "1px";
		this.ivWPixel.style.visibility = "hidden";
		$("klicktel").appendChild (this.ivWPixel);
		this.baseUrl = "http://klicktel.ivwbox.de";
		
		if (($("klicktel") != null && typeof($("klicktel")) != "undefined") ||
		($("telegate") != null && typeof($("telegate")) != "undefined")) {
			this.ivWPixel.src = this.baseUrl + this.path + this.context + ";/?r=" + document.referrer + "&d=" + (Math.random() * 100000);
		}
		if (typeof(_tag)!="undefined"){
			_tag.DCSext={};
		}
		_tag.dcsCollect();
	},

	updateSubsidiaryList:function(url)
	{
		var resultBox = this.bodyEl.down('div.resultbox');
		var currentHeight = resultBox.getHeight();
		
		$("pandoraForm").style.display = "block";
		
		resultBox.setStyle({
			height:currentHeight+'px'
		});

		var indicatorHTML = '<div class="ajaxloader"><img src="/global/img/ajaxloader.gif"></div>';
		$(resultBox).update(indicatorHTML);

		new Ajax.Request(url, {
			method: 'get',
			evalScripts:true,
				onSuccess: function(transport) {
					$(resultBox).update(transport.responseText);

					//top.location.href='#'+page;

					/*var currentPdfEl = this.topnavEl.down('a.pdfcurrent');
					currentHref = currentPdfEl.href;
					var matches = currentHref.match(/pdf\/([0-9A-Z]+);([a-z]+)-(.*)$/);
					var newHref = '/pdf/'+matches[1]+';'+page+'-'+matches[3];
					currentPdfEl.href = newHref;*/

					// Display page content
					$(resultBox).show();

					this.updateEmailLinks();
					this.updateSlidebox();
				}.bind(this)
		});
	},

	getPageType:function()
	{
		if (pageTypes = location.href.match(/#(.*)/)) {
			return pageTypes[1];
		}
		return 'detail';
	},
	
	facebookLikeView:function(e)
	{
		if (typeof(_tag) != "undefined") {
			_tag.DCSext = {};
		}

		if (this.isPremiumEntry()) {
			dcsMultiTrack("DCSext.facebookLike", 'View', "DCSext.facebookLikeEntryType", 'Premium');
		} else {
			dcsMultiTrack("DCSext.facebookLike", 'View', "DCSext.facebookLikeEntryType", 'Standard');
		}
	},
	
	facebookLikeClick:function(e)
	{
		if (typeof(_tag) != "undefined") {
			_tag.DCSext = {};
		}
		
		if (this.isPremiumEntry()) {
			dcsMultiTrack("DCSext.facebookLike", 'Click', "DCSext.facebookLikeEntryType", 'Premium');
		} else {
			dcsMultiTrack("DCSext.facebookLike", 'Click', "DCSext.facebookLikeEntryType", 'Standard');
		}
	}
});

var tgmEntryDetail;
