/* this prevents dom flickering, needs to be outside of dom.ready event: */
document.documentElement.className += 'js_active';
/*end dom flickering =) */

jQuery.noConflict();

jQuery(document).ready(function()
{	
	
	/*Ajax Phonebook functions*/
	pb_show_modify();
	if(jQuery('.no_ajax_phonebook').length == 0) pb_modify_entry();
	/**************************************************************/

	/*prettyphoto lightbox, used for image overlays, video overlays and modal windows (for example 'choose language overlay')*/
	lightbox();
	/**************************************************************/
	
	resend_mail();
	/**************************************************************/
	
	/*function that converts html comments to 'real' html source code*/
	comment2html('.comment2html','append');
	/**************************************************************/
	
	/*embed the video into the site*/
	video_product();
	/**************************************************************/
	
	/*embed the video into the site*/
	video_teaser();
	/**************************************************************/

	
	/*Javascript login form*/	
	js_login_form();
   	/**************************************************************/

	/*Instant test ajax*/	
	js_instant_test();
   	/**************************************************************/

    rounded_corner(".rounded:not(#product_video)");
    // SMS functions
    SMS_counter();
    SMS_Number_adapt();
    
    // trigger help container:
    show_help();
	    
    //Wlan select box trigger
    Wlan_select_switch();
    
    //JAVASCRIPT FORM VALIDATION
    validate_form_element();
    
    //LANGUAGE OVERLAY
    language_overlay('#language_overlay');
    
    //content slider
    jQuery('#content_slide_box3').simple_slide();
    
    // Check checkbox in registration page one.
    Disable_send();
    
    // Disable button to send contact form when text field is empty
    Contact_content_check();
    
    //font replacement:
    Cufon.replace('.heading');
    
    // handle language dropdown
    Language_Dropdown();
    
    // Register Country Switch, to adapt the dial in code to the prefix field
    Country_number_adapt();
    
    // eplus number warning (registration, preferences)
    //eplus_info_show();
    //eplus_info_show_preferences();
    
    // Prevent empty fields on CC formular submit
    empty_cc_send();
    
    // Ajax preloader for JSV
    //jsv_preload();
    //jsv_action();
    
    
    // Extend footer to bottom if needed
    footer_extend();
    
    // Facebook Like Button length check
    //facebook_like();
    
    // Check if user pays with JS enabled
    check_payment_js();
    
    // CVC Tooltip Popup
    cvc_hint();
    
    // Show payment method tooltips
    payment_tooltip();
});

function payment_tooltip()
{
    // Use the title of label tags to create a tooltip shown on payment
    // page 1
    
    // Save some vars
    var tooltip_box = jQuery('#payment_method_info');
    
    if(tooltip_box.length != 0)
    {
        var method_inputs = jQuery('#choose_payment input:radio');
        var selected_input = jQuery('#choose_payment input:checked');
        var selected_label = jQuery(selected_input).parent();
        
        console.log('Selected input value is: "'+selected_input.val()+'" \nTitle of selected input label is: "'+selected_label.attr('title')+'"');
        
        if(selected_label.attr('title') != 0)
        {
            tooltip_box.html('<p>'+selected_label.attr('title')+'</p>');
        }
        
        method_inputs.bind('click', function(){
            if(tooltip_box.find('p') != 0)
            {
                tooltip_box.find('p').replaceWith('<p>'+jQuery(this).parent().attr('title')+'</p>');
                
                // Strip previously selected item of class "clicked" and distribute
                // on clicked element.
                var clicked = jQuery('.clicked_radio');
                clicked.removeClass('clicked_radio');
                jQuery(this).parent().addClass('clicked_radio');
            }
        });
    }
}

function cvc_hint()
{
    // Popup a hint box when hovering the CVC tooltip
    
    // debug
    //jQuery(document).mousemove(function(e){
    //    //console.log('Mouse X is '+e.pageX+'\n Mouse Y is '+e.pageY);
    //});
    
    // The hover item
    var hover_item = jQuery('#cvc_hint');
    
    // The hint box
    var hint_box = jQuery('#hint_box');
    
    // show 
    hover_item.mouseover(function(){
        hint_box.stop(true).css('display', 'block').fadeTo("normal",1);
    });
    
    hover_item.mouseout(function(){
        hint_box.fadeTo("normal",0, function(){
            hint_box.css('display', 'none');
        });
    });
}


function check_payment_js()
{
    // This function checks if a user has javascript activated when submitting payment step 3.
    var js_payment_check = jQuery('#js_payment_check');
    
    if(js_payment_check)
    {
        if(js_payment_check.val() == 'OFF')
        {
            js_payment_check.val('ON');
        }
    }
}

function facebook_like()
{
    // TODO:
    // Get the iframe plugin to work. This needs some testing.
    
    // Check the language of the facebook like button. Set length of iframe accordingly
    var facebook_iframe = jQuery('#fb_like');
    
    var facebook_iframe_body = jQuery('#fb_like').find('body');
    facebook_iframe.addClass('worx');
    // Check if there is an iframe
    if(facebook_iframe)
    {
        // Check for attribute language and value of it
        if(facebook_iframe_body.attr('lang') && facebook_iframe_body.hasClass('Locale_de_DE'))
        {
            facebook_iframe.length(90);
        }
        else if(facebook_iframe_body.attr('lang') && facebook_iframe_body.hasClass('Locale_en_US'))
        {
            facebook_iframe.length(55);
        }
        else if(facebook_iframe_body.attr('lang') && facebook_iframe_body.hasClass('Locale_en_GB'))
        {
            facebook_iframe.length(55);
        }
        else if(facebook_iframe_body.attr('lang') && facebook_iframe_body.hasClass('Locale_en_UD'))
        {
            facebook_iframe.length(55);
        }
        else if(facebook_iframe_body.attr('lang') && facebook_iframe_body.hasClass('Locale_en_UD'))
        {
            facebook_iframe.length(55);
        }
        else if(facebook_iframe_body.attr('lang') && facebook_iframe_body.hasClass('Locale_es_LA'))
        {
            facebook_iframe.length(80);
        }
        else if(facebook_iframe_body.attr('lang') && facebook_iframe_body.hasClass('Locale_es_ES'))
        {
            facebook_iframe.length(80);
        }
    }

}


function footer_extend()
{
    // get the viewport height. compare it to the height of the page
    // if the viewport is bigger than the page content, create a div
    // with a height matching the difference between viewport and site height.
    // Purpose is to fix the footer at the bottom of the page.
    console.log('hallo ich bin der dominik, und ich bin gefangen in der toolani seite!!');
    
    var viewportwidth;
    var viewportheight;
    
    // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
    
    if (typeof window.innerWidth != 'undefined')
    {
      viewportwidth = window.innerWidth,
      viewportheight = window.innerHeight
    }
    
    // IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
    
    else if (typeof document.documentElement != 'undefined'
     && typeof document.documentElement.clientWidth !=
     'undefined' && document.documentElement.clientWidth != 0)
    {
       viewportwidth = document.documentElement.clientWidth,
       viewportheight = document.documentElement.clientHeight
    }
    
    // older versions of IE
    else
    {
       viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
       viewportheight = document.getElementsByTagName('body')[0].clientHeight
    }
    
    //console.log(viewportwidth);
    //console.log(viewportheight);
    
    var footer = jQuery('#footer');
    
    footer.after('<div id="marker" style="position: relative; float: left; width: 100px; height: 2px; background-color: #AAA;"></div>');
    
    var pagesize = jQuery('#marker').offset();
    
    if(viewportheight > pagesize.top)
    {
        var spacer_height = Math.round((viewportheight - pagesize.top));
        footer.before('<div id="footer_positioner" style="float: left; position: relative; clear: both;"></div>');
        jQuery('#footer_positioner').animate({
            height: spacer_height
        }, 700, function(){
            jQuery('#marker').remove();
        });
    }
    else
    {
        jQuery('#marker').remove();
    }
}



