var ws = ws || {};
$.extend(ws,{
	init: function() {
		// set ie fallbacks
		if ($.browser.msie) {
			$('body').addClass('is-ie')
		} 
		
		/* init flaps */
		var flaps = $('aside section h3');
		flaps.click(function(){
			var t = $(this).parent('section'),
				open = t.hasClass('flap-open');
			$(this).next()[(open) ? 'slideUp' : 'slideDown'](function(){
				t[(open) ? 'removeClass' : 'addClass']('flap-open')
			})
		})
		// validate submitted contact or guestbook data
		if ($('.guestbook, .contact').length) {
			$('#content>section form').submit(function(e){
				e.preventDefault()
				var t = $(this),
					errortoken = false,
					tbv = t.find('[required]'), // to be validated
					error = (t.has('.error').length) ? t.find('.error') : $('<div />', {'class':'error'}).prependTo(t);
				
				// check if prepend gives correct element back!

				tbv.each(function(){
						if ($(this).val()=='') {
							errortoken = true;
							$(this).addClass('ws-error');
						}
					})
					.focus(function() {
						$(this).removeClass('ws-error');
						$('.msg').fadeOut(300);
					})
				if (errortoken) {
					// output error message, but prevent doubling the same message.
					ul = (t.has('.error ul').length) ? t.find('>ul').empty() : $('<ul />').prependTo(error);
					
					if (!ul.has('li.fe-error').length) {
						$('<li class="fe-error">Bitte füllen Sie alle notwendigen Felder aus!</li>').appendTo(ul).fadeIn()
					}
				} else {
					error.ajaxError(function() {
						$(this).append('<li>Ajax error.</li>');
					});
					
					// attach submit button value
					var submitparam = '&submit='+t.find(':submit').val();
					
									
					$.post(t.attr('action'), t.serialize()+submitparam, function(data) {
						var newData;
						try {
							newData = $(data);
							if (newData.length > 0) {
								newData.hide().insertBefore('article:first').fadeIn()
								$('article:last').remove()
								error.remove()
								$(':reset').click()
							} else {
								ul = (t.has('.error ul').length) ? t.find('.error>ul').empty() : $('<ul />').prependTo(error);
								$('<li/>',{text:data}).appendTo(ul).fadeIn();
							}
						} catch(e) {
						
						}
					});
				}
			})
		}

		// delete guestbook items, prevent default action on links
		$('.gb-delete article a').click(function(e) {
			e.preventDefault()
		});
		$('.gb-delete article').click(function(e){
			var t = $(this);
			
			t.addClass('gb-delete-this')
			
			if (confirm('Wollen Sie wirklich diesen Eintrag löschen? Diese Aktion kann nicht rückgängig gemacht werden!')) {
				var	cssclass = t.attr('class'),
					idpos = cssclass.indexOf('id-')+3,
					id = cssclass.substr(idpos, 10);
				$.post('edit_gb.php', 'deleteentry='+id, function(data) {
					t.fadeOut(400, function() {
						t.remove()
					})
				})
			} else {
				t.removeClass('gb-delete-this')
			}
		})
		
		// add hover note to h1
		var note = $('<span />', {
				'text':'Zur Startseite'
			}),
			headline = $('h1 a');
		headline.after(note)
				.hover(
					function(){ note.show() },
					function(){ note.hide() }
				)
		
		
		/* ie6 notice */
		if ($.browser.msie && $.browser.version < 7) {
			var bar = $('<div />', {
						'class': 'ie6bar',
						text: 'Bitte aktualisieren Sie Ihren Browser. Er ist unsicher, veraltet und langsam.',
						click: function(){
							$(this).slideUp()
						}
					}
				);
				bar.append('<a href="http://www.microsoft.com/germany/windows/internet-explorer/default.aspx">Zur Microsoft Seite</a>')
					.prependTo('body')
		}
		
		/* sidebar newsletter mode switch */
		var line = $('<div />', {
				'class':'line cf'
				}),
			modes = $('<input type="radio" name="modus" id="radio_an" value="Anmelden" checked="checked" />'
			+'<label for="radio_an">Anmelden</label>'
			+'<input type="radio" name="modus" id="radio_ab" value="Abmelden" />'
			+'<label for="radio_ab">Abmelden</label>'),
			nl_form = $('.side-newsletter form'),
			ws_url = 'http://www.landgasthaus-waldschenke.de/',
			nl_unsub = 'newsletter-abmeldung/',
			nl_sub = 'newsletter-anmeldung/',
			nl_url_ok = nl_form.find('input[name="url_ok"]'),
			nl_url_err = nl_form.find('input[name="url_error"]');

		line.append(modes);
		nl_form.prepend(line)
			.find(':radio').change(function(){
				nl_form.find(':submit').val($(this).val())
					
				if ($(this).val()=='Abmelden') {
					nl_form.attr('action','http://tools.emailsys.net/88/174/1u6djgn/unsubscribe/form.html')
					nl_url_ok.val(ws_url	+ nl_unsub + 'erfolg/')
					nl_url_err.val(ws_url	+ nl_unsub + 'fehler/')
				} else {
					nl_form.attr('action','http://tools.emailsys.net/88/174/1u6djgn/subscribe/form.html')
					nl_url_ok.val(ws_url	+ nl_sub + 'erfolg/')
					nl_url_err.val(ws_url	+ nl_sub + 'fehler/')
				}
			})
		
		
		/* radio items on contact */
		function set_requirements(radios) {
			// setting required and removing error highlighting
			var t = radios,
				v = t.val();

			t.siblings('input:radio').each(function(){
				$('#contact-'+$(this).val())
					.removeAttr('required')
					.removeClass('ws-error fe-error');
			})
			if(v!='none') {
				$('#contact-'+v).attr('required','required')
			}
		}
		
		set_requirements($('.radioblock input:checked'))
		$('.radioblock input:radio').click(function(){
			set_requirements($(this))
		})
		
		
		// social media services
		var path = encodeURIComponent(location.pathname),
			host = "http%3A%2F%2Fwww.landgasthaus-waldschenke.de";
		
		function resolveShareServices (service,serviceurl,textparam, article, anchor, headline) {
			// customizes each standard link to fit to its article
			// escaped hash when anchor is set
			if (anchor != '') {
				anchor = '%23' + anchor;
			}
			var newHref = serviceurl + host + path + anchor +
						"&" + textparam + "=" + headline.replace(/ /g, "+");
			
			article.find('.share_'+service).attr('href',newHref)
		}			
		
		// setup share links
		var articles = $('article').has('footer');
		articles.each(function(){
			var t = $(this),
				anchor = (t.attr('id') != undefined) ? encodeURIComponent(t.attr('id')) : '',
				headline = encodeURIComponent(t.find('h2').eq(0).text());

			resolveShareServices("twitter","http://twitter.com/share?url=","text", t, anchor, headline)
			resolveShareServices("fb","http://www.facebook.com/sharer.php?u=","t", t, anchor, headline)
			resolveShareServices("wong","http://www.mister-wong.de/index.php?action=addurl&bm_url=","bm_description", t, anchor, headline)
		})
	}
})
$(ws.init)
