/*
Copyright 2008 Google Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

TODO Do something if the user clicks and isn't logged in.
*/

/**
 * jQuery Maxlength plugin
 * @version		$Id: jquery.maxlength.js 18 2009-05-16 15:37:08Z emil@anon-design.se $
 * @package		jQuery maxlength 1.0.5
 * @copyright	Copyright (C) 2009 Emil Stjerneman / http://www.anon-design.se
 * @license		GNU/GPL, see LICENSE.txt
 */

(function($)
{

	$.fn.maxlength = function(options)
	{
		var settings = jQuery.extend(
		{
			events:				      [], // Array of events to be triggerd
			maxCharacters:		  10, // Characters limit
			status:				      true, // True to show status indicator bewlow the element
			statusClass:		    "status", // The class on the status div
			statusText:			    "character left", // The status text
			notificationClass:	"notification",	// Will be added to the emement when maxlength is reached
			showAlert: 			    false, // True to show a regular alert message
			alertText:			    "You have typed too many characters.", // Text in the alert message
			slider:				      false // Use counter slider
		}, options );

		// Add the default event
		$.merge(settings.events, ['keyup']);

		return this.each(function()
		{
			var item = $(this);
			var charactersLength = $(this).val().length;

      // Update the status text
			function updateStatus()
			{
				var charactersLeft = settings.maxCharacters - charactersLength;

				if(charactersLeft < 0)
				{
					charactersLeft = 0;
				}

				item.next("div").html(charactersLeft + " " + settings.statusText);
			}

			function checkChars()
			{
				var valid = true;

				// Too many chars?
				if(charactersLength >= settings.maxCharacters)
				{
					// Too may chars, set the valid boolean to false
					valid = false;
					// Add the notifycation class when we have too many chars
					item.addClass(settings.notificationClass);
					// Cut down the string
					item.val(item.val().substr(0,settings.maxCharacters));
					// Show the alert dialog box, if its set to true
					showAlert();
				}
				else
				{
					// Remove the notification class
					if(item.hasClass(settings.notificationClass))
					{
						item.removeClass(settings.notificationClass);
					}
				}

				if(settings.status)
				{
					updateStatus();
				}
			}

			// Shows an alert msg
			function showAlert()
			{
				if(settings.showAlert)
				{
					alert(settings.alertText);
				}
			}

			// Check if the element is valid.
			function validateElement()
			{
				var ret = false;

				if(item.is('textarea')) {
					ret = true;
				} else if(item.filter("input[type=text]")) {
					ret = true;
				} else if(item.filter("input[type=password]")) {
					ret = true;
				}

				return ret;
			}

			// Validate
			if(!validateElement())
			{
				return false;
			}

			// Loop through the events and bind them to the element
			$.each(settings.events, function (i, n) {
				item.bind(n, function(e) {
					charactersLength = item.val().length;
					checkChars();
				});
			});

			// Insert the status div
			if(settings.status)
			{
				item.after($("<div/>").addClass(settings.statusClass).html('-'));
				updateStatus();
			}

			// Remove the status div
			if(!settings.status)
			{
				var removeThisDiv = item.next("div."+settings.statusClass);

				if(removeThisDiv) {
					removeThisDiv.remove();
				}

			}

			// Slide counter
			if(settings.slider) {
				item.next().hide();

				item.focus(function(){
					item.next().slideDown('fast');
				});

				item.blur(function(){
					item.next().slideUp('fast');
				});
			}

		});
	};
})(jQuery);

function displayMail() {
 $('#submit .input_mail').html('E-Mail (optional) : <input class="required email" type="text" name="mail">');
}

/*
function view_address() {
  elements = document.getElementsByClassName('email');
  if(elements){
        for(i=0;i<elements.length;i++){
              if(elements[i].firstChild){
                  address_to_replace=elements[i].firstChild;
                  real_address=address_to_replace.nodeValue.replace("*a*", "@");
                  address_to_replace.nodeValue=real_address;
                  address_to_replace.parentNode.setAttribute("href", "mailto:"+real_address);
              }
        }
  }
}
*/
function email_antispam() {
	$('.email').each(function(){
		var m = $(this).text();
		m = m.replace('*a*', '@');
		$(this).attr('href', 'mailto:'+m);
		$(this).text(m);
	});
}