/*
SIMPLE SLIDE - Content slider jQuery plugin by Kriesi

Switches content elements

Parameters:
transition: 'fade','crossfade','slide'
durationShow: int in milliseconds
durationTransition: int in milliseconds
elements: child elements to slide as class: '.slide'

*/

(function($)
{
	$.fn.simple_slide = function(options) 
	{
		var defaults = 
		{
			transition: 'fade',
			durationShow: 8000,
			durationTransition:400,
			elements: '.slide',
			autoslide: true,
			selectionElements: true
		};
		
		// merge default values with the values that were passed with the function call
		var options = $.extend(defaults, options);
		
		return this.each(function()
		{	
			// save some jQuery selections into variables
			var slideWrapper 	= $(this),
				slides			= slideWrapper.find(options.elements),
				noActiveTransition = true;
				
				
				//check is seletion elements is enabled and add the elements to the slideWrapper
				if(options.selectionElements)
				{
					var controlls = $('<div></div>').addClass('slidecontrolls').css({position:'absolute'}).appendTo(slideWrapper);
					
					slides.each(function(i)
					{	
						var current_class = "";
						
						if (i == 0)
						{
							current_class = 'class="active_item"';
						}
						controlls.append('<span '+current_class+'></span>');
					});		
					
					$(controlls).find('span').each(function(i)
					{	
						var count = i;
						
						$(this).bind('click',function()
						{	
							if(!$(this).is('.active_item'))
							{
								changeSlide(count);
							}
							if(interval)
							window.clearInterval(interval);
						});
					});	
				}
				
				
				//if autosliding is enabled set auto rotation function
				if(options.autoslide)
				{
					var interval = setInterval(function() { changeSlide(); }, options.durationShow );
				}
				
				var nextControll = 0;
				//the main function that changes the slide
				function changeSlide(count)
				{
					var currentSlide = slides.filter(':visible'),
						nextSlide;
					
					if(count >= 0)
					{
						nextSlide = slides.filter(':eq('+count+')');
						nextControll = count;
					}
					else
					{
						if(currentSlide.next(options.elements).length > 0)
						{
							nextSlide = currentSlide.next(options.elements);
							nextControll = nextControll + 1;
						}
						else
						{
							nextSlide = slides.filter(':eq(0)');
							nextControll = 0;
						}
					}
					
					if (noActiveTransition)
					{	
						noActiveTransition = false;
						currentSlide.fadeOut(options.durationTransition, function()
						{
							nextSlide.fadeIn(options.durationTransition, function()
							{
								noActiveTransition = true;
							});
						});	
						
						if(options.selectionElements)
						{
							$('.slidecontrolls>.active_item').removeClass('active_item');
							$('.slidecontrolls span').filter(':eq('+nextControll+')').addClass("active_item");	
						}
					}
					
						
				}
		});
	
	};
})(jQuery);





/* 
LANGUAGE OVERLAY 

If the element $overlay_available is set and found, display the content of this div at page startup
This is used to display the Language Overlay Modal window 

*/
function language_overlay($overlay_available)
{	
	overlay_div = jQuery($overlay_available);
	
	if(overlay_div.length > 0)
	{
		// open overlay with prettyphoto
		jQuery.prettyPhoto.open('#language_overlay');
		
		// set a cookie for the current zone
		var current_zone = jQuery('#language_overlay').attr('class');		
		jQuery.cookie("toolani_user_country", current_zone, { path: '/', expires: 9999 });		

		//only when user chooses to open other domain change cookie value
		jQuery('.changelanguage').live("click", function()
		{	
			var newzone = jQuery('.changelanguage').attr('rel');
	     	jQuery.cookie("user_country", newzone, { path: '/', expires: 9999 });
	     	window.location.href = jQuery('.changelanguage').attr('href');
	     	return false;
	    });
	    
	    //when user wants to keep language close lightbox
		jQuery('.keeplanguage').live("click", function()
		{	
	     	jQuery.prettyPhoto.close();
	     	return false;
	    });
	    
	}
}



/*
JAVASCRIPT FORM VALIDATION

This function validates form elements with certain classes and sends an error message to the
element with class .error that is located within the same 'p' as the validated element.

<p>
	<input class='is_email' /> 	<-- element to validate
	<span class="error"/> 		<-- elemt to display error
</p>


Working classes are:
.is_empty 		- checks if any value is set
.is_number		- checks if value is a number
.is_email		- checks if value is an email
.is_range[x-x]	- number of characters between range x and x: for example 5 and 50

*/

function validate_form_element()
{	
	//check input fields, select boxes and textareas
	jQuery('input, select, textarea').each(function()
	{	
		var currentElement = jQuery(this);
		var errorElement = currentElement.parent('p').find('.error');
		
		//when cursor leaves input field
		currentElement.bind("blur", function()
		{	
			var value = currentElement.val();
			var classes = currentElement.attr('class');
			
			//clear error at beginn of check
			errorElement.text('');
			
			//BEGINNING of checks:
			
			//check if field is not empty
			if(classes.match(/is_empty/))
			{
				if(value == '')
				{
					var errorcode = classes.match(/is_empty\[(\d+)\]/);
					errorElement.text(js_errorlist[errorcode[1]]);
				}	
			}
			
			// check if field has email value
			if(classes.match(/is_email/))
			{
				if(!value.match(/^\w[\w|\.|\-]+@\w[\w|\.|\-]+\.[a-zA-Z]{2,4}$/))
				{
					var errorcode = classes.match(/is_email\[(\d+)\]/);
					errorElement.text(js_errorlist[errorcode[1]]);
				}
			}
			
			//check if field has number value
			if(classes.match(/is_number/))
			{
				if(!value.match(/^(\d+)$/))
				{	
					var errorcode = classes.match(/is_number\[(\d+)\]/);
					errorElement.text(js_errorlist[errorcode[1]]);
				}
			}
			
			//check min and max characters of value
			if(classes.match(/is_range/))
			{
				var range = classes.match(/is_range\[(\d+)-(\d+)\]\[(\d+)\]/);
				
				if(value.length < range[1] || value.length > range[2])
				{
					var errorcode = classes.match(/is_range\[(\d+)-(\d+)\]\[(\d+)\]/);
					errorElement.text(js_errorlist[errorcode[3]]);
				}
			}
			
			
		});
	});
}


function js_login_form()
{	

	if(!jQuery.browser.msie ||  (jQuery.browser.msie && jQuery.browser.version >= 7))
	{
		comment2html('#js_login_form','append');
		
		$button = jQuery('.member_login>a');
		$form = jQuery('#js_login_form');
		$user_input = jQuery('#user');
		
		if($button.hasClass('open'))
		{
			$form.css("display","block");
		}
		
		$button.click(function()
		{
		
			if ($form.hasClass('open'))
			{
				$form.stop().removeClass('open').animate({'opacity':0},500,function()
				{
					$form.css('display','none');
				});
			}
			else
			{
				$form.stop().addClass('open').css({display:'block',opacity:0}).animate({'opacity':1},500);
				$user_input.focus();
			}
			
			return false;
		});
	}
}


function video_product()
{	var $firstclick = true;

	jQuery('#button_video').bind('click',function(){
		if($firstclick)
		{	
			$firstclick = false;
			var $videourl = comment2html('#product_video','return');
						
			jQuery('#product_video').flash(
	        { src: $videourl,
				width: 340,
				height: 230,
				flashvars:{
				imagePath : "",
				videoPath : "info.flv",
				autoStart : "true",
				autoHide : "true",
				autoHideTime : "3",
				hideLogo : "true",
				volAudio : "80",
				disableMiddleButton : "true",
				playSounds : "true",
				soundBarColor : "0xdddddd",
				barColor : "0xff9000",
				barShadowColor : "0xdddddd",
				subbarColor : "0x666666",
				extendVideo : "true"
	          }, 
	          allowfullscreen :'true',
	          wmode : "transparent"
	          },
	        { version: 8 });
	    	jQuery('.product_video_fade').animate({opacity:"0"},function(){
	    	
	    		jQuery(this).css("z-index","0");
	    	
	    	});
		}		
	return false;
	});
	
}

function video_teaser()
{	var $firstclick = true;

	jQuery('#button_video').bind('click',function(){
		if($firstclick)
		{	
			$firstclick = false;
			var $videourl = comment2html('#teaser_video','return');
						
			jQuery('#teaser_video').flash(
	        { src: $videourl,
				width: 351,
				height: 197,
				flashvars:{
				imagePath : "",
				videoPath : "toolanioverall.flv",
				autoStart : "true",
				autoHide : "true",
				autoHideTime : "1",
				hideLogo : "true",
				volAudio : "80",
				disableMiddleButton : "true",
				playSounds : "true",
				soundBarColor : "0xdddddd",
				barColor : "0xff9000",
				barShadowColor : "0xdddddd",
				subbarColor : "0x666666",
				extendVideo : "true"
	          }, 
	          allowfullscreen :'true',
	          wmode : "transparent"
	          },
	        { version: 8 });
	    	jQuery('.teaser_image').animate({opacity:"0"},function(){
	    	
	    		jQuery('#teaser_video').css("z-index","5");
				jQuery('#teaser_video').animate({opacity:"100"});
				
	    	
	    	});
		}		
	return false;
	});
	
}




function comment2html($selector, $output)
{	
	var $childnode;
	
	
	jQuery($selector).each(function()
	{ 
		
		$childnode = jQuery(this).html().replace(/^\s*<!--/,"").replace(/-->\s*$/,"");
		
		if($output == 'append')
		{
			jQuery(this).append($childnode);
		}
	});
	
	return $childnode;
}




// Function to query ddi and display result in ajax
function js_instant_test()
{
    // Only activate instant test when on home
    var home_check = jQuery('#instant_test_container');
    
    if(home_check)
    {
        //console.log('js_instant_test started ... ');
        
        // Define some vars
        var instant_test_field = jQuery('#instant_test_box');
        var instant_test_cancel = jQuery('#instant_test_cancel');
        var instant_test_submit = jQuery('#instant_test_submit');
        var instant_test_cli = jQuery('#instant_test_cli');
        var instant_test_destnum = jQuery('#instant_test_destnum');
        var instant_test_captcha = jQuery('#instant_test_captcha');
        var instant_test_step1 = jQuery('#instant_step_1');
        var instant_test_step2 = jQuery('#instant_step_2');
        var instant_test_step3 = jQuery('#instant_step_3');
        var instant_test_step4 = jQuery('#instant_step_4');
        var instant_test_ddi = jQuery('#instant_test_ddi');
        var instant_test_error = jQuery('#instant_test_error');
        var instant_icon_top = jQuery('#instant_icon_button_top');
        var ajax_loader = jQuery('#ajax_loader');
        var captcha_img = jQuery('#captcha img');
        var captcha_img_src = captcha_img.attr('src');
        var instant_test_prefix = jQuery('#instant_test_prefix');
        
        // Function to reload captcha on click event
        function reload_captcha(captcha)
        {
            var captcha_old_src = captcha_img_src;
            var timestamp = new Date().getTime();
            var captcha_new_url = captcha_old_src+'?'+timestamp;
            
            return captcha_new_url;
        }
        
        captcha_img.bind('click', function()
        {
            // Call function to reload captcha and set new img url
            var new_url = reload_captcha(jQuery(this));
            jQuery(this).attr('src', new_url);
            //console.log('This captcha just reloaded to url: "'+jQuery(this).attr('src')+'"');
        });
        
        // Show instant_test_box when js is enabled
        instant_test_field.css('cursor', 'pointer').show().stop().bind('click', function()
        {
            if(!instant_test_field.hasClass('extended'))
            {
                //console.log('instant_test_field has no class "extended". Animation starts.');
                
                // Hide icon in top right
                instant_icon_top.fadeOut(200);
                
                instant_test_field.animate({bottom:0}, 1200, 'easeOutBounce', function(){
                    // Show cancel button in top left corner
                    instant_test_cancel.fadeIn(1200);
                    //console.log('cancel button should appear... now.');
                });
                
                instant_test_field.addClass('extended').css('cursor', 'default').removeClass('instant_test_box_hover');;
            }
        });
        
        instant_test_cancel.bind('click', function()
        {
            if(instant_test_field.hasClass('extended'))
            {
                //console.log('instant_test_field has class "extended". Roll in starts.');
                
                // Hide error text
                instant_test_error.fadeOut(300);
                
                // Show cancel button in top left corner
                instant_test_cancel.fadeOut('fast', function(){
                    instant_test_field.stop().animate({bottom:-255}, 900, 'easeOutBounce', function(){
                        instant_test_field.removeClass('extended').css('cursor', 'pointer').addClass('instant_test_box_hover');
                        
                        // Show icon in top right
                        instant_icon_top.fadeIn(300);
                    });
                });
                
                //console.log('cancel button should vanish... now.');
            }
        });
        
            
        instant_test_submit.live('click', function(event)
        {
            event.preventDefault();
            
            // Hide error text
            instant_test_error.fadeOut(300);
            
            // Remove mark error class and show all inputs in default state
            instant_test_cli.removeClass('mark_error');
            instant_test_destnum.removeClass('mark_error');
            instant_test_captcha.removeClass('mark_error');
            
            
            //console.log('instant test submit button clicked ...');
            
            // Define vars
            var prefix_value = instant_test_prefix.attr('title');
            var cli_value = instant_test_cli.val();
            
            var user_cli = cli_value;
            //console.log('prefix title value plus cli_value: '+prefix_value+cli_value);
            var user_destnum = instant_test_destnum.val();
            var user_captcha = instant_test_captcha.val();
            //console.log('instant_test_cli = "'+user_cli+'"\n'+'instant_test_destnum = "'+user_destnum+'"\n'+'instant_test_captcha = "'+user_captcha+'"\n')
            
            $request_url = server_url + "toolani_logic/functions/instant_test.php";	
            jQuery.ajax({
                type: "GET",
                dataType: 'json',
                url: $request_url,
                data: 'cli_prefix='+prefix_value+'&cli='+user_cli+'&destnum='+user_destnum+'&captcha_user='+user_captcha,
                
                beforeSend: function(response)
                {
                    //console.log('Sending Ajax Request ... Preparing data.\n Ajax loader gets faded in.')
                    ajax_loader.fadeIn(200);
                },
                
                success: function(response)
                {
                    //console.log('Ajax request success ... providing output');
                    //console.log(response);
                    
                    // Ajax loading image fadeout.
                    //console.log('Ajax Loader gets faded out.');
                    ajax_loader.fadeOut(200);
                    
                    if(response['error'])
                    {
                        // Check which field threw error and add a indication class to it
                        if(response['error']['error_1'])
                        {
                            instant_test_cli.addClass('mark_error');
                            // Show error
                            instant_test_error.fadeIn(200).html(response['error']['error_1']);
                        }
                        
                        if(response['error']['error_2'])
                        {
                            instant_test_destnum.addClass('mark_error');
                            // Show error
                            instant_test_error.fadeIn(200).html(response['error']['error_2']);
                        }
                        
                        if(response['error']['error_3'])
                        {
                            instant_test_captcha.addClass('mark_error');
                            // Show error
                            instant_test_error.fadeIn(200).html(response['error']['error_3']);
                        }
                        
                        instant_test_error.fadeIn(200).html(response['error']['error']);
                        
                    }
                    else if(response['ddi'])
                    {
                        // Set Step 4 content to ddi number
                        instant_test_ddi.html(response['ddi_show']);
                        
                        // Hide Step 3
                        instant_test_step1.fadeOut(300);
                        instant_test_step2.fadeOut(300);
                        instant_test_step3.fadeOut(300);
                        instant_test_step4.fadeIn(300);
                    }
                    
                    // Call function to reload captcha and set new img url
                    var new_url = reload_captcha(captcha_img);
                    captcha_img.attr('src', new_url);
                    //console.log('This captcha just reloaded to url: "'+captcha_img.attr('src')+'"');
                },
                
                error: function(XMLHttpRequest, textStatus, errorThrown)
                {
                },
                
                complete: function()
                {
                }
                
            });
        });
    }
}