function initSubmit() {
	// the facebox for AGB ...
	$('a[rel*=facebox]').facebox();
	// instantiate the validation
	$("#submit").validate({
	  rules: { agb: "required" },
	  errorContainer: $('div.error'),
	  errorLabelContainer: $('div.errorlabel'),
	  invalidHandler: function(form, validator) {
		  var errors = validator.numberOfInvalids();
		  if (errors) {
			var message = 'Bitte alle markierten Felder ausf&uuml;llen. AGB nicht vergessen.';
			$("div.error").html(message);
			$("div.error").show();
		  } else {
			$("div.error").hide();
		  }
		}
	});
	// the textarea counter
	$('#content').maxlength({maxCharacters:399, statusClass:'charsLeft', statusText:''});
}
function initMenu() {
	$('.sddstart').each(function() {
		$(this).css('background', 'transparent url(/img/nav-1-start-a-normal.png) no-repeat scroll 0 0');
	});
	$('.sddeinlesen').each(function() {
		$(this).css('background', 'transparent url(/img/nav-2-einsenden-c-active-lang.png) no-repeat scroll 0 0');
		$(this).css('padding-bottom', '55px');
	});
	$('.sddabstimmen').each(function() {
		$(this).css('background', 'transparent url(/img/nav-3-abstimmen-a-normal.png) no-repeat scroll 0 0');
	});
}

	$(document).ready(function(){
		$('.flashmessage').show().fadeOut(7000);
		//$('#rating').rater('/mod/rank', {style:'basic', maxvalue:5, curvalue:0});
		$('.starrate').each(function(){
			var v = $(this).text();
			var rid = $(this).attr('id');
			var ro = $(this).attr('readonly');
			if(ro !="true") {
				ro = false;
			} else {
				ro = true;
			}
			$(this).text("");
			$(this).rater('/post/rank_it', {readonly:ro, rateid:rid, style:'inline', maxvalue:5, curvalue:v});

		});
		$("#comment0").validate({
		  rules: { email: "required" },
		  errorContainer: $('div.error'),
		  errorLabelContainer: $('div.errorlabel'),
		  invalidHandler: function(form, validator) {
			  var errors = validator.numberOfInvalids();
			  if (errors) {
				var message = 'Bitte alle markierten Felder ausf&uuml;llen.';
				$("div.error").html(message);
				$("div.error").show();
			  } else {
				$("div.error").hide();
			  }
			}
		});
		$('.howto').show();
		$('#howtobutton').click(function(event){
			divToggle();
		});
		// $('a[rel*=facebox]').facebox();
		initSubmit();
        email_antispam(); //view_address();
        $('.sharethis').each(function(){
            var key = $(this).text();
            // alert(key);
        });
    });

function divToggle() {

	if ($('.howto').css('display') == 'none') {

		$('.howto').slideDown();

	} else {

		$('.howto').slideUp();

	}
}

/**
 * jQuery Ajax Rater Plugin
 *
 * This rater is based on the code Ritesh Agrawal did. Unfortunatly his CSS and the hover technique breaks in some browsers.
 * So i thought, why not use the best CSS star-rater known to man kind and throw it in the mix.
 * I have used the CSS and technique from Komodo Media since it is stable and tested on many, many browsers.
 *
 * This rater compared, has no cancel button. But i think we can live with that :)
 * To avoid conflicts i have changed the function name.
 *
 * Licensed under The MIT License
 *
 * @version     1.0
 * @since       03.01.2007
 * @author      Kjell Bublitz <m3nt0r.de@gmail.com
 * @link        http://www.m3nt0r.de/devel/raterDemo/ Demonstration and Documentation
 * @link        http://php.scripts.psu.edu/rja171/widgets/rating.php Based on Ritesh Agrawal Star Rating System
 * @link        http://komodomedia.com/blog/index.php/2007/01/20/css-star-rating-redux/ The Komodo Media CSS Rater Blogpost
 * @license     http://www.opensource.org/licenses/mit-license.php MIT
 * @package     jQuery Plugins
 * @subpackage  Rater
 */