function pb_modify_entry()
{	
	jQuery('.pb_edit_entry').live('click', function(event)
		{
			event.preventDefault();
			jQuery('.pb_help_overlay').fadeOut(); // fades out the help overlay with green arrows and description at step 2
			_pb_edit_entry(jQuery(this)); 
		});	

	jQuery('.pb_delete_entry').live('click', function(event)
		{	
			event.preventDefault();
			jQuery('.pb_help_overlay').fadeOut(); // fades out the help overlay with green arrows and description at step 2
			_pb_delete_entry(jQuery(this)); 
		});	
		
	jQuery('#javascript_add_pb_entry').live('click', function(event)
		{	
			event.preventDefault();
			jQuery('.pb_help_overlay').fadeOut(); // fades out the help overlay with green arrows and description at step 2
			_pb_add_entry(jQuery(this)); 
		});	

}

			function _pb_edit_entry($clicked_element)
			{
				$current_element = $clicked_element.parents('.pb_entry');
				$current_element.spotlight({
				opacity: .8,				//spotlight opacity
				speed: 400,					//animation speed
				color: '#000',				//spotlight colour
				animate: true,				//enable animation (if false 'speed' and 'easing' are irrelevant)
				exitEvent: ''
				});
				
				var $editing_form = jQuery('.pb_currently_editing').appendTo($current_element);
				var $oldname = $current_element.find('.pb_name');
				var $oldnumber = $current_element.find('.pb_real_number');
				var $newname = $editing_form.find("#edit_name");
				var $newnumber = $editing_form.find("#edit_number");
				var $height = $current_element.height() -30;
				var $not_needed = $current_element.find('.pb_sms');
				var $context_name = $current_element.find('.pb_infotext span:not(.pb_toolani_number)');
				var $country_connection = $current_element.find('.pb_rate');
				var $country_flag = $current_element.find('.pb_country');
				
				//hidden input fields with data
				var $data_target = $current_element.find('.pb_modify input[name=target]');
				var $data_ddi = $current_element.find('.pb_modify input[name=ddi]');
				var $data_name = $current_element.find('input[name=name]');
							
				
				if(jQuery('.pb_sms').filter(":hidden").length > 0)
				{
					jQuery('.pb_sms').css("display","block");	
				}
				
				$newname.val($oldname.text());
				$newnumber.val($oldnumber.text());
								
				
				
				$not_needed.fadeOut(400);
				$editing_form.css({height:$height}).fadeIn(400);
				
				$editing_form.find("#edit_done").unbind('click').bind('click', function()
				{	
					var $button = jQuery(this);
					
					// if something was changed make server request
					if($newnumber.val() != $oldnumber.text() || $newname.val() != $oldname.text())
					{	
						$encode_target = encodeURIComponent($newnumber.val());
						$encode_name = encodeURIComponent($newname.val());
					
						$request_url = server_url + "toolani_logic/functions/phonebook_ajax.php";	
						jQuery.ajax({
							type: "POST",
							dataType: 'json',
							url: $request_url,
							data: "Ajax=true&Update=true&target="+$encode_target +"&name="+$encode_name+"&ddi="+$data_ddi.val(),
							
							beforeSend: function(response)
							{
								$button.fadeOut(400);
							},
							
							success: function(response)
							{	
								//remove errorbox
								var $currenterrorbox = jQuery('.js_errorbox');
								
								if ($currenterrorbox.length > 0 )
								{
									$currenterrorbox.slideUp(400)
								}
									
												
								if(response.response == 'true')
								{
									//update all elements that need change
									$oldname.html(response.name); 					// span with name
									$data_name.val(response.name);					// hidden name
									$context_name.html(response.name);				// name within context
														
									$oldnumber.html(response.target_internal);		// span with number
									$data_target.val(response.target_internal);		// hidden number
									
									$country_connection.html(response.country + ' <span>' + response.tarif + '</span>');
									$country_flag.find('img').attr('src',server_url + "/application/images/icons/flags16/"+response.country_code+".png");
						
								}
								else if(response.response == 'false')
								{		
									var $add_number_box = jQuery("#add_number_box");
									
									
									response.error = arrayUniq(response.error);
									response.error = response.error.join(" <br/> ");
										
									jQuery('<div><span class="error">'+response.error+'</span></div>')
									.addClass('box box_medium rounded js_errorbox')
									.css('display','none')
									.insertBefore($add_number_box)
									.slideDown(400);
								}
							},	
							
							error: function(XMLHttpRequest, textStatus, errorThrown)
							{
								
							},
							
							complete: function()
							{
								_pb_hide_overlay($editing_form, $not_needed, $button);
							}
							
						});
						
					}
					else
					{
					_pb_hide_overlay($editing_form, $not_needed, $button);
					}

					return false;
				});
				
				
			}
			
			function _pb_hide_overlay($editing_form, $not_needed, $button)
			{
				//remove overlay
				jQuery('#spotlight').animate({opacity:"0"}, 400, function()
				{
					$current_element.css({zIndex:1});
					jQuery(this).remove();
					$button.css("display","block");
				});
				$editing_form.fadeOut(400);
				$not_needed.fadeIn(400);
				
			}
			
			$sending_data = false;
			$loading_div = jQuery('<span class="number_box_loading"></span>').css('opacity',0).appendTo('#add_number_box');
			
			function _pb_add_entry($clicked_element)
			{
				var $currenterrorbox = jQuery('.js_errorbox');
								
								if ($currenterrorbox.length > 0 )
								{
									$currenterrorbox.slideUp(400)
								}
			
				var $current_element = $clicked_element.parents('#add_number_box');
				var $data_target = $current_element.find('input[name=target]');
				var $data_name = $current_element.find('input[name=name]');
				var $newbox = jQuery('.pb_emptybox>.box');
				var $phonebook_entries = jQuery('#phonebook_entries');
				
				
				
				
				if($data_target.val() != "" && $sending_data == false)
				{
					$request_url = server_url + "toolani_logic/functions/phonebook_ajax.php";
							
							$encode_target = encodeURIComponent($data_target.val());
							$encode_name = encodeURIComponent($data_name.val());
					
							jQuery.ajax({
							type: "POST",
							dataType: 'json',
							url: $request_url,
							data: "Ajax=true&Send=true&target="+$encode_target+"&name="+$encode_name,
							
							beforeSend: function(response)
							{
								 $loading_div.stop().animate({opacity:1});
								 $sending_data = true;
							},
							
							error: function(XMLHttpRequest, textStatus, errorThrown)
							{	
								
								$sending_data = false;
								$loading_div.stop().animate({opacity:0});
								$data_target.val('');
								$data_name.val('');
								
							},
							
							success: function(response)
							{		
								
								$loading_div.stop().animate({opacity:0});
								$data_target.val('');
								$data_name.val('');
								$sending_data = false;
								
								if(response.response == 'true')
								{
									var $box = $newbox.clone();
									var $name = $box.find('.pb_name, .pb_infotext span:not(.pb_toolani_number)');
									var $number_original = $box.find('.pb_real_number');
									var $ddi_show = $box.find('.pb_toolani_number');
									var $flag = $box.find('.pb_country');
									var $rate = $box.find('.pb_rate');
									
									var $ddi_edit_ddi = $box.find('input[name=ddi]');
									var $name_edit_name= $box.find('input[name=name]');
									var $name_edit_target = $box.find('input[name=target]');
									
									
									$ddi_edit_ddi.val(response.ddi);
									$name_edit_name.val(response.name);
									$name_edit_target.val(response.target_internal);
									
									$name.html(response.name);
									$number_original.html(response.target_internal);
									$ddi_show.html(response.ddi_show);
									$flag.find('img').attr('src',server_url + "/application/images/icons/flags16/"+response.country_code+".png");
									$rate.html(response.country + ' <span>' + response.tarif + '</span>');
									
									$box.clone().prependTo($phonebook_entries).css('display','none').slideDown(400);
									
								}
								else if(response.response == 'false')
								{
									var $add_number_box = jQuery("#add_number_box");
									
									
									response.error = arrayUniq(response.error);
									response.error = response.error.join(" <br/> ");
										
									jQuery('<div><span class="error">'+response.error+'</span></div>')
									.addClass('box box_medium rounded js_errorbox')
									.css('display','none')
									.insertBefore($add_number_box)
									.slideDown(400);
								}
							}
					})
				}
				
			}
			
			
			function _pb_delete_entry($clicked_element)
			{
				var $current_element = $clicked_element.parents('.pb_entry');
				var $data_ddi = $current_element.find('.pb_modify input[name=ddi]');
				var $currenterrorbox = jQuery('.js_errorbox');
								
								if ($currenterrorbox.length > 0 )
								{
									$currenterrorbox.slideUp(400)
								}
				
				$request_url = server_url + "toolani_logic/functions/phonebook_ajax.php";
					
							jQuery.ajax({
							type: "POST",
							dataType: 'json',
							url: $request_url,
							data: "Ajax=true&Delete=true&ddi="+$data_ddi.val()
					})
			
				$clicked_element.parents('.pb_entry').animate({opacity:0},400).animate({height:0},400, function(){
					jQuery(this).css({display:"none"});
				});
			}



function pb_show_modify()
{	

	jQuery('.pb_entry').live('mouseover', function()
	{
		jQuery(this).find('.pb_modify').show(0);
	});
	
	jQuery('.pb_entry').live('mouseout', function()
	{
		jQuery(this).find('.pb_modify').hide(0);
	});
}

//array function, removed duplicate entries, copied from "http://markmail.org/message/t436acyrpted3sze#query:jquery remove duplicate entries from array"
function arrayUniq(a) { var rval = [a[0]]; var o = a[0]; for( var i = 1; i < a.length; i++ ) if( a[i] != o ) { rval.push(a[i]); o = a[i]; } return rval; } 

function resend_mail()
{	
	$resend_email_link = jQuery("#resend_email_link");
	$registration_no_mail = jQuery("#registration_no_mail");
	
	if($registration_no_mail.length >= 1)
	{	
		$resend_email_link.click(function()
		{	
			$resend_email_link.css("visibility","hidden");
			$height = $registration_no_mail.height();
			$registration_no_mail.wrap('<div id="no_mail_ie_helper"></div>');
			$helper = jQuery("#no_mail_ie_helper");
			
			
			$helper.css({float:"left", width:"100%"}).animate({height:$height}, 400, function(){
				$registration_no_mail.fadeIn(400);
			});
			return false;
		});	
	}
}

function rounded_corner($element)
{	
	if((jQuery.browser.msie && jQuery.browser.version >= 7) || jQuery.browser.opera)
	{
		jQuery($element).each(function()
		{
			if(!jQuery(this).is("#teaser_video")) // video outline exception, otherwise it wont work
			{
				jQuery(this).append('<div class="tl"></div><div class="tr"></div><div class="bl"></div><div class="br"></div>');
			}	
		});
	}
}

function lightbox()
{
	jQuery("a[rel^='prettyPhoto'], a[rel^='lightbox']").prettyPhoto();
}


function show_help()
{
	var items = jQuery(".tree_item");
	
	items.each(
		function()
		{
			var parent = jQuery(this).parent();
			parent.children('div').hide();
			
			jQuery(this).css({cursor:"pointer"});
			
			jQuery(this).bind('click' ,
				function()
				{
					parent.children('div').slideToggle(323);
					parent.siblings().children('div').hide(323);
				}
			);
		}
	);
}


/*  SMS Counter  for MA  */

// when textarea is filled with text, a counter runs down from 160 to indicate the end of the sms
function SMS_counter()
{
    // handler is saved into variable to prevent DOM search every call
    $textarea = jQuery('#sms_textarea');
    var max = jQuery('#sms_counter').val();
	
    // textarea is bound to the following events
    $textarea.bind("click keydown keyup focus change", change_number);
	
	function change_number()
	{
		// defining variables  max = count of maximum characters in one sms 
		// wert = amount of characters currently in textarea
		var wert;            
		
		// wert is defined by the maximum characters minus the characters in the textarea
		wert = max-$textarea.val().length;
		
		// if wert below zero, prohibit any further input
		if (wert < 0)
		{
			$textarea.val($textarea.val().substring(0,max));
			wert = max-$textarea.val().length;
			jQuery('#sms_counter').val(wert);
		}
		else
		{
			// if counter is above zero, allow input
			jQuery('#sms_counter').val(wert);
		}
	}
}


/*  SMS Number adapt   */

function SMS_Number_adapt()
{

// when number is selected from select box, it is automatically written to the number field

// first hide the div containing the submit button
    jQuery('#number_entry').html('');
    
// take the variable from the select box and on change write it to the number field
    //store the select box in variable "sms_select"
    $sms_select = jQuery('#sms_receiver_phonebook');
    
    sms_number_adapt_onload();
    
    // bind event and action to sms_select
    $sms_select.bind("change", sms_number_adapt_onload);
}

function sms_number_adapt_onload($sms_select, $number_field){
	//store the select box in variable "sms_select"
    $sms_select = jQuery('#sms_receiver_phonebook');
    
    // store the number field in variable "number_field"
    $number_field = jQuery('#sms_receiver_nr');
    
	// store the value of the selected number in the select box into variable "number"
	$number = $sms_select.val();
	
	// write the number in the number field
	$number_field.val($number);
}


/*  WLAN Model<->Brand switch   */

function Wlan_select_switch()
{

// when brand is chosen from first list, the model list should activate itself and show models accordingly

// hide the firt submit button
    jQuery('#jquery_hide_me').hide();
    
// read out the value of the first select box if CHANGED. write the models list according to it
    //store the select box in variable "choose_brand"
    $brand_select = jQuery('#choose_brand');
    
    // store the number field in variable "choose_model"
    $model_select = jQuery('#choose_model');
    
    // bind event and action to the Brand selection
    $brand_select.bind("change", function(){
            
		// store the value of the selected number in the select box into variable "brand"
		$brand = $brand_select.val();
		
		// enable model form
		jQuery($model_select).removeAttr("disabled");
		jQuery('#model_submit').removeAttr("disabled");
		
		// store default value of model select for later use
		$default_option_text = jQuery('#choose_model option:first').text();
		$default_option_val = jQuery('#choose_model option:first').val();
		
		// according to selected brand, alter the classes of the option boxes.
		if (jQuery('#choose_model option').hasClass('model_list_visible')) 
		{
			// hide all options that are visible atm
			jQuery('#choose_model option').removeClass('model_list_visible').addClass('model_list_invisible');
		}
		
		// store all options which go along with the brand in variable
		$brand_options = jQuery($model_select).find('option.'+$brand);
		
		// show all those options
		jQuery($brand_options).removeClass('model_list_invisible').addClass('model_list_visible');
		
		// store the brand in a hidden field, in order to pass it to post once form is submitted
		jQuery('#hidden_model').val($brand);
		
		// Switch the selected option field to default when changing brands
		jQuery('#choose_model option:selected').text($default_option_text);
		jQuery('#choose_model option:selected').val($default_option_val);
    });
}




/*  Disable login button when checkbox not checked   */