/**
 * Usage: $('#rating').rater('your_servlet', {style:'basic', maxvalue:5, curvalue:0});
 *
 * @param url The address you want to post the result to.
 * @param options The style and value attributes
 *
 * Valid options:
 * ---------------------------------------
 *       style:       'basic', 'inline' OR 'small'
 *       maxvalue:    the maximum value / number of stars
 *       curvalue:    the initial value / selected stars
 */
jQuery.fn.rater = function(url, options)
{
	if(url == null) return;
	var settings = {
		url       : url, // post changes to
		maxvalue  : 10,   // max number of stars
		curvalue  : 0,    // number of selected stars
		readonly  : false,  // can modify the rating if false
		rateid    : ""    // the id to rate
	};

	if(options) { jQuery.extend(settings, options); };
	jQuery.extend(settings, {cancel: (settings.maxvalue > 1) ? true : false});

	var container = jQuery(this);
	jQuery.extend(container, { averageRating: settings.curvalue, url: settings.url });

	if(!settings.style || settings.style == null || settings.style == 'basic') {
		var raterwidth = settings.maxvalue * 16; // war 25
		var ratingparent = '<ul class="star-rating" style="width:'+raterwidth+'px">';
	}
	if(settings.style == 'small') {
		var raterwidth = settings.maxvalue * 10;
		var ratingparent = '<ul class="star-rating small-star" style="width:'+raterwidth+'px">';
	}
	if(settings.style == 'inline') {
		/*
		var raterwidth = settings.maxvalue * 10;
		var ratingparent = '<span class="inline-rating"><ul class="star-rating small-star" style="width:'+raterwidth+'px">';
		*/
		var raterwidth = settings.maxvalue * 16;
		var ratingparent = '<span class="inline-rating"><ul class="star-rating" style="width:'+raterwidth+'px">';
	}
	container.append(ratingparent);

	// create rater
	var starWidth, starIndex, listitems = '';
	var curvalueWidth = Math.floor(100 / settings.maxvalue * settings.curvalue);
	for(var i = 0; i <= settings.maxvalue ; i++) {
		if (i == 0) {
			listitems+='<li class="current-rating" style="width:'+curvalueWidth+'%;">'+settings.curvalue+'/'+settings.maxvalue+'</li>';
		} else {
			starWidth = Math.floor(100 / settings.maxvalue * i);
			starIndex = (settings.maxvalue - i) + 2;
			if(settings.readonly) {
				listitems+='<li class="star"></li>';
			} else {
				listitems+='<li class="star"><a href="#'+i+'" title="'+i+'/'+settings.maxvalue +'" style="width:'+starWidth+'%;z-index:'+starIndex+'">'+i+'</a></li>';
			}
		}
	}
	container.find('.star-rating').append(listitems); // i am using find here, because the span wrapped in the small style would break children()

	if(settings.maxvalue > 1) // add a container for the ajax result
	{
		container.append('<span class="star-rating-result"></span>');
	}
	var stars = jQuery(container).find('.star-rating').children('.star');
	stars.click(function()
	{
		if(settings.maxvalue == 1) // on / off
		{
			settings.curvalue = (settings.curvalue == 0) ? 1 : 0;
			jQuery(container).find('.star-rating').children('.current-rating').css({width:(settings.curvalue*100)+'%'});
			jQuery.post(container.url, { "rateid": settings.rateid, "rating": settings.curvalue });
			return false;
		}
		else
		{

			settings.curvalue = stars.index(this) + 1;
			raterValue = jQuery(this).children('a')[0].href.split('#')[1];
			jQuery.post(container.url, { "rateid": settings.rateid, "rating": raterValue }, function(response){
				container.children('.star-rating-result').html(response)
			});
			container.find('ul.star-rating').hide(); // hide to refuse voting again
			return false;
		}
		return true;
	});

	return this; // strict warning: anonymous function does not always return a value. fix?
}