function Disable_send()
{
	// Define variables
	var button = jQuery('.js_disabled');
	var agb_error = jQuery('.agb_error').addClass('error');
	var checkbox = jQuery('#register_agb_accept');
	
	// On button click prevent DOM sending, when checkbox isnt checked
	button.bind("click", function()
	{
		if (!checkbox.attr('checked'))
		{
			
			agb_error.css("display","block");
			return false;
			
		}
		else
		{
			agb_error.css("display","none");
		}
	});
}


/* Don't send CC Request to interface, when form fields of CC form are empty */
function empty_cc_send()
{
    console.log('empty_cc_send called ...');
    // Define variables
    var card_holder, card_number, card_cvc, card_submit, card_error;
    
    card_holder = jQuery('#card_holder');
    card_number = jQuery('#card_number');
    card_cvc    = jQuery('#topup_cvc');
    card_submit = jQuery('#cc_submit');
    card_error  = jQuery('#card_error');
    
    // Check form field values on form submit -> prevent sending if emtpy
    card_submit.bind('click', function()
        {
            console.log('Click on cc-submit detected ... ');
            if(!card_holder.val() || !card_number.val() || !card_cvc.val())
            {
                console.log('One of the fields does not have the right value ... preventing submit');
                card_error.css({
                    'display': 'block'
                    });
                return false;
            }
            else
            {
                console.log('CC_Empty says: all is fine. submit the form.');
                card_error.css('display','none');
            }
        });
}


/* Disable form field submit, when textfield is emtpy */
function Contact_content_check()
{
	// save textfield and button to variable
	var form_text_field1 = jQuery('#kontaktform_tnachricht');
	var form_text_field2 = jQuery('#kontaktform_iname');
	var form_text_field3 = jQuery('#kontaktform_iemail');

	var form_button = jQuery('#contact_submit');

	var contact_error1 = jQuery('#contact_error1');
	var contact_error2 = jQuery('#contact_error2');
	var contact_error3 = jQuery('#contact_error3');
	
	// when textfield is empty send "false" as a button return
	form_button.bind('click', function(){
			
			var error_true = 0;
			
			if (form_text_field1.val() == "")
			{
				contact_error1.css("display","block");
				error_true = 1;
			} else { contact_error1.css("display","none"); }
			
				
			if (form_text_field2.val() == "")
			{
				contact_error2.css("display","block");
				error_true = 1;
			} else { contact_error2.css("display","none"); }
			
			if (form_text_field3.val() == "")
			{
				contact_error3.css("display","block");
				error_true = 1;
			} else { contact_error3.css("display","none"); }
			
			if (error_true != 0)
			{
				return false;
			}
	});
	
}


function Language_Dropdown()
{
	// get the submit button and hide him
	var language_submit = jQuery('.header_language_submit');
	language_submit.hide();
	//console.log('language submit gets hidden ...');
	
	// use the selectbox-plugin on selectbox
	var selectbox = jQuery('#language_select_dropdown');
	selectbox.selectbox();
	//console.log('selectbox gets processed by selectbox plugin ...');
	
	// Save the hidden field which is read out by php
	var language_handler = jQuery('#language_handler');
	//console.log('language handler gets declared ...');
	
	// Select form
	var language_form = jQuery('#language_dropdown_form');
	
	// Select the input field generated by selectbox()
	var input_field = jQuery('#language_select_dropdown_input');
	
	// Select the substition for the select box (an ul)
	var substi_li = jQuery('#language_select_dropdown_container ul li');
	
	// on click of the li tag (produced through selectbox plugin) the form should be filled with the new value and then submitted
    substi_li.bind('click', function(){
        // Get the value from the id of the clicked element
        li_this = jQuery(this);
        
        li_value = li_this.attr('id').split('_');
        li_value = li_value[li_value.length];
        
        language_handler.val(li_value);
        //console.log('The value of language handler is \"'+language_handler.val()+'\"');
        language_form.submit();
	});
}

// Function to check preferences number input and displaying info box of eplus
function eplus_info_show_preferences()
{
	if (jQuery('.preferences_input').length > 0)
	{
		// create dialin-matching-number-array
		var matching_dialin = eplus_matching_array;
		//console.log("matching_dialin is ..."+matching_dialin);
		
		// get eplus warning field
		var eplus_warning = jQuery('.eplus_overlay');
		//console.log("eplus_warning is ..."+eplus_warning);
		
		// get number input
		var number_input = jQuery('.number_input');
		//console.log("number_input is ..."+number_input);
		
		// get hidden input field (to verify javascript active)
		var eplus_hidden_check = jQuery('#eplus_hidden_check');
		//console.log("eplus_hidden_check is ..."+eplus_hidden_check);
		
		// get number prefix
		var number_prefix = jQuery('.prefix').eq(1).text();
		//console.log("number_prefix is ..."+number_prefix);
		
		// replace the prefix's zero with nothing
		number_prefix = number_prefix.replace(/\+/, '');
		//console.log("number_prefix is ..."+number_prefix);
		
		number_input.bind('keyup blur', function()
		{
			//console.log("called keyup or blur event, showing eplus overlay");
			
			var number_input_value = jQuery(this).val();
			//console.log("number_input_value is ..."+number_input_value);
			
			jQuery.each(matching_dialin, function(){
					// regex input to match inconsistencies
					number_input_value = number_input_value.replace(/[\D]/g, '');
					number_input_value = number_input_value.replace(/^0+/, '');
					
					// add dial in to phonenumber
					number_user_input = number_prefix + number_input_value;
					
					
					if (this == number_user_input)
					{
						eplus_warning.fadeIn();
						eplus_hidden_check.val('checked');
					}
			});
		});
	}
}



// Register Country Switch, to adapt the dial in code to the prefix field

function Country_number_adapt()
{
    //save SELECT BOX into var
    country_select = jQuery('#register_country_selection');
    
    //save PREFIX_display and HIDDEN INPUT 'Prefix' into var (where number should be written)
    phone_prefix_display = jQuery('.register_number_prefix');
    
    //get value of country_select
    country_select_value = jQuery('#register_country_selection :selected').attr('title');
    
    //change value of PREFIX_display and HIDDEN INPUT 'Prefix'
    phone_prefix_display.val(country_select_value);
    
    // binding change event to select box
    country_select.bind("change", function()
        {
            //get value of country_select
            country_select_value = jQuery('#register_country_selection :selected').attr('title');
            
            //change value of PREFIX_display and HIDDEN INPUT 'Prefix'
            phone_prefix_display.val(country_select_value);
            
        });
}






/*
 * jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/
*/

// t: current time, b: begInnIng value, c: change In value, d: duration
jQuery.easing['jswing'] = jQuery.easing['swing'];

jQuery.extend( jQuery.easing,
{
	def: 'easeOutQuad',
	swing: function (x, t, b, c, d) {
		//alert(jQuery.easing.default);
		return jQuery.easing[jQuery.easing.def](x, t, b, c, d);
	},
	easeInQuad: function (x, t, b, c, d) {
		return c*(t/=d)*t + b;
	},
	easeOutQuad: function (x, t, b, c, d) {
		return -c *(t/=d)*(t-2) + b;
	},
	easeInOutQuad: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t + b;
		return -c/2 * ((--t)*(t-2) - 1) + b;
	},
	easeInCubic: function (x, t, b, c, d) {
		return c*(t/=d)*t*t + b;
	},
	easeOutCubic: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t + 1) + b;
	},
	easeInOutCubic: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t + b;
		return c/2*((t-=2)*t*t + 2) + b;
	},
	easeInQuart: function (x, t, b, c, d) {
		return c*(t/=d)*t*t*t + b;
	},
	easeOutQuart: function (x, t, b, c, d) {
		return -c * ((t=t/d-1)*t*t*t - 1) + b;
	},
	easeInOutQuart: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t*t + b;
		return -c/2 * ((t-=2)*t*t*t - 2) + b;
	},
	easeInQuint: function (x, t, b, c, d) {
		return c*(t/=d)*t*t*t*t + b;
	},
	easeOutQuint: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t*t*t + 1) + b;
	},
	easeInOutQuint: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;
		return c/2*((t-=2)*t*t*t*t + 2) + b;
	},
	easeInSine: function (x, t, b, c, d) {
		return -c * Math.cos(t/d * (Math.PI/2)) + c + b;
	},
	easeOutSine: function (x, t, b, c, d) {
		return c * Math.sin(t/d * (Math.PI/2)) + b;
	},
	easeInOutSine: function (x, t, b, c, d) {
		return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
	},
	easeInExpo: function (x, t, b, c, d) {
		return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
	},
	easeOutExpo: function (x, t, b, c, d) {
		return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
	},
	easeInOutExpo: function (x, t, b, c, d) {
		if (t==0) return b;
		if (t==d) return b+c;
		if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
		return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
	},
	easeInCirc: function (x, t, b, c, d) {
		return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
	},
	easeOutCirc: function (x, t, b, c, d) {
		return c * Math.sqrt(1 - (t=t/d-1)*t) + b;
	},
	easeInOutCirc: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b;
		return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b;
	},
	easeInElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
	},
	easeOutElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
	},
	easeInOutElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d/2)==2) return b+c;  if (!p) p=d*(.3*1.5);
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
		return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;
	},
	easeInBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		return c*(t/=d)*t*((s+1)*t - s) + b;
	},
	easeOutBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
	},
	easeInOutBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158; 
		if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
		return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
	},
	easeInBounce: function (x, t, b, c, d) {
		return c - jQuery.easing.easeOutBounce (x, d-t, 0, c, d) + b;
	},
	easeOutBounce: function (x, t, b, c, d) {
		if ((t/=d) < (1/2.75)) {
			return c*(7.5625*t*t) + b;
		} else if (t < (2/2.75)) {
			return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
		} else if (t < (2.5/2.75)) {
			return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
		} else {
			return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
		}
	},
	easeInOutBounce: function (x, t, b, c, d) {
		if (t < d/2) return jQuery.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b;
		return jQuery.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b;
	}
});

(function($) {

	$.fn.spotlight = function(options) {
		// Default settings
		settings = $.extend({}, {
			opacity: .5,
			speed: 400,
			color: '#333',
			animate: true,
			easing: '',
			exitEvent: 'click',
			onShow: function(){},
			onHide: function(){}
		}, options);
		
	  // Do a compatibility check
	  //if(!jQuery.support.opacity) return false;
		if(jQuery.browser.msie && jQuery.browser.version < 8) return false;	
		
		if($('#spotlight').size() == 0){
			// Add the overlay div
			$('body').append('<div id="spotlight"></div>');
			
			// Get our elements
			var element = $(this);
			var spotlight = $('#spotlight');
			
			// Set the CSS styles
			spotlight.css({
				'position':'fixed', 
				'background':settings.color, 
				'opacity':'0', 
				'top':'0px', 
				'left':'0px', 
				'height':'100%', 
				'width':'100%', 
				'z-index':'9998'
			});
			
			// Set element CSS
			var currentPos = element.css('position');
			if(currentPos == 'static'){
				element.css({'position':'relative', 'z-index':'9999'});
			} else {
				element.css('z-index', '9999');
			}
			
			// Fade in the spotlight
			if(settings.animate){
				spotlight.animate({opacity: settings.opacity}, settings.speed, settings.easing, function(){
					// Trigger the onShow callback
					settings.onShow.call(this);
				});
			} else {
				spotlight.css('opacity', settings.opacity);
				// Trigger the onShow callback
				settings.onShow.call(this);
			}
			
			// Set up click to close
			spotlight.live(settings.exitEvent, function(){
				if(settings.animate){
					spotlight.animate({opacity: 0}, settings.speed, settings.easing, function(){
						if(currentPos == 'static') element.css('position', 'static');
						element.css('z-index', '1');
						$(this).remove();
						// Trigger the onHide callback
						settings.onHide.call(this);
					});
				} else {
					spotlight.css('opacity', '0');
					if(currentPos == 'static') element.css('position', 'static');
					element.css('z-index', '1');
					$(this).remove();
					// Trigger the onHide callback
					settings.onHide.call(this);
				}
			});
		}

		// Returns the jQuery object to allow for chainability.  
		return this;
	};

})(jQuery);


/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

/**
 * Flash (http://jquery.lukelutman.com/plugins/flash)
 * A jQuery plugin for embedding Flash movies.
 * 
 **/ 
(function(){
	
var $$;

$$ = jQuery.fn.flash = function(htmlOptions, pluginOptions, replace, update) {
	
	// Set the default block.
	var block = replace || $$.replace;
	
	// Merge the default and passed plugin options.
	pluginOptions = $$.copy($$.pluginOptions, pluginOptions);
	
	// Detect Flash.
	if(!$$.hasFlash(pluginOptions.version)) {
		// Use Express Install (if specified and Flash plugin 6,0,65 or higher is installed).
		if(pluginOptions.expressInstall && $$.hasFlash(6,0,65)) {
			// Add the necessary flashvars (merged later).
			var expressInstallOptions = {
				flashvars: {  	
					MMredirectURL: location,
					MMplayerType: 'PlugIn',
					MMdoctitle: jQuery('title').text() 
				}					
			};
		// Ask the user to update (if specified).
		} else if (pluginOptions.update) {
			// Change the block to insert the update message instead of the flash movie.
			block = update || $$.update;
		// Fail
		} else {
			// The required version of flash isn't installed.
			// Express Install is turned off, or flash 6,0,65 isn't installed.
			// Update is turned off.
			// Return without doing anything.
			return this;
		}
	}
	
	// Merge the default, express install and passed html options.
	htmlOptions = $$.copy($$.htmlOptions, expressInstallOptions, htmlOptions);
	
	// Invoke $block (with a copy of the merged html options) for each element.
	return this.each(function(){
		block.call(this, $$.copy(htmlOptions));
	});
	
};

$$.copy = function() {
	var options = {}, flashvars = {};
	for(var i = 0; i < arguments.length; i++) {
		var arg = arguments[i];
		if(arg == undefined) continue;
		jQuery.extend(options, arg);
		// don't clobber one flash vars object with another
		// merge them instead
		if(arg.flashvars == undefined) continue;
		jQuery.extend(flashvars, arg.flashvars);
	}
	options.flashvars = flashvars;
	return options;
};

$$.hasFlash = function() {
	// look for a flag in the query string to bypass flash detection
	if(/hasFlash\=true/.test(location)) return true;
	if(/hasFlash\=false/.test(location)) return false;
	var pv = $$.hasFlash.playerVersion().match(/\d+/g);
	var rv = String([arguments[0], arguments[1], arguments[2]]).match(/\d+/g) || String($$.pluginOptions.version).match(/\d+/g);
	for(var i = 0; i < 3; i++) {
		pv[i] = parseInt(pv[i] || 0);
		rv[i] = parseInt(rv[i] || 0);
		// player is less than required
		if(pv[i] < rv[i]) return false;
		// player is greater than required
		if(pv[i] > rv[i]) return true;
	}
	// major version, minor version and revision match exactly
	return true;
};

$$.hasFlash.playerVersion = function() {
	// ie
	try {
		try {
			// avoid fp6 minor version lookup issues
			// see: http://blog.deconcept.com/2006/01/11/getvariable-setvariable-crash-internet-explorer-flash-6/
			var axo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash.6');
			try { axo.AllowScriptAccess = 'always';	} 
			catch(e) { return '6,0,0'; }				
		} catch(e) {}
		return new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version').replace(/\D+/g, ',').match(/^,?(.+),?$/)[1];
	// other browsers
	} catch(e) {
		try {
			if(navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin){
				return (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]).description.replace(/\D+/g, ",").match(/^,?(.+),?$/)[1];
			}
		} catch(e) {}		
	}
	return '0,0,0';
};

$$.htmlOptions = {
	height: 240,
	flashvars: {},
	pluginspage: 'http://www.adobe.com/go/getflashplayer',
	src: '#',
	type: 'application/x-shockwave-flash',
	width: 320		
};


$$.pluginOptions = {
	expressInstall: false,
	update: true,
	version: '6.0.65'
};

$$.replace = function(htmlOptions) {
	this.innerHTML = '<div class="alt">'+this.innerHTML+'</div>';
	jQuery(this)
		.addClass('flash-replaced')
		.prepend($$.transform(htmlOptions));
};
$$.update = function(htmlOptions) {
	var url = String(location).split('?');
	url.splice(1,0,'?hasFlash=true&');
	url = url.join('');
	var msg = '<p>This content requires the Flash Player. <a href="http://www.adobe.com/go/getflashplayer">Download Flash Player</a>. Already have Flash Player? <a href="'+url+'">Click here.</a></p>';
	this.innerHTML = '<span class="alt">'+this.innerHTML+'</span>';
	jQuery(this)
		.addClass('flash-update')
		.prepend(msg);
};

function toAttributeString() {
	var s = '';
	for(var key in this)
		if(typeof this[key] != 'function')
			s += key+'="'+this[key]+'" ';
	return s;		
};

function toFlashvarsString() {
	var s = '';
	for(var key in this)
		if(typeof this[key] != 'function')
			s += key+'='+encodeURIComponent(this[key])+'&';
	return s.replace(/&$/, '');		
};

$$.transform = function(htmlOptions) {
	htmlOptions.toString = toAttributeString;
	if(htmlOptions.flashvars) htmlOptions.flashvars.toString = toFlashvarsString;
	return '<embed ' + String(htmlOptions) + '/>';		
};

if (window.attachEvent) {
	window.attachEvent("onbeforeunload", function(){
		__flash_unloadHandler = function() {};
		__flash_savedUnloadHandler = function() {};
	});
}
	
})();

function popup (url) {
 fenster = window.open(url, "Popupfenster", "width=400,height=300,resizable=yes");
 fenster.focus();
 return false;
}





/*
 * jQuery selectbox plugin
 *
 * Copyright (c) 2007 Sadri Sahraoui (brainfault.com)
 * Licensed under the GPL license and MIT:
 *   http://www.opensource.org/licenses/GPL-license.php
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * The code is inspired from Autocomplete plugin (http://www.dyve.net/jquery/?autocomplete)
 *
 * Revision: $Id$
 * Version: 0.5
 * 
 * Changelog :
 *  Version 0.5 
 *  - separate css style for current selected element and hover element which solve the highlight issue 
 *  Version 0.4
 *  - Fix width when the select is in a hidden div   @Pawel Maziarz
 *  - Add a unique id for generated li to avoid conflict with other selects and empty values @Pawel Maziarz
 */
jQuery.fn.extend({
	selectbox: function(options) {
		return this.each(function() {
			new jQuery.SelectBox(this, options);
		});
	}
});


/* pawel maziarz: work around for ie logging */
if (!window.console) {
	var console = {
		log: function(msg) { 
	 }
	}
}
/* */

jQuery.SelectBox = function(selectobj, options) {
	
	var opt = options || {};
	opt.inputClass = opt.inputClass || "selectbox";
	opt.containerClass = opt.containerClass || "selectbox-wrapper";
	opt.hoverClass = opt.hoverClass || "current";
	opt.currentClass = opt.selectedClass || "selected"
	opt.debug = opt.debug || false;
	
	var elm_id = selectobj.id;
	var active = -1;
	var inFocus = false;
	var hasfocus = 0;
	//jquery object for select element
	var select = jQuery(selectobj);
	// jquery container object
	var container = setupContainer(opt);
	//jquery input object 
	var input = setupInput(opt);
	// hide select and append newly created elements
	select.hide().before(input).before(container);
	
	
	init();
	
	input
	.click(function(){
    if (!inFocus) {
		  container.toggle();
		}
	})
	.focus(function(){
	   if (container.not(':visible')) {
	       inFocus = true;
	       container.show();
	   }
	   input.addClass('language_select_dropdown_input_clicked');

	})
	.keydown(function(event) {	   
		switch(event.keyCode) {
			case 38: // up
				event.preventDefault();
				moveSelect(-1);
				break;
			case 40: // down
				event.preventDefault();
				moveSelect(1);
				break;
			//case 9:  // tab 
			case 13: // return
				event.preventDefault(); // seems not working in mac !
				jQuery('li.'+opt.hoverClass).trigger('click');
				break;
			case 27: //escape
			  hideMe();
			  break;
		}
	})
	.blur(function() {
		if (container.is(':visible') && hasfocus > 0 ) {
			if(opt.debug) console.log('container visible and has focus')
		} else {
			hideMe();	
		}
        input.removeClass('language_select_dropdown_input_clicked');

	});


	function hideMe() { 
		hasfocus = 0;
		container.hide(); 
	}
	
	function init() {
		container.append(getSelectOptions(input.attr('id'))).hide();
		var width = input.css('width');
		container.width(width);
    }
	
	function setupContainer(options) {
		var container = document.createElement("div");
		container = jQuery(container);
		container.attr('id', elm_id+'_container');
		container.addClass(options.containerClass);
		
		return container;
	}
	
	function setupInput(options) {
		var input = document.createElement("input");
		var input = jQuery(input);
		input.attr("id", elm_id+"_input");
		input.attr("type", "text");
		input.addClass(options.inputClass);
		input.attr("autocomplete", "off");
		input.attr("readonly", "readonly");
		input.attr("tabIndex", select.attr("tabindex")); // "I" capital is important for ie
		
		return input;	
	}
	
	function moveSelect(step) {
		var lis = jQuery("li", container);
		if (!lis) return;

		active += step;

		if (active < 0) {
			active = 0;
		} else if (active >= lis.size()) {
			active = lis.size() - 1;
		}

		lis.removeClass(opt.hoverClass);

		jQuery(lis[active]).addClass(opt.hoverClass);
	}
	
	function setCurrent() {	
		var li = jQuery("li."+opt.currentClass, container).get(0);
		var ar = (''+li.id).split('_');
		var el = ar[ar.length-1];
		select.val(el);
		input.val(jQuery(li).html());
		return true;
	}
	
	// select value
	function getCurrentSelected() {
		return select.val();
	}
	
	// input value
	function getCurrentValue() {
		return input.val();
	}
	
	function getSelectOptions(parentid) {
		var select_options = new Array();
		var ul = document.createElement('ul');
		select.children('option').each(function() {
			var li = document.createElement('li');
			li.setAttribute('id', parentid + '_' + jQuery(this).val());
			
			li.innerHTML = jQuery(this).html();
			if (jQuery(this).is(':selected')) {
				input.val(jQuery(this).html());
				jQuery(li).addClass(opt.currentClass);
			}
			ul.appendChild(li);
			jQuery(li)
			.mouseover(function(event) {
				hasfocus = 1;
				if (opt.debug) console.log('over on : '+this.id);
				jQuery(event.target, container).addClass(opt.hoverClass);
			})
			.mouseout(function(event) {
				hasfocus = -1;
				if (opt.debug) console.log('out on : '+this.id);
				jQuery(event.target, container).removeClass(opt.hoverClass);
			})
			.click(function(event) {
			  var fl = jQuery('li.'+opt.hoverClass, container).get(0);
				if (opt.debug) console.log('click on :'+this.id);
				jQuery('li.'+opt.currentClass).removeClass(opt.currentClass); 
				jQuery(this).addClass(opt.currentClass);
				setCurrent();
				hideMe();
			});
		});
		return ul;
	}
	
};















